<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <!-- 筛选条件 -->
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="4.8">
            <el-form-item label="会员">
              <el-select
                v-model="query.memberIds"
                placeholder="请选择会员"
                multiple
                filterable
                remote
                :remote-method="remoteSearchMembers"
                :loading="memberLoading"
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="member in memberOptions"
                  :key="member.id"
                  :label="member.label"
                  :value="member.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="是否升医美">
              <el-select
                v-model="query.hasUpgradeMedicalBeauty"
                placeholder="请选择"
                clearable
                :style='{"width":"100%"}'>
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="是否升科美">
              <el-select
                v-model="query.hasUpgradeTechBeauty"
                placeholder="请选择"
                clearable
                :style='{"width":"100%"}'>
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="是否升生美">
              <el-select
                v-model="query.hasUpgradeLifeBeauty"
                placeholder="请选择"
                clearable
                :style='{"width":"100%"}'>
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="当前部门月份">
              <el-date-picker 
                v-model="query.month" 
                type="month" 
                value-format="yyyyMM"
                format="yyyy年MM月"
                placeholder="请选择当前部门月份"
                :style='{"width":"100%"}'
                @change="handleMonthChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="组织类型">
              <el-select
                v-model="query.organizationType"
                placeholder="请选择组织类型"
                filterable
                clearable
                @change="handleOrganizationTypeChange"
                :style='{"width":"100%"}'>
                <el-option label="事业部" value="事业部"></el-option>
                <el-option label="科技部" value="科技部"></el-option>
                <el-option label="教育部" value="教育部"></el-option>
                <el-option label="大项目部" value="大项目部"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="部门">
              <el-select
                v-model="query.departmentId"
                placeholder="请选择部门"
                filterable
                clearable
                @change="handleDepartmentChange"
                :style='{"width":"100%"}'>
                <el-option
                  v-for="dept in departmentOptions"
                  :key="dept.Id || dept.id"
                  :label="dept.FullName || dept.fullName"
                  :value="dept.Id || dept.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店">
              <el-select
                v-model="query.storeIds"
                placeholder="请选择门店"
                multiple
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="store in storeOptions"
                  :key="store.id"
                  :label="store.dm"
                  :value="store.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 数据表格 -->
      <div class="NCC-common-layout-main NCC-flex-main">
        <NCC-table v-loading="listLoading" :data="list" has-c>
          <!-- <el-table-column prop="MemberId" label="会员ID" min-width="180">
            <template slot-scope="scope">
              <i class="el-icon-user-solid" style="margin-right: 4px; color: #409EFF;"></i>
              <span>{{ scope.row.MemberId || '无' }}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="MemberName" label="会员名称" min-width="120">
            <template slot-scope="scope">
              <i class="el-icon-user" style="margin-right: 4px; color: #409EFF;"></i>
              <span>{{ scope.row.MemberName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="MemberPhone" label="会员手机" min-width="130">
            <template slot-scope="scope">
              <i class="el-icon-phone" style="margin-right: 4px; color: #67C23A;"></i>
              <span>{{ scope.row.MemberPhone || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="HasUpgradeMedicalBeauty" label="是否升医美" min-width="120">
            <template slot-scope="scope">
              <el-tag 
                :type="scope.row.HasUpgradeMedicalBeauty === '是' ? 'success' : 'info'" 
                size="small">
                {{ scope.row.HasUpgradeMedicalBeauty || '无' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="HasUpgradeTechBeauty" label="是否升科美" min-width="120">
            <template slot-scope="scope">
              <el-tag 
                :type="scope.row.HasUpgradeTechBeauty === '是' ? 'success' : 'info'" 
                size="small">
                {{ scope.row.HasUpgradeTechBeauty || '无' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="HasUpgradeLifeBeauty" label="是否升生美" min-width="120">
            <template slot-scope="scope">
              <el-tag 
                :type="scope.row.HasUpgradeLifeBeauty === '是' ? 'success' : 'info'" 
                size="small">
                {{ scope.row.HasUpgradeLifeBeauty || '无' }}
              </el-tag>
            </template>
          </el-table-column>
        </NCC-table>
        <pagination 
          v-show="total > 0" 
          :total="total" 
          :page.sync="listQuery.pageIndex"
          :limit.sync="listQuery.pageSize" 
          @pagination="handlePagination" 
        />
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import Pagination from '@/components/Pagination'

export default {
  name: 'MemberUpgradeStatistics',
  components: {
    Pagination
  },
  data() {
    return {
      query: {
        memberIds: [],
        hasUpgradeMedicalBeauty: null,
        hasUpgradeTechBeauty: null,
        hasUpgradeLifeBeauty: null,
        month: undefined,
        organizationType: undefined,
        departmentId: undefined,
        storeIds: []
      },
      memberOptions: [],
      memberLoading: false,
      storeOptions: [],
      departmentOptions: [],
      list: [],
      listLoading: false,
      total: 0,
      listQuery: {
        pageIndex: 1,
        pageSize: 10
      }
    }
  },
  created() {
    this.setDefaultMonth()
    this.loadAllStores()
    this.initMemberOptions()
    this.search()
  },
  watch: {
    // 监听年月变化，重新加载门店列表
    'query.month'() {
      this.$nextTick(() => {
        this.initStoreOptions()
      })
    }
  },
  methods: {
    // 设置默认年月（当前年月）
    setDefaultMonth() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      this.query.month = `${year}${month}`
    },

    // 加载全部门店（当没有选择部门时）
    loadAllStores() {
      request({
        url: '/api/Extend/LqMdxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        if (res.data && res.data.list) {
          this.storeOptions = res.data.list
        }
      }).catch(() => {
        this.storeOptions = []
      })
    },

    // 获取部门选项（根据组织类型）
    loadDepartmentOptions() {
      if (!this.query.organizationType) {
        this.departmentOptions = []
        return
      }
      
      request({
        url: '/api/Extend/Organize/GetByName',
        method: 'GET',
        data: {
          organizeName: this.query.organizationType
        }
      }).then(res => {
        this.departmentOptions = res.data || []
        // 如果部门ID不在新列表中，清空部门ID
        if (this.query.departmentId) {
          const exists = this.departmentOptions.some(
            dept => (dept.Id || dept.id) === this.query.departmentId
          )
          if (!exists) {
            this.query.departmentId = undefined
            this.query.storeIds = []
            this.storeOptions = []
          }
        }
      }).catch(() => {
        this.departmentOptions = []
      })
    },

    // 初始化门店选项（根据组织类型、部门、年月）
    initStoreOptions() {
      // 如果没有选择部门，加载全部门店
      if (!this.query.departmentId) {
        this.loadAllStores()
        return
      }

      // 如果缺少必要参数，不加载门店列表
      if (!this.query.organizationType || !this.query.month) {
        this.storeOptions = []
        return
      }

      request({
        url: '/api/Extend/lqmdtarget/GetManagedStores',
        method: 'POST',
        data: {
          month: this.query.month,
          organizationType: this.query.organizationType,
          departmentId: this.query.departmentId
        }
      }).then(res => {
        if (res.data && Array.isArray(res.data)) {
          // 将返回的数据格式转换为 storeOptions 需要的格式
          // 返回格式: [{ StoreId: "...", StoreName: "..." }]
          // 需要格式: [{ id: "...", dm: "..." }]
          this.storeOptions = res.data.map(store => ({
            id: store.StoreId,
            dm: store.StoreName
          }))
          // 默认选中所有获取到的门店
          this.query.storeIds = this.storeOptions.map(store => store.id)
        } else {
          this.storeOptions = []
          this.query.storeIds = []
        }
      }).catch(err => {
        console.error('获取门店列表失败:', err)
        this.$message({
          type: 'error',
          message: '获取门店列表失败',
          duration: 1500
        })
        this.storeOptions = []
        this.query.storeIds = []
      })
    },

    // 处理年月变化
    handleMonthChange() {
      this.$nextTick(() => {
        this.initStoreOptions()
      })
    },

    // 处理组织类型变化
    handleOrganizationTypeChange() {
      // 清空部门和门店
      this.query.departmentId = undefined
      this.query.storeIds = []
      // 重新加载部门选项
      this.loadDepartmentOptions()
      // 加载全部门店（因为部门已清空）
      this.loadAllStores()
    },

    // 处理部门变化
    handleDepartmentChange() {
      // 清空门店选择
      this.query.storeIds = []
      // 重新加载门店列表（如果有部门则加载部门管理的门店，否则加载全部门店）
      this.initStoreOptions()
    },

    // 初始化会员选项（加载前10个）
    initMemberOptions() {
      request({
        url: '/api/Extend/LqKhxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 10
        }
      }).then(res => {
        if (res.code == 200 && res.data && res.data.list) {
          this.memberOptions = res.data.list.map(item => ({
            id: item.id,
            label: item.khmc || item.id
          }))
        } else {
          this.memberOptions = []
        }
      }).catch(() => {
        this.memberOptions = []
      })
    },

    // 远程搜索会员
    remoteSearchMembers(query) {
      if (query !== '') {
        this.memberLoading = true
        request({
          url: '/api/Extend/LqKhxx',
          method: 'GET',
          data: {
            currentPage: 1,
            pageSize: 10,
            keyword: query
          }
        }).then(res => {
          this.memberLoading = false
          if (res.code == 200 && res.data && res.data.list) {
            this.memberOptions = res.data.list.map(item => ({
              id: item.id,
              label: item.khmc || item.id
            }))
          } else {
            this.memberOptions = []
          }
        }).catch(() => {
          this.memberLoading = false
          this.memberOptions = []
        })
      } else {
        this.memberOptions = []
        this.initMemberOptions()
      }
    },

    // 查询数据
    search() {
      this.listLoading = true

      const params = {
        pageIndex: this.listQuery.pageIndex,
        pageSize: this.listQuery.pageSize
      }

      if (this.query.memberIds && this.query.memberIds.length > 0) {
        params.memberIds = this.query.memberIds
      }

      if (this.query.hasUpgradeMedicalBeauty !== null && this.query.hasUpgradeMedicalBeauty !== undefined) {
        params.hasUpgradeMedicalBeauty = this.query.hasUpgradeMedicalBeauty
      }

      if (this.query.hasUpgradeTechBeauty !== null && this.query.hasUpgradeTechBeauty !== undefined) {
        params.hasUpgradeTechBeauty = this.query.hasUpgradeTechBeauty
      }

      if (this.query.hasUpgradeLifeBeauty !== null && this.query.hasUpgradeLifeBeauty !== undefined) {
        params.hasUpgradeLifeBeauty = this.query.hasUpgradeLifeBeauty
      }

      if (this.query.storeIds && this.query.storeIds.length > 0) {
        params.storeIds = this.query.storeIds
      }

      request({
        url: '/api/Extend/lqstatistics/get-member-upgrade-statistics-list',
        method: 'POST',
        data: params
      }).then(res => {
        if (res.data && res.data.list) {
          this.list = res.data.list
          this.total = (res.data.pagination && res.data.pagination.total) || res.data.list.length || 0
        } else {
          this.list = []
          this.total = 0
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
        this.list = []
        this.total = 0
      })
    },

    // 处理分页变化
    handlePagination({ page, limit }) {
      this.listQuery.pageIndex = page
      this.listQuery.pageSize = limit
      this.search()
    },

    // 重置查询条件
    reset() {
      this.query = {
        memberIds: [],
        hasUpgradeMedicalBeauty: null,
        hasUpgradeTechBeauty: null,
        hasUpgradeLifeBeauty: null,
        month: undefined,
        organizationType: undefined,
        departmentId: undefined,
        storeIds: []
      }
      this.setDefaultMonth()
      this.departmentOptions = []
      // 重置后加载全部门店
      this.loadAllStores()
      this.listQuery.pageIndex = 1
      this.listQuery.pageSize = 10
      this.list = []
      this.total = 0
      this.search()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

