<!-- 装置到期提醒列表 -->
<script lang="ts" setup name="StandardReminderList">
import type { Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { IOptions, IexpiraListQuery } from '@/views/device/standardEquipment/standard_interface'
import { getTypeSelect } from '@/api/system/price'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { exportRemindList, getRemindListPage, getStandardListDelete, getUsersDept, setRemind } from '@/api/device/standard'
import { exportFile } from '@/utils/exportUtils'
import { printJSON } from '@/utils/printUtils'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
// 逻辑代码
const listQuery: Ref<IexpiraListQuery> = ref({
  category: '', // 类别
  id: '', // 主键id
  managerState: '', // 管理状态
  preparationEndDate: '', // 结束时间
  preparationStartDate: '', // 开始时间
  standardLaboratory: '', // 标准所在部门
  standardName: '', // 标准名称
  standardNo: '', // 标准编号
  validEndTime: '', // 结束时间
  validStartTime: '', // 开始时间
  offset: 1, // 当前页
  limit: 20, // 每页多少条
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'standardReminder', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('standardReminder') || {
  category: '', // 类别
  id: '', // 主键id
  managerState: '', // 管理状态
  preparationEndDate: '', // 结束时间
  preparationStartDate: '', // 开始时间
  standardLaboratory: '', // 标准所在部门
  standardName: '', // 标准名称
  standardNo: '', // 标准编号
  validEndTime: '', // 结束时间
  validStartTime: '', // 开始时间
  offset: 1, // 当前页
  limit: 20, // 每页多少条
}
// 获取权限
const { proxy } = getCurrentInstance() as any
const list = ref([]) // 存放数据
// 表头
const columns = ref<TableColumn[]>([
  {
    text: '标准代码',
    value: 'standardNo',
    width: '160',
    align: 'center',
  },
  {
    text: '标准名称',
    value: 'standardName',
    width: '90',
    align: 'center',
  },
  {
    text: '管理状态',
    value: 'managerStateName',
    width: '100',
    align: 'center',
  },
  {
    text: '标准所在部门',
    value: 'standardLaboratoryName',
    width: '120',
    align: 'center',
  },
  {
    text: '负责人',
    value: 'laboratoryOwnerName',
    align: 'center',
  },
  {
    text: '建标项目',
    value: 'constructionStandardUnitName',
    align: 'center',
  },
  {
    text: '筹建日期',
    value: 'preparationDate',
    width: '120',
    align: 'center',
  },
  {
    text: '有效日期',
    value: 'validTime',
    width: '120',
    align: 'center',
  },
])
const total = ref(0)
// 表格loding
const loadingTable = ref(false)
// 选中的数据
const checkoutList = ref([])
// 点击的类型
const buttonType = ref('')
// 类别下拉框
const checkTypeOptions = ref<IOptions[]>([])
// 管理状态下拉框
const standardManagerStateList = ref<IOptions[]>([])
// 标准所在部门下拉框
const standardUsersDeptList = ref<IOptions[]>([])
// 筹建日期
const preparation = ref<string>('')
// 到期开始以及结束
const validTime = ref<string>('')
watch(preparation, (val) => {
  if (val) {
    listQuery.value.preparationStartDate = `${val[0]}`
    listQuery.value.preparationEndDate = `${val[1]}`
  }
  else {
    listQuery.value.preparationStartDate = ''
    listQuery.value.preparationEndDate = ''
  }
})
// 有效日期变更
watch(validTime, (val) => {
  if (val) {
    listQuery.value.validStartTime = `${val[0]}`
    listQuery.value.validEndTime = `${val[1]}`
  }
  else {
    listQuery.value.validStartTime = ''
    listQuery.value.validEndTime = ''
  }
})
// 获取数据
const fetchData = (isNowPage: boolean) => {
  // listQuery.value.preparationStartDate = preparation.value[0] || ''
  // listQuery.value.preparationEndDate = preparation.value[1] || ''
  // listQuery.value.validStartTime = validTime.value[0] || ''
  // listQuery.value.validEndTime = validTime.value[1] || ''
  loadingTable.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页，否则跳转第一页
  //   listQuery.value.offset = 1
  // }
  getRemindListPage(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: any) => {
      return {
        ...item,
        preparationDate: item.preparationDate ? dayjs(item.preparationDate).format('YYYY-MM-DD') : '',
        validTime: item.validTime ? dayjs(item.validTime).format('YYYY-MM-DD') : '',
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
onMounted(() => {
  fetchData(true)
})
// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 获取下拉框
const getSelectList = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'standardCategory') {
      checkTypeOptions.value = res.data
    }
    else if (code === 'standardManagerState') {
      standardManagerStateList.value = res.data
    }
  })
}
getSelectList('standardCategory') // 获取类别下拉框
getSelectList('standardManagerState') // 获取管理状态下拉框

// 初始化路由
const $router = useRouter()
// 获取部门信息参数
const DeptParams = ref({
  createEndTime: '',
  createstartTime: '',
  director: '',
  meterMajor: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '3', // 3科室
  pdeptId: null,
  offset: 1,
  limit: 999999,
})
// 获取部门信息
getUsersDept(DeptParams.value).then((res) => {
  standardUsersDeptList.value = res.data.rows
})
// 点击重置
const clearList = () => {
  listQuery.value = {
    category: '', // 类别
    id: '', // 主键id
    managerState: '', // 管理状态
    preparationEndDate: '', // 结束时间
    preparationStartDate: '', // 开始时间
    standardLaboratory: '', // 标准所在部门
    standardName: '', // 标准名称
    standardNo: '', // 标准编号
    validEndTime: '', // 结束时间
    validStartTime: '', // 开始时间
    offset: 1, // 当前页
    limit: 20, // 每页多少条
  }
  preparation.value = ''
  validTime.value = ''
  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 handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}
// 导出id类型
interface ISupplier {
  id: never
}
// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item: TableColumn) => {
    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: ISupplier) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '到期提醒列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      category: listQuery.value.category, // 类别
      id: listQuery.value.id, // 主键id
      managerState: listQuery.value.managerState, // 管理状态
      preparationEndDate: listQuery.value.preparationEndDate, // 结束时间
      preparationStartDate: listQuery.value.preparationStartDate, // 开始时间
      standardLaboratory: listQuery.value.standardLaboratory, // 标准所在部门
      standardName: listQuery.value.standardName, // 标准名称
      standardNo: listQuery.value.standardNo, // 标准编号
      validEndTime: listQuery.value.validEndTime, // 结束时间
      validStartTime: listQuery.value.validStartTime, // 开始时间
      offset: 1, // 当前页
      limit: 20, // 每页多少条
      ids: checkoutList.value,
    }
    // 导出接口
    exportRemindList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '到期提醒列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  // 关闭loading
  loading.close()
}
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
  standardName: string
  standardOwnerName: string
}

// 点击详情
const handleEdit = (row: rowReturn) => {
  $router.push(`/board/detail/${row.id}`)
}
// 提醒函数
const warnClick = (row: rowReturn) => {
  ElMessageBox.confirm(
    `确认催办${row.standardOwnerName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      setRemind({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '已催办',
          })
          fetchData(true)
        }
      })
    })
}
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.standardNo"
          placeholder="标准代码"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.standardName"
          placeholder="标准名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-select
          v-model.trim="listQuery.standardLaboratory"
          clearable style="width: 200px;"
          placeholder="标准所在部门"
          size="default"
        >
          <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="preparation"
          type="daterange"
          range-separator="到"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="筹建开始日期"
          end-placeholder="筹建结束日期"
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/standard/expiration/remind/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/standard/expiration/remind/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" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleEdit(row)"
              >
                详情
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/standard/expiration/remind/warn')"
                size="small"
                link
                type="primary"
                @click="warnClick(row)"
              >
                催办
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

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