<!-- 计量数据管理列表 -->
<script lang="ts" setup name="MeasureDataList">
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { IList, IListQuery } from './measureData-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { getDictByCode } from '@/api/system/dict'
import selectApproverDialog from '@/components/Approval/selectApproverDialog.vue'
import type { dictType } from '@/global'
import type { IMenu } from '@/components/buttonBox/buttonBox'
// import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
// import ApprovalDialog from '@/components/Approval/ApprovalDialogByProcess.vue'
import ButtonBox from '@/components/buttonBox/buttonBox.vue'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
import { getStaffList } from '@/api/measure/person'
import { cancelApproval } from '@/api/approval'
import { SCHEDULE } from '@/utils/scheduleDict'
import ApprovalDialog from '@/components/Approval/ApprovalDialogCustom.vue'
import customApproval from '/public/config/customApproval.json'
import { deleteMeasureData, getMeasureDataList, submit } from '@/api/business/lab/measureData'
const { proxy } = getCurrentInstance() as any
const $router = useRouter() // 初始化路由
const approvalDialog = ref() // 审批对话ref
const $route = useRoute()
const TabActiveButton = 'BusinessLabMeasureData'
const menu = ref<IMenu[]>([]) // 审批状态按钮组合
const certificateReportCategoryDict = ref({}) as any
const active = ref('')
// 查询条件
const listQuery = ref<IListQuery>({
  sampleModel: '',
  manufacturingNo: '',
  measurePersonId: '',
  approvalStatus: active.value, // 审批状态
  certificateReportCode: '', //		证书编号
  certificateReportName: '', //		证书名称
  customerName: '', //		委托方名称
  formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS,
  measureCategory: '', //	检校类别
  certificateReportType: '', // 证书类别
  orderCode: '', //	委托单编号
  sampleName: '', //	样品名称
  sampleNo: '', //	样品编号
  offset: 1, // 当前页
  limit: 20, // 每页多少条
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'measureDataList', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('measureDataList') || {
  approvalStatus: active.value, // 审批状态
  certificateReportCode: '', //		证书编号
  certificateReportName: '', //		证书名称
  customerName: '', //		委托方名称
  formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS,
  measureCategory: '', //	检校类别
  orderCode: '', //	委托单编号
  sampleName: '', //	样品名称
  sampleNo: '', //	样品编号
  offset: 1, // 当前页
  limit: 20, // 每页多少条
}
// 多选选中
const checkoutList = ref<string[]>([])
const list = ref<IList[]>([]) // 数据列表
const total = ref(0) // 总条数
const certificationTypeList = ref<dictType[]>([]) // 证书类别
const loadingTable = ref(false) // 表格loading

// 表头
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: 'certificateReportCategoryName', align: 'center', width: '120' },
  { text: '委托单编号', value: 'orderCode_hide', align: 'center', followLink: true, width: '160' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '检定员', value: 'measurePerson', align: 'center' },
  { text: '证书附件', value: 'certificateReportFile', align: 'center', isLink: true, width: '460' },
  { text: '检校日期', value: 'calibrationTime', align: 'center', width: '120' },
])

