<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
    >
      <el-form-item label="" prop="type">
        <el-radio-group v-model="queryParams.type" @change="typeChange" class="!w-390px">
          <!-- <el-radio-button label="全部" value="-1" /> -->
          <el-radio-button label="24小时内" value="3" />
          <el-radio-button label="7天内" value="0" />
          <!-- <el-radio-button label="上个月" value="1" /> -->
          <el-radio-button label="30天内" value="4" />
          <el-radio-button label="3个月内" value="6" />
          <!-- <el-radio-button label="上个季度" value="2" /> -->
          <el-radio-button label="1年内" value="5" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="" prop="time">
        <span class="mr-3">自定义日期</span>
        <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-form-item>
    </el-form>
  </ContentWrap>
  <!-- 统计 -->
  <div>
    <CardTitle title="招聘进展"  style="margin-left: 5px;"/>
    <el-row :gutter="16" class="row" style="margin-top: 10px;">
      <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]" class="mb-10px" />
      </el-col>
    </el-row>
  </div>
  <!-- 图表 -->
   
  <div style="margin-top: 15px;">
    <CardTitle title="数量统计" style=" margin-top: 20px;margin-left: 5px;"/>
  </div>
  <el-row class="mt-8px" :gutter="10" justify="space-between">
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px" v-for="(val, index) in list" :key="index">
      <el-skeleton :loading="val.loading" animated>
        <el-card shadow="hover" class="mb-8px">
          <template #header>
            <div class="h-3 flex justify-between">
              <span>{{ val.title }}</span>
            </div>
          </template>
          <el-skeleton :loading="val.loading" animated>
            <Echart :options="val.options" :height="280" />
          </el-skeleton>
        </el-card>
      </el-skeleton>
    </el-col>
  </el-row>
</template>

<script setup>
defineOptions({ name: 'Home' })
import { cloneDeep } from 'lodash-es'
import { getNewResumeNum, getNewRegisterUserNum, getNewRegisterEnterpriseNum, getNewEnterpriseUserNum } from '@/api/home'
import { statisticAnalysisApi } from '@/api/menduner/system/analysis/statisticAnalysis'
import ComparisonCard from '@/views/menduner/system/analysis/statisticAnalysis/components/ComparisonCard.vue'

const queryFormRef = ref()
const queryParams = reactive({
  type: '3',
  time: []
})
const barCommonOptions = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: 50,
    bottom: 50,
    right: 40,
    top: 30
  },
  xAxis: {
    type: 'category',
    name: '',
    data: [],
    axisTick: {
      alignWithLabel: true
    },
    axisLabel: {
      rotate: 30
    }
  },
  yAxis: {
    type: 'value',
    name: '人'
  },
  series: [
    { 
      data: [],
      type: 'line',
      // barWidth: 20,
      label: { show: true }
    }
  ]
}

const getCommonOptions = (yAxisName) => {
  const options = cloneDeep(barCommonOptions)
  if (yAxisName) options.yAxis.name = yAxisName
  return options
}
const list = ref([
  {
    api: getNewRegisterUserNum,
    title: '新个人用户注册数量统计',
    loading: false,
    options: getCommonOptions()
  },
  {
    api: getNewResumeNum,
    title: '新增简历数量统计',
    loading: false,
    options: getCommonOptions('份')
  },
  {
    api: getNewRegisterEnterpriseNum,
    title: '新注册企业数量统计',
    loading: false,
    options: getCommonOptions()
  },
  {
    api: getNewEnterpriseUserNum,
    title: '新企业用户数量统计',
    loading: false,
    options: getCommonOptions()
  }
])

/** 图表数据请求 */
const fetchData = async (api) => {
  try {
    const data = await api(queryParams)
    return data
  } catch (error) {
    console.error('Error fetching data:', error)
    return null
  }
}

const unitArr = {
  '3': '小时',
  '0': '日',
  '4': '日',
  '5': '月'
}
async function fetchAllData() {
  list.value.forEach(item => item.loading = true)
  const promises = list.value.map(item => fetchData(item.api))
  try {
    const results = await Promise.all(promises)
    results.forEach((result, index) => {
      list.value[index].options.xAxis.name = unitArr[queryParams.type]
      list.value[index].options.xAxis.data = result.x
      list.value[index].options.series[0].data = result.y
      list.value[index].loading = false
    })
  } catch (error) {
    list.value.forEach(item => item.loading = false)
  }
}
// fetchAllData()

/** 类型选择操作 */
const typeChange = (value) => {
  if (value) queryParams.time = []
  handleQuery()
}

/** 自定义时间选择操作 */
const timeRangeChange = (value) => {
  if (value?.length) queryParams.type = '99'
  else queryParams.type = '0'
}

const loading = ref(true) // 加载中
/** 初始化 **/
onMounted(async () => {
  loading.value = true
})

// 统计
const statisticList = [
  { title: '注册未填写简历', name: 'registerUnResume' },
  { title: '发布职位数量', name: 'pushNum' },
  { title: '职位浏览量', name: 'pageViews' },
  { title: '收到的简历', name: 'resumeReceived' },
  { title: '已查看简历', name: 'resumeViewed' },
  { title: '已邀面试', name: 'invitedInterviews' },
  { title: '面试完成', name: 'invitedCompleted' },
]

// 统计
const statistic = reactive({
  pageViews: 0,
  pushNum: 0,
  resumeReceived: 0,
  resumeViewed: 0,
  invitedInterviews: 0,
  invitedCompleted: 0,
  registerUnResume: 0
})

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

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 {
      // 使用钻取接口
      const params = { ...queryParams, ...{ pageNo: 1, pageSize: 10 } }
      if (typeName === 'pushNum') params.jobStatus = 0 // 发布职位数量单独加上jobStatus字段
      data = await apiArr[typeName](params)
    }
    if (details) {
      tableData.value = data.list || []
      total.value = data.total || 0
    } else {
      statistic[typeName] = data.total || 0
    }
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  if (Object.keys(statistic).length) { // 招聘进展
    Object.keys(statistic).forEach(name => {
      getList(name)
    })
  }
  fetchAllData()
}
handleQuery() // 默认展示数据

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
</script>
