<!--  -->
<template>
  <div>
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
      >
        <div>
          <el-form-item label="企业" prop="enterpriseId">
            <el-select
              v-model="queryParams.enterpriseId"
              placeholder="请选择企业"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in enterpriseOption"
                :key="dict.value"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="deptId">
            <el-select
              v-model="queryParams.deptId"
              placeholder="请选择部门"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in deptOption"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户" prop="userId">
            <el-select
              v-model="queryParams.userId"
              placeholder="请选择用户"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in userOption"
                :key="dict.value"
                :label="dict.name"
                :value="dict.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="职位" prop="jobId">
            <el-select
              v-model="queryParams.jobId"
              placeholder="请选择职位"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in jobOption"
                :key="dict.value"
                :label="dict.name"
                :value="dict.positionId"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="" prop="type">
          <el-radio-group v-model="queryParams.type" @change="typeChange" class="!w-240px">
            <el-radio-button label="最近七天" value="0" />
            <el-radio-button label="上个月" value="1" />
            <el-radio-button label="上季度" value="2" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" prop="time">
          <el-date-picker
            v-model="queryParams.time"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-240px"
            @change="timeRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button
            type="success"
            plain
            @click="null"
            :loading="false"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <div class="flex flex-col">
      <!-- 数据对照 -->
      <el-row :gutter="16" class="row">
        <el-col v-for="item in statisticList" :key="item.name" :md="4" :sm="12" :xs="24" :loading="loading">
          <ComparisonCard
            :title="item.title"
            :value="statistic[item.name]"
            style="cursor: pointer;"
            @click="openDialog(item)"
          />
        </el-col>
      </el-row>
      <el-row :gutter="16" class="row">
        <el-col :md="12">
          <SexDistribution :data="distribution.sexDistributionData" title="性别分布" />
        </el-col>
        <el-col :md="12">
          <ageDistribution :data="distribution.ageDistributionData" title="年龄分布" />
        </el-col>
      </el-row>
      <el-row :gutter="16" class="row">
        <el-col :md="12">
          <workExperience :data="distribution.workExperienceData" title="工作年限分布" />
        </el-col>
        <el-col :md="12">
          <education :data="distribution.educationData" title="学历分布" />
        </el-col>
      </el-row>
    </div>
    <!-- 弹窗 -->
    <Dialog :title="currentItem.title+'详情'" v-model="showDialog" width="1200" @close="closeDialog">
      <ContentWrap>
        <el-table v-loading="dialogLoading" :data="tableData" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column
            v-for="item in tableHeaders[currentItem.name]"
            :key="item.prop"
            :prop="item.prop"
            :label="item.name"
            :align="item.align || 'center'"
          />
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="page.pageNo"
          v-model:limit="page.pageSize"
          @pagination="paginationChange"
        />
      </ContentWrap>
    </Dialog>
</div>
</template>

<script setup>
import ComparisonCard from './components/ComparisonCard.vue'
import SexDistribution from './components/SexDistribution.vue'
import ageDistribution from './components/AgeDistribution.vue'
import workExperience from './components/WorkExperience.vue'
import education from './components/Education.vue'
import { statisticAnalysisApi } from '@/api/menduner/system/analysis/statisticAnalysis'
// import { dealDictArrayData, dealDictObjData } from '@/utils/position'
defineOptions({name: 'StatisticAnalysis'})

const loading = ref(true) // 加载中
const dialogLoading = ref(false)

/** 初始化 **/
onMounted(async () => {
  loading.value = true
})

const page = reactive({ pageNo: 1, pageSize: 10 })
const queryParams = reactive({
  type: '0',
  enterpriseId: undefined,
  deptId: undefined,
  userId: undefined,
  jobId: undefined,
  time: [],
})

const queryFormRef = ref() // 搜索的表单
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const typeChange = (value) => { // 
  if (value) {
    queryParams.time = []
  }
}
const timeRangeChange = (value) => {
  if (value?.length) queryParams.type = '99' // 自定义
  else queryParams.type = '0'
}

