<!-- 证书报告列表  -->
<script lang="ts" setup name="ReportOnCredentialslist">
import type { PropType, Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IList, IListQuery, dictType } from './report_interface'
import type { IButton, ISupplier, IlistTypes, supplierExportQuery } from '@/views/measure/source/list_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import {
  approvalDeleteReport,
  draftDeleteReport,
  exportReportList,
  getReportList,
  submitReport,
} from '@/api/business/lab/report'
import ApprovalDialog from '@/components/Approval/ApprovalDialogByProcess.vue'
import { printJSON } from '@/utils/printUtils'
import { SCHEDULE } from '@/utils/scheduleDict'
import { cancelApproval } from '@/api/approval'
import { getDictByCode } from '@/api/system/dict'
import { exportFile } from '@/utils/exportUtils'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
const props = defineProps({
  status: {
    type: String,
  },
  buttons: {
    type: Array as PropType<IButton[]>,
    default: () => [],
  },
})
const { proxy } = getCurrentInstance() as any
// 操作列宽度-计算属性
const operationWidth = computed(() => {
  return props.buttons.length * 40 + 20
})
const mesureCategoryList = ref<dictType[]>([]) // 校检类别
// 查询条件
const listQuery = ref<IListQuery>({
  approvalStatus: '', // 审批状态 -- 全部
  certificateReportCode: '', // 证书号
  customerName: '', // 委托方名称
  measureCategory: '', // 检校类别
  orderCode: '', // 委托单编号
  sampleName: '', // 样品名称
  sampleNo: '', // 样品编号
  formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS,
  offset: 1,
  limit: 20,
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'reportOnCredentialsList', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('reportOnCredentialsList') || {
  approvalStatus: '', // 审批状态 -- 全部
  certificateReportCode: '', // 证书号
  customerName: '', // 委托方名称
  measureCategory: '', // 检校类别
  orderCode: '', // 委托单编号
  sampleName: '', // 样品名称
  sampleNo: '', // 样品编号
  formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS,
  offset: 1,
  limit: 20,
}
const approvalStatusReserveMap = ref({}) as any// 审批状态字典{草稿箱: 1}
// 表格数据
const list = ref<IList[]>([])
// 总数
const total = ref(0)
// 表头
const columns = ref<TableColumn[]>([
  { text: '证书号', value: 'certificateReportCode', width: '160', align: 'center' },
  { text: '证书名称', value: 'certificateReportName', align: 'center' },
  { text: '样品编号', value: 'sampleNo', align: 'center', width: '160' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '委托单编号', value: 'orderCode', width: '160', align: 'center' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '检校类别', value: 'measureCategoryName', align: 'center' },
  { text: '检定人员', value: 'measurePersonName', align: 'center' },
  { text: '审批状态', value: 'approvalStatusName', align: 'center', width: '110' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
])
// 初始化路由
const $router = useRouter()
// 选中的内容
const checkoutList = ref<string[]>([])
// 表格loadingTable
const loadingTable = ref(false)

// 获取字典值
async function getDict() {
  // 校检类别
  const response = await getDictByCode('measureCategory')
  mesureCategoryList.value = response.data

  // 审批状态
  const res = await getDictByCode('approvalStatus')
  // 审批状态字典 {草稿箱: 1}
  res.data.forEach((item: any) => {
    approvalStatusReserveMap.value[item.name] = `${item.value}`
  })
}
// 获取列表数据
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页，否则跳转第一页
  //   listQuery.value.offset = 1
  // }
  if (listQuery.value.approvalStatus === '') {
    listQuery.value.approvalStatus = '0'
  }
  getReportList(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}

// 多选选中
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 点击删除
const handleDelete = (row: IList) => {
  ElMessageBox.confirm(
    '确认删除所选记录吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    draftDeleteReport({ ids: [row.id] }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        fetchData(true)
      }
    })
  })
}
// 取消
const handleCancel = (row: IList) => {
  const params = {
    processInstanceId: row.processId!,
    comments: '',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      cancelApproval(params).then(() => {
        ElMessage.success('已取消')
        fetchData(true)
      })
    })
}

const approvalDialog = ref()

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

