<!-- 样品超期提醒列表页 -->
<script lang="ts" setup name="OverdueReminderList">
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IList, IListQuery } from './overdueReminder_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { exportTaskList, getTaskList } from '@/api/business/schedule/task'
import { interchangeListUrge } from '@/api/business/schedule/interchangeList'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  orderNo: '', // 委托单编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  isUrgent: '', // 是否加急
  sampleBelong: '', // 样品属性
  startTime: '', // 应检完时间-开始
  endTime: '', // 应检完时间-结束
  sampleStatus: '8', // 样品状态:8已超期
  offset: 1,
  limit: 20,
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'overdueReminder', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('overdueReminder') || {
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  orderNo: '', // 委托单编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  isUrgent: '', // 是否加急
  sampleBelong: '', // 样品属性
  startTime: '', // 应检完时间-开始
  endTime: '', // 应检完时间-结束
  sampleStatus: '8', // 样品状态:8已超期
  offset: 1,
  limit: 20,
}
// 表头
const columns = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', width: '160', align: 'center' },
  { text: '样品名称', value: 'sampleName', width: '120', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '委托单编号', value: 'orderNo', align: 'center' },
  { text: '委托方代码', value: 'customerNo', align: 'center' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '送检人', value: 'deliverer', align: 'center' },
  { text: '送达时间', value: 'realDeliverTime', align: 'center', width: '180' },
  { text: '当前节点', value: 'currentSegment', align: 'center' },
  { text: '应检完时间', value: 'requireOverTime', align: 'center', width: '180' },
  // { text: '备注', value: 'remark', align: 'center' },
])
// 表格数据
const list = ref<IList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页，否则跳转第一页
  //   listQuery.value.offset = 1
  // }
  getTaskList(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

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

// 点击详情
const handleEdit = (row: IList) => {
  $router.push(`/board/overdueReminderDetail/${row.sampleId}?order=${row.orderId}`)
}

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

// 点击重置
const clearList = () => {
  listQuery.value = {
    sampleNo: '', // 样品编号
    sampleName: '', // 样品名称
    orderNo: '', // 委托单编号
    customerNo: '', // 委托方代码
    customerName: '', // 委托方名称
    isUrgent: '', // 是否加急
    sampleBelong: '', // 样品属性
    startTime: '', // 应检完时间-开始
    endTime: '', // 应检完时间-结束
    sampleStatus: '8', // 样品状态:8已超期
    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(() => {
      interchangeListUrge({ orderId: row.orderId, reason: '', sampleId: row.sampleId, status: '' }).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 = {
      sampleNo: listQuery.value.sampleNo, // 样品编号
      sampleName: listQuery.value.sampleName, // 样品名称
      orderNo: listQuery.value.orderNo, // 委托单编号
      customerNo: listQuery.value.customerNo, // 委托方代码
      customerName: listQuery.value.customerName, // 委托方名称
      isUrgent: listQuery.value.isUrgent, // 是否加急
      sampleBelong: listQuery.value.sampleBelong, // 样品属性
      startTime: listQuery.value.startTime, //	应检定开始时间
      endTime: listQuery.value.endTime, //	应检定结束时间
      sampleStatus: '8', // 样品状态 -- 8已超期
      ids: checkoutList.value,
    }
    exportTaskList(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('无可打印内容')
  }
}

onMounted(() => {
  fetchData(true)
})
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleNo"
          placeholder="样品编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleName"
          placeholder="样品名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.orderNo"
          placeholder="委托单编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerNo"
          placeholder="委托方代码"
          clearable
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/sample/list/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/sample/list/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" @multi-select="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') && row.currentSegment && row.currentSegment !== '待分配'"
                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>
