<!-- 业务工作量分析 -->
<script lang="ts" setup name="WorkloadAnalysisList">
import type { Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { DateModelType, ElLoading, ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IList, IListQuery } from './workloadAnalysis-interface'
import type { StaffType } from '@/views/measure/person/person-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { getUsersDept } from '@/api/device/standard'
import { getStaffList } from '@/api/measure/person'
import { exportWorkloadAnalysisList, getWorkloadAnalysisList } from '@/api/business/board/workloadAnalysis'
const { proxy } = getCurrentInstance() as any
const usePersonList = ref([]) as any// 申请人列表（用户）
const usePersonOptions = ref([]) as any// 申请人列表（用户）--模糊搜索数据
const applyPersonLoading = ref(false) // 申请人模糊搜索框loading
// 部门
const standardUsersDeptList = ref([]) as any
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  deptId: '', // 部门id
  staffId: '', // 人员id
  month: '', // 月份
  year: '', // 年份
  date: '', // 日期
})
// 表头
const columns = ref<TableColumn[]>([
  { text: '部门', value: 'deptName', width: '160', align: 'center' },
  { text: '人员', value: 'staffName', width: '160', align: 'center' },
  { text: '检定样品数量', value: 'samples', align: 'center' },
  { text: '出具证书数量', value: 'certificates', align: 'center' },
  { text: '较上月工作量分析', value: 'compareLastMonth', align: 'center' },
])

// 表格数据
const list = ref<IList[]>([])
// 表格加载状态
const loadingTable = ref(false)

// 数据查询
function fetchData() {
  if (listQuery.value.date) {
    listQuery.value.year = listQuery.value.date.slice(0, listQuery.value.date.indexOf('-'))
    listQuery.value.month = listQuery.value.date.slice(listQuery.value.date.indexOf('-') + 1)
    loadingTable.value = true
  }
  else {
    ElMessage.warning('请选择年月')
    return
  }
  getWorkloadAnalysisList(listQuery.value).then((response) => {
    list.value = response.data
    loadingTable.value = false
  })
}

// 重置
const clearList = () => {
  listQuery.value = {
    deptId: '', // 部门id
    staffId: '', // 人员id
    month: '', // 月份
    year: '', // 年份
    date: dayjs().format('YYYY-MM'),
  }
  fetchData()
}

// 搜索
const searchList = () => {
  fetchData()
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      deptId: listQuery.value.deptId, // 部门id
      staffId: listQuery.value.staffId, // 人员id
      month: listQuery.value.month, // 月份
      year: listQuery.value.year, // 年份
      date: '',
    }
    exportWorkloadAnalysisList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '业务工作量分析列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (list.value.length) {
    printJSON(list.value, properties, '业务工作量分析列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 获取部门信息
const fetchUsersDept = () => {
  // 获取部门信息参数
  const DeptParams = ref({
    createEndTime: '',
    createstartTime: '',
    director: '',
    meterMajor: '',
    organizeName: '',
    organizeNo: '',
    organizeType: '3',
    pdeptId: null,
    offset: 1,
    limit: 999999,
  })
  getUsersDept(DeptParams.value).then((res) => {
    standardUsersDeptList.value = res.data.rows
  })
}

// 选择器模糊查询
const remoteMethod = (query: string) => {
  if (query) {
    applyPersonLoading.value = true
    setTimeout(() => {
      applyPersonLoading.value = false
      usePersonOptions.value = usePersonList.value.filter((item: any) => {
        return item.name.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  }
  else {
    usePersonOptions.value = usePersonList.value
  }
}

// 获取计量人员列表
const fetchUserList = (deptId: string) => {
  const searchQuery = {
    staffNo: '', // 人员编号
    name: '', // 姓名
    deptId: deptId || '', // 工作部门
    major: '', // 计量专业
    verifierCertificateNo: '', // 证书号
    certificateStatus: '', // 证书状态
    limit: 9999999,
    offset: 1,
  }
  getStaffList(searchQuery).then((res) => {
    if (res.code === 200) {
      res.data.records = res.data.records.map((item: StaffType) => ({ ...item, sex: item.sex == '1' ? '男' : '女', technologyExam: item.technologyExam == '0' ? '已考核' : '未考核', certificateDate: item.certificateDate.split(' ')[0] }))
      usePersonList.value = res.data.records
      usePersonOptions.value = res.data.records
    }
    loadingTable.value = false
  })
}

// 部门值发生变化
const deptChange = (deptId: string) => {
  listQuery.value.staffId = ''
  fetchUserList(deptId)
}

onMounted(() => {
  fetchUsersDept() // 获取部门信息
  listQuery.value.date = dayjs().format('YYYY-MM') // 年月默认本月
  fetchData() // 获取表格数据
})
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-select
          v-model="listQuery.deptId"
          clearable
          placeholder="选择部门"
          size="default"
          @change="deptChange"
        >
          <el-option
            v-for="item in standardUsersDeptList"
            :key="item.deptId"
            :label="item.organizeName"
            :value="item.deptId!"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-select
          v-if="usePersonList.length && listQuery.deptId"
          v-model="listQuery.staffId"
          placeholder="选择人员"
          style="width: 100%;"
          filterable
          remote
          remote-show-suffix
          :remote-method="remoteMethod"
          :loading="applyPersonLoading"
        >
          <el-option v-for="item in usePersonOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </search-item>

      <!-- <search-item>
        <el-date-picker
          v-model="listQuery.year"
          type="year"
          placeholder="选择年份"
        />
      </search-item> -->
      <search-item>
        <el-date-picker
          v-model="listQuery.date"
          type="month"
          placeholder="选择年月"
          format="YYYY-MM"
          value-format="YYYY-MM"
        />
      </search-item>
    </search-area>
    <table-container title="业务工作量分析" :is-center="true">
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/business/board/businessWorkloadAnalysis/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/business/board/businessWorkloadAnalysis/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
      </template>
      <normal-table
        :data="list" :pagination="false" :columns="columns" :query="listQuery"
        :list-loading="loadingTable" :is-showmulti-select="false"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

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