// 点击重置
const clearList = () => {
  listQuery.value = {
    approvalStatus: props.status! || '0', // 审批状态
    certificateReportCode: '', // 证书号
    customerName: '', // 委托方名称
    measureCategory: '', // 检校类别
    orderCode: '', // 委托单编号
    sampleName: '', // 样品名称
    sampleNo: '', // 样品编号
    formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS,
    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 goDetail = (row: any, pageType: 'detail' | 'edit') => {
  let from = ''
  if (row.approvalStatusName === '草稿箱') {
    from = 'caogao'
  }
  else if (row.approvalStatusName === '未通过-驳回') {
    from = 'reject'
  }
  $router.push({
    path: `/lab/reportOnCredentialsApproval/${pageType}/${row.id}`,
    query: {
      from,
      processId: row.processId,
      row: JSON.stringify(row),
    },
  })
}
// 新建证书报告
const add = () => {
  $router.push('/lab/reportOnCredentialsApproval/add')
}

// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}

// 提交
const approvalSubmit = (row: IList) => {
  ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    submitReport({
      id: row.id,
      formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS,
    }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('已提交')
        fetchData(true)
      }
    })
  })
}

// 点击数据后的操作按钮
const clickBtn = (row: IList, buttonType: string) => {
  switch (buttonType) {
    case '查看':
      goDetail(row, 'detail')
      break
    case '提交':
      approvalSubmit(row)
      break
    case '编辑':
      goDetail(row, 'edit')
      break
    case '同意':
      approvalDialog.value.initDialog('agree', row.taskId, row.id, row.decisionItem)
      break
    case '驳回':
      approvalDialog.value.initDialog('reject', row.taskId, row.id, row.decisionItem)
      break
    case '拒绝':
      approvalDialog.value.initDialog('refuse', row.taskId, row.id)
      break
    case '取消':
      handleCancel(row)
      break
    case '删除':
      handleDelete(row)
      break
  }
}

// 监听status变化，更新approvalStatus
watch (
  () => props.status,
  (newVal) => {
    listQuery.value.approvalStatus = newVal!
    window.sessionStorage.setItem('reportOnCredentials', newVal!)
    // fetchData(true)
    fetchData(false)
  },
)

// 打印列表
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 => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '证书报告列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

onMounted(async () => {
  await getDict() // 获取字典
  if (window.sessionStorage.getItem('reportOnCredentials')) {
    listQuery.value.approvalStatus = window.sessionStorage.getItem('reportOnCredentials')!
  }
  else {
    listQuery.value.approvalStatus = approvalStatusReserveMap.value['全部']
  }
  fetchData(true)
})
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input v-model.trim="listQuery.certificateReportCode" placeholder="证书号" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.orderCode" placeholder="委托单编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.customerName" placeholder="委托方名称" clearable />
      </search-item>
      <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-select
          v-model="listQuery.measureCategory"
          placeholder="请选择检校类别"
          style="width: 195px;"
          clearable
        >
          <el-option
            v-for="item in mesureCategoryList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/lab/reportOnCredentialsApproval/add')" icon="icon-add" title="新建" type="primary" @click="add" />
        <!-- <icon-button v-if="proxy.hasPerm('/lab/reportOnCredentialsApproval/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" /> -->
        <icon-button v-if="proxy.hasPerm('/lab/reportOnCredentialsApproval/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" :width="operationWidth" fixed="right">
            <template #default="{ row }">
              <!-- <el-button
                v-for="(item, index) in buttons"
                :key="index"
                size="small"
                :type="item.type" link
                :disabled="row.approvalStatusName !== '未通过-驳回' && item.name === '编辑'"
                @click="clickBtn(row, item.name)"
              >
                {{ item.name }}
              </el-button> -->
              <el-button
                size="small"
                type="primary"
                link
                @click="clickBtn(row, '查看')"
              >
                查看
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/agree') && row.approvalStatusName === '待审批'"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/regect') && row.approvalStatusName === '待审批' && row.decisionItem !== 3"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '驳回')"
              >
                驳回
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/refuse') && row.approvalStatusName === '待审批' && row.decisionItem !== 2"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '拒绝')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/edit') && row.approvalStatusName === '未通过-驳回' || row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                size="small"
                link
                type="primary"
                @click="clickBtn(row, '编辑')"
              >
                编辑
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                size="small"
                link
                type="primary"
                @click="clickBtn(row, '提交')"
              >
                提交
              </el-button>
              <!-- 是发起者且审批中可以取消 -->
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/cancel') && row.approvalStatusName === '审批中'"
                size="small"
                link
                type="info"
                :disabled="row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '取消')"
              >
                取消
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/delete') && row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回' && row.approvalStatusName !== '审批中' && row.approvalStatusName !== '待审批'"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                @click="clickBtn(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
  <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
</template>

