<!-- 设备到期提醒列表页 -->
<script lang="ts" setup name="equipmentReminderList">
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { IList, IListQuery, dictType } from './equipmentReminder-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import { getUserList } from '@/api/system/user'
import type { userType } from '@/views/system/user/user-interface'
import type { deptType } from '@/views/device/standingBook/standingBook-interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { exportEquipmentReminderList, getEquipmentReminderList, urgeEquipmentReminderList } from '@/api/business/board/equipmentReminder'
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
const useDeptList = ref<deptType[]>([]) // 部门列表
const usePersonList = ref<userType[]>([]) // 申请人列表（用户）
const usePersonOptions = ref<userType[]>([]) // 申请人列表（用户）--模糊搜索数据
const applyPersonLoading = ref(false) // 申请人模糊搜索框loading

// 查询条件
const listQuery: Ref<IListQuery> = ref({
  equipmentName: '',	// 设备名称
  equipmentNo: '',	// 设备编号
  mesureType: '', // 检定方式
  useDept: '', // 使用部门
  usePerson: '',	// 使用人
  offset: 1,
  limit: 20,
})
// 表头
const columns = ref<TableColumn[]>([
  { text: '设备编号', value: 'equipmentNo', align: 'center', width: '160' },
  { text: '名称', value: 'equipmentName', align: 'center' },
  { text: '型号', value: 'modelNo', align: 'center' },
  { text: 'ABC', value: 'abc', align: 'center', width: '58' },
  { text: '检定方式', value: 'mesureTypeName', align: 'center', width: '90' },
  { text: '管理状态', value: 'managerStateName', align: 'center', width: '100' },
  { text: '使用部门', value: 'useDeptName', align: 'center' },
  { text: '使用人', value: 'usePersonName', align: 'center' },
  { text: '有效日期', value: 'validDate', align: 'center', width: '120' },
  // { text: '备注', value: 'remark', align: 'center' },
])
// 表格数据
const list = ref<IList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])

// 获取数据
const mesureTypeList = ref<dictType[]>([]) // 检定方式
const managerStateList = ref<dictType[]>([]) // 管理状态
const abcList = ref<dictType[]>([]) // ABC
// 获取字典值
async function getDict() {
  // 获取检定方式
  getDictByCode('measureType').then((response) => {
    mesureTypeList.value = response.data
  })
  // 获取管理状态
  getDictByCode('managerState').then((response) => {
    managerStateList.value = response.data
  })
  // 获取ABC
  getDictByCode('ABC').then((response) => {
    abcList.value = response.data
  })
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getEquipmentReminderList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: { validDate: string }) => {
      return {
        ...item,
        validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : item.validDate,
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 点击详情
const handleEdit = (row: IList) => {
  // $router.push(`/board/equipmentReminderDetail/${row.id}`)
  $router.push({
    // name: 'EquipmentReminderDetail',
    path: `/board/equipmentReminderDetail/detail/${row.id}`,
    // params: {
    //   type: 'detail',
    // },
    query: {
      title: '详情',
      name: '固定资产',
      id: row.id,
    },
  })
}

// 点击搜索
const search = () => {
  fetchData(true)
}

// 点击重置
const reset = () => {
  listQuery.value = {
    equipmentName: '',	// 设备名称
    equipmentNo: '',	// 设备编号
    mesureType: '', // 检定方式
    useDept: '', // 使用部门
    usePerson: '',	// 使用人
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}

// 催办
const urge = (row: IList) => {
  ElMessageBox.confirm(
    '确认催办吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      urgeEquipmentReminderList({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('已催办')
          fetchData(true)
        }
      })
    })
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      equipmentName: listQuery.value.equipmentName,	// 设备名称
      equipmentNo: listQuery.value.equipmentNo,	// 设备编号
      mesureType: listQuery.value.mesureType, // 检定方式
      useDept: listQuery.value.useDept, // 使用部门
      usePerson: listQuery.value.usePerson,	// 使用人
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    exportEquipmentReminderList(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 (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '设备到期提醒列表')
  }
  else if (checkoutList.value.length > 0) {
    const printList = list.value.filter((item: IList) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '设备到期提醒列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

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

// 获取用户列表(增加模糊查询)
const fetchUserList = () => {
  getUserList({ offset: 1, limit: 999999 }).then((res: any) => {
    usePersonList.value = res.data.rows
    usePersonOptions.value = res.data.rows
  })
}

// 获取使用部门
const fetchDeptTreeList = () => {
  getDeptTreeList().then((res: any) => {
    if (res.data) { // 将列表转树结构
      useDeptList.value = toTreeList(res.data, '0', true)
    }
  })
}

onMounted(async () => {
  await getDict() // 获取字典值
  fetchDeptTreeList() // 获取使用部门
  fetchUserList() // 获取人员列表
  fetchData() // 获取表格数据
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <search-item>
        <el-input v-model="listQuery.equipmentNo" placeholder="设备编号" clearable class="w-50 m-2" style="width: 185px;" />
      </search-item>
      <search-item>
        <el-input v-model="listQuery.equipmentName" placeholder="设备名称" clearable class="w-50 m-2" style="width: 185px;" />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.mesureType" class="m-2" placeholder="检定方式" clearable style="width: 185px;">
          <el-option
            v-for="item in mesureTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <dept-select v-model="listQuery.useDept" :data="useDeptList" placeholder="使用部门" style="width: 185px;" />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.usePerson"
          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-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/device/receive/applyList/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/device/receive/applyList/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
      </template>
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery"
        :list-loading="loadingTable" is-showmulti-select @change="changePage" @multiSelect="handleSelectionChange"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <!-- ------------------------------------------------- -->
        <template #columns>
          <el-table-column label="操作" align="center" fixed="right" width="120">
            <template #default="{ row }">
              <el-button
                size="small"
                link
                type="primary"
                @click="handleEdit(row)"
              >
                详情
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/urge') "
                size="small"
                link
                type="primary"
                @click="urge(row)"
              >
                催办
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

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