<template>
  <div class="app-container">
    <div class="container">
      <!-- 查询表单 -->
      <el-form :model="queryParams"
        inline
        label-width="68px">
        <el-row>
          <el-form-item label="选择日期"
            prop="activityDate">
            <el-date-picker v-model="queryParams.activityDate"
              type="daterange"
              clearable
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="pickerOptions"
              @change="selActivityDate" />
          </el-form-item>
          <el-form-item label="活动状态"
            prop="planStatus">
            <el-select v-model="queryParams.planStatus"
              placeholder="请选择活动状态"
              filterable
              clearable
              @change="getPlanList">
              <el-option v-for="item in taskStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <!-- 省市 -->
        <el-row>
          <el-form-item label="区域查询"
            prop="region">
            <el-radio-group v-model="queryParams.region"
              @change="changeRegion">
              <el-radio-button label="全国"
                value="全国" />
              <el-radio-button label="省"
                value="省" />
              <el-radio-button label="省-市"
                value="省-市" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="省份"
            prop="provinceId"
            v-show="queryParams.region !== '全国'">
            <el-select v-model="queryParams.provinceId"
              placeholder="请选择省"
              @change="selProvince"
              filterable
              clearable>
              <el-option v-for="item in provinceList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="城市"
            prop="cityId"
            v-show="queryParams.region === '省-市'">
            <el-select v-model="queryParams.cityId"
              placeholder="请选择市"
              @change="selCity"
              filterable
              clearable>
              <el-option v-for="item in cityList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="经销商"
            prop="dealerId">
            <el-select v-model="queryParams.dealerId"
              placeholder="搜索更多经销商"
              @change="getPlanList"
              filterable
              remote
              :remote-method="dealerRemoteSearch"
              clearable>
              <el-option v-for="item in dealerList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="战区"
            prop="warZoneId">
            <el-select v-model="queryParams.warZoneId"
              placeholder="搜索战区"
              filterable
              clearable
              :disabled="isCityManager"
              @change="getPlanList">
              <el-option v-for="item in warZoneList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="归属人"
            prop="employeeId">
            <el-select v-model="queryParams.employeeId"
              placeholder="搜索归属人"
              filterable
              clearable
              :disabled="isCityManager"
              @change="getPlanList">
              <el-option v-for="item in belongPerList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="店铺名"
            prop="storeName">
            <el-input v-model="queryParams.storeName"
              clearable
              placeholder="搜索店铺名"
              @input="getPlanList" />
          </el-form-item>
        </el-row>
      </el-form>
      <el-tabs type="card">
        <el-tab-pane label="有效计划">
          <EffectivePlan ref="effectivePlan"
            :queryParams="queryParams" />
        </el-tab-pane>
        <el-tab-pane label="已删除计划">
          <InvalidPlan ref="invalidPlan"
            :queryParams="queryParams" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { getProCityAPI, getDealerListAPI, getWarZoneListAPI, getChargeListAPI } from '@/api'
import { parseTime } from '@/utils'
import userStore from '@/store/modules/user'
import { useDatePickerOptions } from '@/hooks'
import { PROMOTION_STATUS } from '@/dicts'
import EffectivePlan from './effectivePlan.vue'
import InvalidPlan from './invalidPlan.vue'

const { proxy } = getCurrentInstance()

const isCityManager = userStore().promotionIdentity
const empInfo = userStore().empInfo // 当前登录员工信息

const queryParams = reactive({
  activityDate: [],
  planStatus: '',
  region: '全国',
  provinceId: '',
  cityId: '',
  dealerId: '', // 经销商
  warZoneId: '', // 战区
  employeeId: '', // 归属人
  storeName: '', // 门店名称
})
/************* 选择日期 *************/
const { recentPickerOptions: pickerOptions } = useDatePickerOptions()
const selActivityDate = () => {
  if (queryParams.activityDate?.length > 0) {
    queryParams.activityDate = queryParams.activityDate.map(item => parseTime(item, '{y}-{m}-{d}'))
  }
  getPlanList()
}

/************* 选择状态 *************/
const taskStatusList = ref(Object.values(PROMOTION_STATUS))

/************* 区域查询 *************/
const provinceList = ref([])
const cityList = ref([])
const getProCityList = async () => {
  const { data } = await getProCityAPI(queryParams)
  const list = data.map(item => ({
    label: item.name,
    value: item.num
  }))
  queryParams.provinceId ? (cityList.value = list) : (provinceList.value = list)
}
getProCityList()
// 切换省市范围
const changeRegion = async () => {
  if (queryParams.region === '全国') {
    queryParams.provinceId = ''
    queryParams.provinceName = ''
    queryParams.cityId = ''
    queryParams.cityName = ''
  } else if (queryParams.region === '省') {
    queryParams.cityId = ''
    queryParams.cityName = ''
  }
  getPlanList()
}
// 选择省
const selProvince = async () => {
  // 设置省名
  queryParams.provinceName = provinceList.value.find(item => item.value === queryParams.provinceId)?.label
  // 重置城市
  queryParams.cityId = ''
  queryParams.cityName = ''
  cityList.value = []
  // 重新获取城市列表以及查询列表
  getProCityList()
  getPlanList()
}
// 选择市
const selCity = async () => {
  // 设置市名
  queryParams.cityName = cityList.value.find(item => item.value === queryParams.cityId)?.label
  // 重新获取查询列表
  getPlanList()
}

/*************** 经销商 ***************/
const dealerList = ref([])
const getDealerList = async () => {
  const { data } = await getDealerListAPI(queryParams)
  dealerList.value = data.map(item => {
    return {
      label: item.dealerName,
      value: item.dealerId
    }
  })
}
// 经销商远程搜索
const dealerRemoteSearch = (searchKey) => {
  queryParams.dealerName = searchKey
  getDealerList()
}

/*************** 战区 ***************/
const warZoneList = ref([])
const getWarZoneList = async () => {
  const { data } = await getWarZoneListAPI()
  warZoneList.value = data.map(item => {
    return {
      label: item.orgName,
      value: item.qcId
    }
  })
  // 城市经理，设置默认战区
  isCityManager && (queryParams.warZoneId = belongPerList.value.find(item => item.employeeNo === empInfo.empNo)?.deptQcId)
}

/*************** 归属人 ***************/
const belongPerList = ref([])
const getBelongPerList = async () => {
  const { data } = await getChargeListAPI()
  belongPerList.value = data.map(item => {
    return {
      label: item.name,
      value: item.id,
      employeeNo: item.employeeNo,
      deptQcName: item.deptQcName,
      deptQcId: item.deptQcId
    }
  })

  // 城市经理，设置默认归属人 

  isCityManager && (queryParams.employeeId = belongPerList.value.find(item => item.employeeNo === empInfo.empNo)?.value)
}

onMounted(async () => {
  // 给城市经理设置默认选中战区，需要确保归属人列表数据有值
  await getBelongPerList()
  await getWarZoneList()
  getPlanList()
})

/************ 数据列表管理 ************/
const getPlanList = () => {
  proxy.$refs.effectivePlan.getPlanList('resetPage')
  proxy.$refs.invalidPlan.getPlanList('resetPage')
}
</script>