<script lang="ts" setup name="CustomerList">
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage } from 'element-plus'
import type { ICerPrintList, ICertPrintSearch } from './cert-interface'
import DistributeDialog from './components/distributeDialog.vue'
import BarCodeBind from '@/components/BarCodeBind/index.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'
import { exportTaskList, getTaskList } from '@/api/business/task'
import type { dictType } from '@/global'
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
// 右上角按钮
const menus = [
  { name: '未打印', value: '未打印' },
  { name: '全部', value: '全部' },
  { name: '待审批', value: '待审批' },
  { name: '已通过', value: '已通过' },
  { name: '未通过', value: '未通过' },
]
const currentMenu = ref('未打印') // 当前选中状态
// 查询条件
const listQuery = ref<ICertPrintSearch>({
  certificationReportCode: '', // 证书编号
  orderNo: '', // 委托书编号
  customerName: '', // 委托方名称
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  certificateReportType: '', // 证书类型
  printNum: '', // 打印次数 -未打印和全部用
  approvalStatus: '', // 审批状态-审批查询用
  formId: 'jlglsygfsp',
  offset: 1,
  limit: 20,
})
// --------------获取所需字典值----------------
const certificationClassList = ref<dictType[]>([]) // 样品属性列表
function getDict() {
  // 获取样品属性
  getDictByCode('certificationClass').then((response) => {
    certificationClassList.value = response.data
  })
}
getDict()

// 表头
const columns = ref<TableColumn[]>([
  { text: '证书编号', value: 'certificationReportCode', align: 'center' },
  { text: '证书名称', value: 'certificationReportName', align: 'center' },
  { text: '样品编号', value: 'sampleNo', width: '110', 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: 'certificateReportTypeName', align: 'center' },
  { text: '打印状态', value: '', align: 'center', width: '85px', filter: (row: ICerPrintList) => { return row.printNum == 0 ? '未打印' : `${row.printNum}次打印` } },
  { text: '生成时间', value: 'createTime', align: 'center', width: '165px' },
])
// 表格数据
const list = ref<ICerPrintList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])

// 根据过滤查询条件
function filterQuery() {
  switch (currentMenu.value) {
    case '未打印':
      listQuery.value.printNum = 0
      listQuery.value.approvalStatus = ''
      break
    case '全部':
      listQuery.value.printNum = 0
      listQuery.value.approvalStatus = ''
      break
    case '待审批':
      listQuery.value.printNum = ''
      listQuery.value.approvalStatus = '1'
      break
    case '审批中':
      listQuery.value.printNum = ''
      listQuery.value.approvalStatus = '2'
      break
    case '已通过':
      listQuery.value.printNum = ''
      listQuery.value.approvalStatus = '3'
      break
    case '未通过':
      listQuery.value.printNum = ''
      listQuery.value.approvalStatus = '4'
      break
  }
}

// 数据查询
function fetchData(isNowPage = false) {
  filterQuery()
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  // 模拟数据
  list.value = [
    { certificationId: '1', certificationReportCode: '12345614', certificationReportName: '力学检定证书', orderId: '1', sampleNo: '1yp123456', sampleName: '压力表', sampleModel: 'xx', manufacturingNo: 'xx', orderNo: 'wtd123456', customerNo: 'kh123456', customerName: '北京无线电测量研究所', createTime: '2023-02-01 08:00:00', printNum: 0, printStatus: '0', printStatusName: '未打印', certificateReportTypeName: '自检', approvalStatusName: '待审批' },
    { certificationId: '1', certificationReportCode: '12345614', certificationReportName: '力学检定证书', orderId: '1', sampleNo: '1yp123457', sampleName: '压力表', sampleModel: 'xx', manufacturingNo: 'xx', orderNo: 'wtd123456', customerNo: 'kh123456', customerName: '北京无线电测量研究所', createTime: '2023-02-01 08:00:00', printNum: 0, printStatus: '1', printStatusName: '已打印', certificateReportTypeName: '自检', approvalStatusName: '待审批' },
  ]
  loadingTable.value = false
  console.log(listQuery.value)
  // 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: { id: string }) => item.id)
}

// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    certificationReportCode: '', // 证书编号
    orderNo: '', // 委托书编号
    customerName: '', // 委托方名称
    sampleNo: '', // 样品编号
    sampleName: '', // 样品名称
    certificateReportType: '', // 证书类型
    printNum: '', // 打印次数 -未打印和全部用
    approvalStatus: '', // 审批状态-审批查询用
    formId: 'jlglsygfsp',
    offset: 1,
    limit: 20,
  }
}
// 点击详情
const handleDetail = (row: ICerPrintList) => {
  $router.push(`/schedule/cert/detail/${row.certificationId}?printStatus=${row.printStatus}`)
}

// 点击分发， 弹窗
const distributeDialogRef = ref()
const handleDistribute = (row: ICerPrintList) => {
  // distributeDialogRef.value.initDialog(row.orderId, row.sampleId)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    // const params = {
    //   bussinessSize: listQuery.value.bussinessSize, // 业务规模
    //   customerName: listQuery.value.customerName, // 公司名称
    //   customerNo: listQuery.value.customerNo, // 任务分发编号
    //   grade: listQuery.value.grade, // 履约评级
    //   ids: checkoutList.value,
    // }
    // exportCustomerList(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: ICerPrintList) => checkoutList.value.includes(item.certificationId))
    printJSON(printList, properties, '证书打印列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 选择按钮变更
watch(currentMenu, (val: string) => {
  fetchData(false)
})

fetchData(false)
</script>

<template>
  <app-container>
    <div class="float-radio-buttons">
      <!-- 三级菜单 -->
      <el-radio-group v-model="currentMenu">
        <el-radio-button v-for="item in menus" :key="item.name" :label="item.value">
          {{ item.name }}
        </el-radio-button>
      </el-radio-group>
    </div>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.certificationReportCode"
          placeholder="证书编号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.orderNo"
          placeholder="委托书编号"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerName"
          placeholder="委托方名称"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleName"
          placeholder="样品名称"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.certificateReportType" placeholder="证书类型" style="width: 120px;" clearable>
          <el-option v-for="item in certificationClassList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/meter/customer/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/meter/customer/export')" 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 #columns>
          <el-table-column v-if="listQuery.printNum === ''" label="审批状态" align="center" width="90px" prop="approvalStatusName" />
          <el-table-column label="操作" align="center" fixed="right" width="120">
            <template #default="{ row }">
              <el-button size="small" link type="primary" @click="handleDetail(row)">
                详情
              </el-button>
              <el-button v-if="listQuery.printNum === 0 || (listQuery.approvalStatus === '3')" size="small" link type="primary" @click="bindLabel(row)">
                打印
              </el-button>
              <el-button v-if="listQuery.approvalStatus === '1'" size="small" type="primary" link @click="handleDistribute(row)">
                同意
              </el-button>
              <el-button v-if="listQuery.approvalStatus === '1'" size="small" type="primary" link @click="handleDistribute(row)">
                拒绝
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss" scoped>
.short-input {
  width: 160px;
}
</style>