// 列表数据查询
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getMeasureDataList(listQuery.value).then((response: any) => {
    list.value = response.data.rows.map((item: { certificateReportCategory: string; calibrationTime: string; orderCode: string; certificateReportFile: string; certificateReportName: string; calibrationMajorName: string; certificateReportCategoryName: string; certificateReportCode: string }) => {
      return {
        ...item,
        calibrationTime: item.calibrationTime ? dayjs(item.calibrationTime).format('YYYY-MM-DD') : item.calibrationTime,
        followLinkArr: [item.orderCode], // 委托单编号
        fileArr: [item.certificateReportFile], // 证书附件
        certificateReportCategoryName: item.certificateReportCategory ? certificateReportCategoryDict.value[item.certificateReportCategory] : item.certificateReportCategory, // 证书类别
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}

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

// 重置
const clearList = () => {
  listQuery.value = {
    sampleModel: '',
    manufacturingNo: '',
    measurePersonId: '',
    approvalStatus: active.value, // 审批状态
    certificateReportCode: '', //		证书编号
    certificateReportName: '', //		证书名称
    customerName: '', //		委托方名称
    formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS,
    measureCategory: '', //	检校类别
    certificateReportType: '', // 证书类别
    orderCode: '', //	委托单编号
    sampleName: '', //	样品名称
    sampleNo: '', //	样品编号
    offset: 1, // 当前页
    limit: 20, // 每页多少条
  }
  fetchData(true)
}

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

// 点击新建
const add = () => {
  $router.push('/lab/measureData/add')
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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)
}

// 打印列表
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('无可打印内容')
  }
}
// -----------------------------------提交-------------------------------------------------------
const selectApproverRef = ref() // 审批人自选组件ref
const submitRow = ref() // 要提交的数据
// 选好审批人
const confirmSelectApprover = async (approverList: string[] = []) => {
  if (!approverList.length) {
    ElMessage.warning('无审批人，无法提交！')
    return false
  }
  console.log('审批人', approverList)
  ElMessageBox.confirm(`是否提交计量数据管理 ${submitRow.value.certificateReportCode}-${submitRow.value.certificateReportName}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (submitRow.value.id) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      const params = {
        id: submitRow.value.id,
        formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS, // 表单id
        assignees: approverList,
      }
      submit(params).then(() => {
        ElMessage.success('提交成功')
        loading.close()
        fetchData(true)
      }).catch(() => {
        loading.close()
      })
    }
    else {
      ElMessage.warning('请先保存！')
    }
  })
}
// --------------------------------------------------------------------------------------

// 操作
const handleEdit = (row: IList, val: string, title = '') => {
  if (val === '取消') {
    const params = {
      processInstanceId: row.processId!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          fetchData(true)
        })
      })
  }
  else if (val === '删除') {
    ElMessageBox.confirm(
      '确认删除吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        deleteMeasureData({ ids: [row.id] }).then((res) => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        })
      })
  }
  else if (val === '提交') {
    submitRow.value = row
    selectApproverRef.value.initDialog()
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', row.taskId, row.id, row.decisionItem, row.processId, row.sampleId, row.orderId, row.invalid, row.measurePersonId)
    // approvalDialog.value.initDialog('agree', row.taskId, row.decisionItem)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', row.taskId, row.id, row.decisionItem)
    // approvalDialog.value.initDialog('reject', row.taskId, row.decisionItem)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', row.taskId, row.id)
    // approvalDialog.value.initDialog('refuse', row.taskId)
  }
  else if (val === 'detail' || val === 'edit') { // 详情和编辑
    $router.push({
      path: `/lab/measureData/${val}/${row.id}`,
      query: {
        formId: listQuery.value.formId,
        approvalStatusName: row.approvalStatusName, // 审批状态名称
        decisionItem: `${row.decisionItem}`, // 控制同意、驳回、拒绝按钮
        processId: row.processId, // 流程实例
        taskId: row.taskId, // 任务id，用于审批
        sampleId: row.sampleId,
        orderId: row.orderId,
        measurePersonId: row.measurePersonId,
      },
    })
  }
}
// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}
const userList: any = ref([]) // 计量人员列表
// 获取字典值
const getDict = async () => {
  // 审批状态
  const res = await getDictByCode('approvalStatus')
  // 制作右上角的菜单
  res.data.forEach((item: dictType) => {
    if (item.name === '全部' || item.name === '草稿箱'
      || item.name === '待审批' || item.name === '审批中'
      || item.name === '已通过' || item.name === '未通过'
      || item.name === '已取消') {
      menu.value.push({
        name: item.name,
        id: `${item.value}`,
      })
    }
  })

  // 证书类别
  const response = await getDictByCode('certificationType')
  certificationTypeList.value = response.data
  response.data.forEach((item: any) => {
    certificateReportCategoryDict.value[`${item.value}`] = item.name
  })

  // 获取计量人员列表
  const params = {
    staffNo: '', // 人员编号
    name: '', // 姓名
    deptId: '', // 工作部门
    major: '', // 计量专业
    verifierCertificateNo: '', // 证书号
    certificateStatus: '', // 证书状态
    limit: 100000,
    offset: 1,
  }
  // 获取人员列表
  getStaffList(params).then((res) => {
    userList.value = res.data.records
  })
}

// 切换tab状态
const changeCurrentButton = (val: string) => {
  active.value = val
  window.sessionStorage.setItem(TabActiveButton, val)
  listQuery.value.approvalStatus = active.value
  fetchData(true)
}

// 点击委托单编号
const handleClickFollowLink = (row: any) => {
  if (row.orderId) {
    $router.push({
      path: `/schedule/order/detail/${row.orderId}`,
    })
  }
  else {
    ElMessage.warning('此条数据没有委托单信息')
  }
}

onMounted(async () => {
  await getDict()
  if (window.sessionStorage.getItem(TabActiveButton)) {
    active.value = window.sessionStorage.getItem(TabActiveButton)!
  }
  else {
    active.value = menu.value.find(item => item.name === '全部')!.id as string // 全部
  }
})
</script>

<template>
  <app-container class="business-lab-measure-data">
    <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.certificateReportName"
          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.sampleName"
          placeholder="样品名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleModel"
          placeholder="型号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.manufacturingNo"
          placeholder="出厂编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.measurePersonId" filterable clearable placeholder="检定员"
        >
          <el-option v-for="(item) in userList" :key="item.id" :label="item.name" :value="item.id">
            <span style="float: left;">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px;">{{ item.deptName }}</span>
          </el-option>
        </el-select>
      </search-item>
      <search-item v-if="active === '0'">
        <el-select
          v-model="listQuery.certificateReportType"
          placeholder="证书类别"
          clearable
          style="width: 200px;"
        >
          <el-option
            v-for="item in certificationTypeList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button
          icon="icon-add"
          title="新建"
          type="primary"
          @click="add"
        />
        <!-- <icon-button
          v-if="proxy.hasPerm('/measure/train/plan/export')"
          icon="icon-export"
          title="导出"
          type="primary"
          @click="exportAll"
        /> -->
        <icon-button
          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"
        @handle-click-follow-link="handleClickFollowLink"
      >
        <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="(active === '0') ? 200 : (active === '1' || active === '6' || active === '3') ? 150 : (active === '4' || active === '5') ? 100 : 200"
          >
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleEdit(row, 'detail')"
              >
                查看
              </el-button>
              <el-button
                v-if=" row.approvalStatusName === '待审批'"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="handleEdit(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if=" row.approvalStatusName === '待审批' && row.decisionItem !== 3"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="handleEdit(row, '驳回')"
              >
                驳回
              </el-button>
              <el-button
                v-if=" row.approvalStatusName === '待审批' && row.decisionItem !== 2"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="handleEdit(row, '拒绝')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="(row.approvalStatusName === '未通过-驳回' && `${row.buttonFlag}` === '1') || row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '提交')"
              >
                提交
              </el-button>
              <!-- 是发起者且审批中可以取消 -->
              <el-button
                v-if="row.approvalStatusName === '审批中'"
                size="small"
                link
                type="info"
                :disabled="row.approvalStatusName !== '审批中'"
                @click="handleEdit(row, '取消')"
              >
                取消
              </el-button>
              <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
              <!-- <el-button
                v-if="row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回'"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                 @click="handleEdit(row, '删除')"
              >
                删除
              </el-button> -->
              <!-- ---------------------------审批中的删除按钮暂时去掉------------------------ -->
              <el-button
                v-if="row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回' && row.approvalStatusName !== '审批中' && row.approvalStatusName !== '待审批'"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                @click="handleEdit(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
      <!-- 审批弹窗 -->
      <approval-dialog ref="approvalDialog" :last-name="customApproval.approvalLastName.measureData" @on-success="approvalSuccess" />
      <!-- 选择审批人弹窗 -->
      <select-approver-dialog ref="selectApproverRef" @confirm="confirmSelectApprover" />
      <button-box :active="active" :menu="menu" @change-current-button="changeCurrentButton" />
    </table-container>
  </app-container>
</template>

<style lang="scss">
.business-lab-measure-data {
  // 单元格样式
  .el-table__cell {
    position: static !important; // 解决el-image 和 el-table冲突层级冲突问题
  }

  .el-radio__label {
    display: block !important;
  }
}
</style>