const apiArr = reactive({
  // 统计
  pageViewsTotal: statisticAnalysisApi.getAnalysisJobBrowseNum, // 职位浏览量-总数据
  pageViews: statisticAnalysisApi.getAnalysisJobBrowseNumPage, // 职位浏览量-钻取
  resumeReceived: statisticAnalysisApi.getAnalysisJobCvNewPage, // 钻取
  resumeViewed: statisticAnalysisApi.getAnalysisJobCvLookPage, // 钻取
  invitedInterviews: statisticAnalysisApi.getAnalysisInterviewWaitPage, // 钻取
  invitedCompleted: statisticAnalysisApi.getAnalysisInterviewCompletePage, // 钻取
  // 分布
  sexDistributionData: statisticAnalysisApi.getAnalysisJobCvSexCount,
  ageDistributionData: statisticAnalysisApi.getAnalysisJobCvAgeCount,
  workExperienceData: statisticAnalysisApi.getAnalysisJobCvExpCount,
  educationData: statisticAnalysisApi.getAnalysisJobCvEduCount,
})

// 统计
const statisticList = [
  { title: '职位浏览量', name: 'pageViews' },
  { title: '收到的简历', name: 'resumeReceived' },
  { title: '已查看简历', name: 'resumeViewed' },
  { title: '已邀面试', name: 'invitedInterviews' },
  { title: '面试完成', name: 'invitedCompleted' },
]
// 统计
const statistic = reactive({
  pageViews: 0,
  resumeReceived: 0,
  resumeViewed: 0,
  invitedInterviews: 0,
  invitedCompleted: 0,
})

// 分布
const distribution = reactive({
  sexDistributionData: {},
  ageDistributionData: {},
  workExperienceData: {},
  educationData: {},
})

// 统计
const tableData = ref([])
const total = ref(0)
const getList = async (typeName, details = '') => {
  loading.value = true
  try {
    let data
    if (!details && typeName === 'pageViews') {
      // 职位浏览量-总数据
      const res = await apiArr.pageViewsTotal(queryParams)
      data ={ total: res || 0 }
    } else {
      // 使用钻取接口
      data = await apiArr[typeName]({ ...queryParams, ...page })
    }
    if (details) {
      tableData.value = data.list || []
      total.value = data.total || 0
      dealTableData()
    } else {
      statistic[typeName] = data.total || data || 0
    }
  } finally {
    loading.value = false
    dialogLoading.value = false
  }
}

import { getDictOptions } from '@/utils/transform/getText'
import { timesTampChange } from '@/utils/transform/date'
import { DICT_TYPE, getDictLabel } from '@/utils/dict'

const getText = (value, arr, itemText = 'name', itemValue = 'id') => { // 一维数组
  if (!arr?.length || !(value && value !== 0)) return
  const item = arr.find(formItem => formItem[itemValue] === value)
  if (!item) return
  return item[itemText]
}


