<!-- 部门综合分析 -->
<script lang="ts" setup name="DepComprehensiveList">
import type { Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { IList, IListQuery } from './depComprehensive-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 { exportDepComprehensiveList, getDepComprehensiveList } from '@/api/business/board/depComprehensive'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
const { proxy } = getCurrentInstance() as any
// 部门
const standardUsersDeptList = ref([]) as any
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  deptId: '', // 部门id
  startTime: '', // 开始时间
  endTime: '', // 结束时间
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'depComprehensive', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('depComprehensive') || {
  deptId: '', // 部门id
  startTime: '', // 开始时间
  endTime: '', // 结束时间
}
// 表头
const columns = ref<TableColumn[]>([
  { text: '部门', value: 'deptName', width: '160', align: 'center' },
  { text: '检完样品数量', value: 'samples', align: 'center' },
  { text: '出具证书数量', value: 'certificates', align: 'center' },
  { text: '样品总量', value: 'samplesTotal', align: 'center' },
  { text: '超期总数', value: 'expireSamples', align: 'center' },
  { text: '超期率', value: 'expireRate', align: 'center' },
  { text: '设备检定及时率', value: 'deviceTimelyRate', align: 'center' },
  { text: '设备检定合格率', value: 'deviceQualifyRate', align: 'center' },
  { text: '设备维修率', value: 'deviceRepairRate', align: 'center' },
])

// 表格数据
const list = ref<IList[]>([])
// 表格加载状态
const loadingTable = ref(false)
// 表格标题
const title = ref('')
// 筛选时间段数据
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])

// 数据查询
function fetchData() {
  loadingTable.value = true
  title.value = listQuery.value.startTime && listQuery.value.endTime ? `部门综合分析 (${listQuery.value.startTime} ~ ${listQuery.value.endTime})` : '部门综合分析'
  getDepComprehensiveList(listQuery.value).then((response) => {
    list.value = response.data
    loadingTable.value = false
  })
}

// 重置
const clearList = () => {
  listQuery.value = {
    deptId: '', // 部门id
    startTime: '', // 开始时间
    endTime: '', // 结束时间
  }
  listQuery.value.startTime = dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss')
  listQuery.value.endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  timeRange.value = [listQuery.value.startTime, listQuery.value.endTime]
  fetchData()
}

// 搜索
const searchList = () => {
  console.log(timeRange.value, ';;')
  if (timeRange.value) {
    listQuery.value.startTime = timeRange.value[0] as string || ''
    listQuery.value.endTime = timeRange.value[1] as string || ''
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
    timeRange.value = ['', '']
  }
  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
      startTime: listQuery.value.startTime, // 开始时间
      endTime: listQuery.value.endTime, // 结束时间
    }
    exportDepComprehensiveList(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
  })
}

onMounted(() => {
  fetchUsersDept() // 获取部门信息
  listQuery.value.startTime = dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss')
  listQuery.value.endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  title.value = `部门综合分析 (${listQuery.value.startTime} ~ ${listQuery.value.endTime})`
  timeRange.value = [listQuery.value.startTime, listQuery.value.endTime]
  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"
          style="width: 200px;"
        >
          <el-option
            v-for="item in standardUsersDeptList"
            :key="item.deptId"
            :label="item.organizeName"
            :value="item.deptId!"
          />
        </el-select>
      </search-item>

      <search-item>
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </search-item>
    </search-area>
    <table-container :title="title" :is-center="true">
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/business/board/depOutputAnalysis/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/business/board/depOutputAnalysis/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>
