<script lang="ts" setup name="CustomerList">
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
// import { Row } from 'element-plus/es/components/table-v2/src/components'
import type { ICerPrintList, ICertPrintSearch } from './cert-interface'
import ApprovalDialogPart from './components/ApprovalDialogPart.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 { exportCert, getCertList, submitApproval } from '@/api/business/cert'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { dictType } from '@/global'
import ButtonBox from '@/components/buttonBox/buttonBox.vue'
import type { IMenu } from '@/components/buttonBox/buttonBox'

const { proxy } = getCurrentInstance() as any
const $router = useRouter()
// 右上角按钮
const menu = ref<IMenu[]>([]) // 右上角审批状态按钮组合
const active = ref('') // 选中的按钮
const activeTitle = ref('') // active对应的审批状态名字
// 查询条件
const listQuery = ref<ICertPrintSearch>({
  certificationReportCode: '', // 证书编号
  orderNo: '', // 委托书编号
  customerName: '', // 委托方名称
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  certificateReportType: '', // 证书类型
  printNum: '', // 打印次数 -未打印和全部用
  approvalStatus: '', // 审批状态-审批查询用
  orderId: '0', // 委托书id
  reason: '', // 操作原因
  sampleId: '0', // 样品id
  status: '', // 状态变更(无需检测状态7,收入状态2,归还6，回退状态2.5.1,终止5)
  formId: SCHEDULE.BUSINESS_CERT_PRINT,
  offset: 1,
  limit: 20,
})
const approvalDialogPart = ref() // 审批组件
// --------------获取所需字典值----------------
const certificationClassList = ref<dictType[]>([]) // 样品属性列表
function getDict() {
  // 获取样品属性
  getDictByCode('certificationClass').then((response) => {
    certificationClassList.value = response.data
  })
  getDictByCode('approvalStatus').then((response) => {
    // 审批状态字典 {1：草稿箱}
    // response.data.forEach((item: any) => {
    //   approvalStatusMap.value[`${item.value}`] = item.name
    // })

    // 审批状态字典 {草稿箱: 1}
    // response.data.forEach((item: any) => {
    //   approvalStatusReserveMap.value[item.name] = `${item.value}`
    // })
    // 制作右上角的菜单
    response.data.forEach((item: dictType) => {
      if (item.name === '可打印' || item.name === '全部'
      || item.name === '待审批' || item.name === '审批中'
      || item.name === '已通过' || item.name === '未通过'
      ) {
        if (item.name === '可打印') {
          active.value = item.value
          activeTitle.value = item.name
          menu.value.unshift({
            name: item.name,
            id: `${item.value}`,
          })
        }
        else {
          menu.value.push({
            name: item.name,
            id: `${item.value}`,
          })
        }
      }
    })
  })
}

// 表头
const columns = ref<TableColumn[]>([
  { text: '证书编号', value: 'certificationReportCode', width: '110', align: 'center' },
  { text: '证书名称', value: 'certificationReportName', width: '120', align: 'center' },
  { text: '样品编号', value: 'sampleNo', width: '110', align: 'center' },
  { text: '样品名称', value: 'sampleName', width: '120', align: 'center' },
  { text: '型号', value: 'sampleModel', width: '120', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', width: '120', align: 'center' },
  { text: '委托书编号', value: 'orderNo', width: '120', align: 'center' },
  { text: '检校类别', value: 'customerNo', width: '120', align: 'center' },
  { text: '检定人员', value: 'customerName', width: '120', align: 'center' },
  { text: '证书类型', value: 'certificateReportTypeName', width: '120', 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() {
  console.log(activeTitle)
  switch (activeTitle.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
  }
  // 模拟数据
  loadingTable.value = false
  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: '待审批', taskId: '100', id: '10' },
    { 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: '待审批', taskId: '1001', id: '101' },
  ]
  // getCertList(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: '', // 审批状态-审批查询用
    orderId: '0', // 委托书id
    reason: '', // 操作原因
    sampleId: '0', // 样品id
    status: '', // 状态变更(无需检测状态7,收入状态2,归还6，回退状态2.5.1,终止5)
    formId: SCHEDULE.BUSINESS_CERT_PRINT,
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}
// 点击详情
const handleDetail = (row: ICerPrintList) => {
  $router.push(`/schedule/cert/detail/${row.certificationId}?printStatus=${row.printStatus}`)
}

// 点击分发， 弹窗
const distributeDialogRef = ref()
const handleDistribute = (row: ICerPrintList, status: string) => {
  if (status === 'agree') {
    approvalDialogPart.value.initDialog('agree', row.taskId)
  }
  else {
    approvalDialogPart.value.initDialog('refuse', row.taskId, row.id)
  }
}

// 审批结束回调
const approvalSuccess = () => {
  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 exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    // const params = {
    //   ...listQuery.value,
    //   ids: checkoutList.value,
    // }
    // exportCert(params).then((res) => {
    //   const blob = new Blob([res.data])
    //   exportFile(blob, '证书打印列表.xlsx')
    // })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 打印
const bindLabel = (row: ICerPrintList) => {
  console.log(1)
  row.printNum = 1
  // 判断状态第一次可以直接打印,之后的打印需要审批
  if (row.printNum == 1) {
    ElMessageBox.confirm(
      '确定要打印吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
      exportCert({ orderId: row.orderId, reason: row.reason, sampleId: row.sampleId, status: row.status }).then((res) => {
        console.log(res)
      })
    })
  }
  else {
    ElMessageBox.confirm(
      '打印前需申请   确定要打印吗?',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
      },
    ).then(() => {
      submitApproval({ id: row.id, formId: listQuery.value.formId }).then((res) => {
        console.log(res)
        if (res === 200) {
          ElMessageBox.confirm(
            '已经发送申请！',
            '确认操作',
            {
              type: 'success',
            },
          )
        }
      })
    })
  }
}

// 打印列表
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('无可打印内容')
  }
}

// 按钮切换
const changeCurrentButton = (val: string) => {
  active.value = val
  activeTitle.value = menu.value.find(item => item.id === val)!.name
  window.sessionStorage.setItem('buttonBoxActive', val)
  clearList()
}

onMounted(async () => {
  await getDict() // 获取字典-审批状态
  if (window.sessionStorage.getItem('buttonBoxActive') !== 'undefined' && window.sessionStorage.getItem('buttonBoxActive') !== '') {
    active.value = window.sessionStorage.getItem('buttonBoxActive')!
  }
  else {
    active.value = menu.value.find(item => item.name === '可打印')!.id // 可打
    activeTitle.value === '可打印'
  }
  fetchData(true)
})
onUnmounted(() => {
  window.sessionStorage.setItem('buttonBoxActive', '') // 清除
})
</script>

<template>
  <app-container>
    <approval-dialog-part ref="approvalDialogPart" @on-success="approvalSuccess" />
    <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, 'agree')">
                同意
              </el-button>
              <el-button v-if="listQuery.approvalStatus === '1'" size="small" type="primary" link @click="handleDistribute(row, 'refuse')">
                拒绝
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <button-box :active="active" :menu="menu" @changeCurrentButton="changeCurrentButton" />
  </app-container>
</template>

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