// 分布
const getDistributionCount = async (typeName) => {
  try {
    const data = await apiArr[typeName](queryParams)
    distribution[typeName] = data || {}
  } catch (error) {
    console.log(error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (Object.keys(statistic).length) {
    Object.keys(statistic).forEach(name => {
      getList(name)
    })
  }
  // 
  if (Object.keys(distribution).length) {
    Object.keys(distribution).forEach(name => {
      getDistributionCount(name)
    })
  }
}
handleQuery()

const showDialog = ref(false)
const currentItem = ref({})
// 打开弹窗
const openDialog = (item) => {
  dialogLoading.value = true
  currentItem.value = item
  page.pageNo = 1
  tableData.value = []
  getList(item.name, '钻取')
  showDialog.value = true
}
const closeDialog = () => {
}
const paginationChange = () => {
  getList(currentItem.value.name, '钻取')
}

const tableHeaders = {
  pageViews: [
    { name: '浏览量', prop: 'num' },
    { name: '招聘职位', prop: 'name' },
    { name: '薪酬', prop: 'salaryDisplay' },
    { name: '工作地区', prop: 'areaName' },
    { name: '工作经验', prop: 'expName' },
    { name: '学历要求', prop: 'eduName' },
  ],
  resumeReceived: [
    { name: '投递人', prop: 'personName' },
    { name: '求职状态', prop: 'jobStatus' },
    { name: '薪酬', prop: 'salaryDisplay' },
    { name: '工作地区', prop: 'areaName' },
    { name: '工作经验', prop: 'expName' },
    { name: '学历要求', prop: 'eduName' },
  ],
  resumeViewed: [
    { name: '简历标题', prop: 'title' },
    { name: '投递人', prop: 'personName' },
    { name: '投递类型', prop: 'typeName' },
    { name: '推荐人', prop: 'recommendPersonName' },
  ],
  invitedInterviews: [
    { name: '求职者', prop: 'personName' },
    { name: '面试岗位', prop: 'jobName' },
    { name: '面试类型', prop: 'typeName' },
    { name: '面试时间', prop: 'timeName' },
    { name: '面试地点', prop: 'addressName' },

  ],
  invitedCompleted: [
    { name: '求职者', prop: 'personName' },
    { name: '面试岗位', prop: 'jobName' },
    { name: '面试类型', prop: 'typeName' },
    { name: '面试时间', prop: 'timeName' },
    { name: '面试地点', prop: 'addressName' },
    { name: '反馈评价', prop: 'evaluate' },
  ],
}

const dealTableData = async () => {
  if (currentItem.value.name === 'pageViews') {
    const areaList = await getDictOptions('areaList')
    tableData.value = tableData.value.map(item => {
      item.salaryDisplay = `${item.payFrom}-${item.payTo}/${getDictLabel(DICT_TYPE.MENDUNER_PAY_UNIT, item.payUnit)}`
      item.areaName = getText(item.areaId, areaList)
      item.expName = getDictLabel(DICT_TYPE.MENDUNER_EXP_TYPE, item.expType)
      item.eduName = getDictLabel(DICT_TYPE.MENDUNER_EDUCATION_TYPE, item.eduType)
      return item
    })
  }
  if (currentItem.value.name === 'resumeReceived') {
    const areaList = await getDictOptions('areaList')
    tableData.value = tableData.value.map(item => {
      item.areaName = getText(item.job.areaId, areaList)
      item.salaryDisplay = `${item.job.payFrom}-${item.job.payTo}/${getDictLabel(DICT_TYPE.MENDUNER_PAY_UNIT, item.job.payUnit)}`
      item.jobStatus = getDictLabel(DICT_TYPE.MENDUNER_JOB_STATUS, item.person.jobStatus)
      item.expName = getDictLabel(DICT_TYPE.MENDUNER_EXP_TYPE, item.job.expType)
      item.eduName = getDictLabel(DICT_TYPE.MENDUNER_EDUCATION_TYPE, item.job.eduType)
      item.personName = item.person.name
      return item
    })
  }
  if (currentItem.value.name === 'resumeViewed') {
    tableData.value = tableData.value.map(item => {
      item.personName = item.person.name
      item.address = item.job.address
      item.typeName = item.type === 0 ? '平台投递': '赏金投递'
      item.recommendPersonName = item.recommendPerson?.name || ''
      return item
    })
  }
  if (currentItem.value.name === 'invitedInterviews') {
    tableData.value = tableData.value.map(item => {
      item.personName = item.person.name
      item.jobName = item.job.name
      item.typeName = item.type === 0 ? '线上面试': '线下面试'
      item.timeName = timesTampChange(item.time, 'Y-M-D h:m')
      item.addressName = item.job.address
      return item
    })
  }
  if (currentItem.value.name === 'invitedCompleted') {
    tableData.value = tableData.value.map(item => {
      item.personName = item.person.name
      item.jobName = item.job.name
      item.typeName = item.type === 0 ? '线上面试': '线下面试'
      item.timeName = timesTampChange(item.time, 'Y-M-D h:m')
      item.addressName = item.job.address
      return item
    })
  }
}


// 企业
const enterpriseOption = ref([])
const getEnterpriseOption = async () => {
  try {
    const data = await statisticAnalysisApi.getAnalysisEnterpriseSimpleList()
    enterpriseOption.value = data || []
  } catch (error) {
    console.log(error)
  }
}
getEnterpriseOption()

// 部门
const deptOption = ref([])

// 用户
const userOption = ref([])
const getUserOption = async () => {
  try {
    // const params = {}
    const data = await statisticAnalysisApi.getAnalysisEnterpriseUserList()
    userOption.value = data || []
  } catch (error) {
    console.log(error)
  }
}
getUserOption()

// 用户
const jobOption = ref([])
const getJobOption = async () => {
  try {
    // const params = {}
    const data = await statisticAnalysisApi.getAnalysisJobAdvertisedList()
    jobOption.value = data || []
  } catch (error) {
    console.log(error)
  }
}
getJobOption()

</script>
<style lang="scss" scoped>
.row {
  .el-col {
    margin-bottom: 1rem;
  }
}
</style>
