Newer
Older
xc-business-system / src / views / business / taskMeasure / myTask / list.vue
dutingting on 2 Dec 43 KB 临时提交
<!-- 我的任务列表 -->
<script name="TaskMeasureMyTaskList" lang="ts" setup>
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import dayjs from 'dayjs'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import RollbackDialog from '../myTask/dialog/rollbackDialog.vue'
import type { IList, IListQuery } from './myTask-interface'
import selectItemDialog from './dialog/selectItemDialog.vue'
import selectBatchDialog from './dialog/selectBatchDialog.vue'
import batchAddLabTaskDialog from './dialog/batchAddLabTaskDialog.vue'
import constDataSynchronousDialog from './dialog/constDataSynchronousDialog.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'
import { exportMyTaskList, getMyMeasureList, getTaskDetail, myExecutiveDone, myExecutiveReceive } from '@/api/business/manager/task'
import type { dictType } from '@/global'
import type { IMenu } from '@/components/buttonBox/buttonBox'
import { getItemList, getInfo as getMesureItemDetail } from '@/api/business/measure/item'
import { deleteMeasureData, getInfo } from '@/api/business/taskMeasure/measureData'
import { scanAddMyTask } from '@/api/reader'
import scanSampleDialog from '@/components/ScanSampleDialog/index.vue'
import QRcodeDeviceDialog from '@/components/QRcodeDeviceDialog/index.vue'
import { intersectionManyArray } from '@/utils/Array'
import type { IList as IListItem, IListQuery as IListQueryItem } from '@/views/business/measure/item/item-interface'
const buttonBoxActive = 'businessMyTask' // 存储在sessionstorage里面的字段名,用于记录右上角buttonbox点击状态
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
// 右上角按钮
const menu = ref<IMenu[]>([]) // 右上角审批状态按钮组合
const active = ref('') // 选中的按钮
// 查询条件
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])
const dateRangeCertificateValid = ref<[DateModelType, DateModelType]>(['', ''])
const listQuery: Ref<IListQuery> = ref({
  customerName: '', //	委托方名称
  customerNo: '', //		委托方编号
  helpInstruction: '', //	辅助字段
  isUrgent: '', //		是否加急(1是0否null全部)
  manufactureNo: '', //		出厂编号
  manufacturer: '', //		生产厂家
  measureStatus: active.value, //		检测状态(字典code,2:待检测,3:检测中,4:检测完成)
  model: '', //		规格型号
  orderNo: '', //		任务单编号
  sampleName: '', //		受检设备名称
  sampleNo: '', //		样品编号
  startTime: '', //		要求检完时间开始
  endTime: '', //		要求检完时间结束
  measureValidDateStart: '', //	检定有效期开始
  measureValidDateEnd: '', //	检定有效期结束
  meterIdentify: '', // 计量标识
  traceDateStart: '', //	测试、校准或检定日期开始
  traceDateEnd: '', //	测试、校准或检定日期结束
  restrictionInstruction: '', // 限用说明
  conclusion: '', // 结论
  offset: 1,
  limit: 20,
})
const operateWidth = ref('220') // 操作栏的宽度

const columns = ref<TableColumn[]>([ // 表头
  { text: '受检设备名称', value: 'sampleName', align: 'center' },
  { text: '规格型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufactureNo', align: 'center' },
  // { text: '生产厂家', value: 'manufacturer', align: 'center' },
  { text: '辅助字段', value: 'helpInstruction', align: 'center' },
  { text: '任务单编号', value: 'orderNo', align: 'center' },
  { text: '委托方', value: 'customerName', align: 'center' },
  { text: '要求检完时间', value: 'requireOverTime', align: 'center', width: '180' },
  { text: '是否加急', value: 'isUrgentName', align: 'center', width: '55px', styleFilter: (row: IList) => { return row.isUrgentName == '是' ? 'color: red' : '' } },
  // { text: '检定项分类名称', value: 'itemCategoryName', align: 'center' },
])

const columns_complete = ref<TableColumn[]>([ // 表头
  { text: '受检设备名称', value: 'sampleName', align: 'center' },
  { text: '规格型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufactureNo', align: 'center' },
  // { text: '生产厂家', value: 'manufacturer', align: 'center' },
  { text: '辅助字段', value: 'helpInstruction', align: 'center' },
  { text: '任务单编号', value: 'orderNo', align: 'center' },
  { text: '委托方', value: 'customerName', align: 'center' },
  { text: '检定日期', value: 'traceDate', align: 'center', width: '120' },
  { text: '检定结论', value: 'conclusion', align: 'center' },
  { text: '限用说明', value: 'restrictionInstruction', align: 'center' },
  { text: '计量标识', value: 'meterIdentify', align: 'center' },
  { text: '证书有效期', value: 'certificateValid', align: 'center', width: '120' },
  // { text: '检定项分类名称', value: 'itemCategoryName', align: 'center' },
])
const list = ref<IList[]>([]) // 表格数据
const total = ref(0) // 总数
const loadingTable = ref(false) // 表格加载状态
const checkoutList = ref<IList[]>([]) // 选中的内容

// --------------------------------------------字典--------------------------------------

const isUrgentList = ref<dictType[]>([])// 是否加急
const isUrgentMap = ref({}) as any // 是否加急{1: 是}
const meterIdentifyDict = ref({}) as any // 计量标识
const conclusionList = ref<dictType[]>([]) as any // 检定结论

function getDict() {
  // 结论
  getDictByCode('bizConclusion').then((response) => {
    conclusionList.value = response.data
  })
  // 计量标识
  getDictByCode('eqptMeterIdentify').then((response) => {
    meterIdentifyDict.value = response.data
  })
  // 是否加急
  getDictByCode('isUrgent').then((response) => {
    isUrgentList.value = response.data
    response.data.forEach((item: any) => {
      isUrgentMap.value[`${item.value}`] = item.name
    })
  })
  return new Promise((resolve, reject) => {
    // 获取菜单字典
    getDictByCode('measureStatus').then((response) => {
      response.data.forEach((item: dictType) => {
        if (['待检测', '检测中', '检测完成'].includes(item.name)) {
          menu.value.push({
            name: item.name,
            id: `${item.value}`,
          })
          resolve(menu.value)
        }
      })
    })
  })
}

// -----------------------------------------表格数据--------------------------------------------

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页,否则跳转第一页
    listQuery.value.offset = 1
  }
  getMyMeasureList(listQuery.value).then((res) => {
    list.value = res.data.rows.map((item: any) => {
      return {
        ...item,
        isUrgentName: `${item.isUrgent}` === '1' ? '是' : '否',
        traceDate: item.traceDate ? dayjs(item.traceDate).format('YYYY-MM-DD') : item.traceDate, // 检定日期
        certificateValid: item.certificateValid ? dayjs(item.certificateValid).format('YYYY-MM-DD') : item.certificateValid, // 证书有效期
        requireOverTime: item.requireOverTime ? dayjs(item.requireOverTime).format('YYYY-MM-DD HH:mm') : item.requireOverTime, // 要求检完时间
      }
    })
    total.value = res.data.total
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

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

// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    customerName: '', //	委托方名称
    customerNo: '', //		委托方编号
    helpInstruction: '', //	辅助字段
    isUrgent: '', //		是否加急(1是0否null全部)
    manufactureNo: '', //		出厂编号
    manufacturer: '', //		生产厂家
    measureStatus: active.value, //		检测状态(字典code,2:待检测,3:检测中,4:检测完成)
    model: '', //		规格型号
    orderNo: '', //		任务单编号
    sampleName: '', //		受检设备名称
    sampleNo: '', //		样品编号
    startTime: '', //		要求检完时间开始
    endTime: '', //		要求检完时间结束
    measureValidDateStart: '', //	检定有效期开始
    measureValidDateEnd: '', //	检定有效期结束
    meterIdentify: '', // 计量标识
    traceDateStart: '', //	测试、校准或检定日期开始
    traceDateEnd: '', //	测试、校准或检定日期结束
    restrictionInstruction: '', // 限用说明
    conclusion: '', // 结论
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  dateRange.value = ['', '']
  dateRangeCertificateValid.value = ['', '']
  fetchData(false)
}

// 页数发生变化后的操作,可能是页码变化,可能是每页容量变化,此函数必写
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 handleDetail = (row: IList) => {
  $router.push({
    path: '/myTask/detail/',
    query: {
      orderId: row.orderId, // 任务单id
      equipmentId: row.sampleId, // 设备id\样品id
    },
  })
}

// 点击收入
const takeIn = function (row: IList) {
  let param = [] as any
  if (Array.isArray(row)) {
    param = row.map((item: { sampleId: string; orderId: string }) => {
      return {
        orderId: item.orderId,
        sampleId: item.sampleId,
      }
    })
  }
  else {
    param = [row]
  }
  ElMessageBox.confirm(
    '确认收入该样品吗?',
    '提示',
    { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
  ).then(() => {
    // 收入样品
    myExecutiveReceive(param).then((res) => {
      if (res.code == 200) {
        ElMessage.success('已收入')
        fetchData()
      }
    })
  })
}

// 点击退回
const rollbackRef = ref()
const rollback = function (row: IList) {
  rollbackRef.value.initDialog(row)
}

// 检完
const mearsureOver = function (row: IList) {
  let param = [] as any
  if (Array.isArray(row)) { // 是数组说明是扫码过来的
    param = row.map((item: { sampleId: string; orderId: string }) => {
      return {
        orderId: item.orderId,
        sampleId: item.sampleId,
      }
    })
  }
  else {
    param = [row]
  }
  ElMessageBox.confirm(
    '确认完成该设备检测吗?',
    '提示',
    { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
  ).then(() => {
    myExecutiveDone(param).then((res) => {
      if (res.code == 200) {
        ElMessage.success('检测完成')
        fetchData()
      }
    })
  })
}

// ===============================获取检定项id==========================================
const fetchItemList = ref<IListItem[]>([]) // 查询的检定项列表
// 查询条件
const fetchItemIdListQuery: Ref<IListQueryItem> = ref({
  dataSync: '', // 检定项数据是否同步
  deviceName: '', // 设备名称
  deviceType: '', // 设备分类
  helpInstruction: '', // 辅助字段
  model: '', // 规格型号
  syncTimeEnd: '', // 自动检定系统最新同步时间结束
  syncTimeStart: '', // 自动检定系统最新同步时间开始
  limit: 20,
  offset: 1,
})
// 查询检定项管理列表页
async function fetchItemData(isNowPage = false, deviceName = '', model = '', helpInstruction = '') {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页,否则跳转第一页
    fetchItemIdListQuery.value.offset = 1
  }
  fetchItemIdListQuery.value.deviceName = deviceName// 设备名称
  fetchItemIdListQuery.value.model = model// 规格型号
  fetchItemIdListQuery.value.helpInstruction = helpInstruction // 辅助字段
  const response = await getItemList(fetchItemIdListQuery.value)
  fetchItemList.value = response.data.rows
  loadingTable.value = false
}
// =====================================================================================
const selectItemDialogRef = ref() // 选择设备的检定项组件ref
const checkoutRow = ref({}) as any // 选中的行数据

/**
 * 判断是否配置过检定数据
 * @param belongStandardEquipment 检校标准装置
 * @param itemId 检定项id
 * @param itemData 选择的检定项数据
 */
const estimateConfig = async (itemData: any) => {
  await getInfo({
    id: '',
    belongStandardEquipment: itemData.belongStandardEquipment, // 检校标准装置
    // 我的任务跳转过来如果已经配置过检定项了,到编辑页面,且用一下三个字段替代传id请求详情
    itemId: itemData.id, // 检定项id
    orderId: checkoutRow.value.orderId, // 任务单id
    sampleId: checkoutRow.value.sampleId, // 被检设备id
  }).then((res: any) => {
    if (res.data === '') {
      $router.push({
        path: 'measureData/add',
        query: {
          ...checkoutRow.value,
          itemId: itemData.id, // 检定项id
          itemCategoryId: itemData.itemCategoryId, // 检定项分类id
          itemCategoryName: itemData.itemCategoryName, // 检定项分类名称
          belongStandardEquipment: itemData.belongStandardEquipment, // 检校标准装置Code
          belongStandardEquipmentName: itemData.belongStandardEquipmentName, // 检校标准装置名称
          checkCycle: checkoutRow.value.checkCycle, // 检定周期
          customerName: checkoutRow.value.customerName, // 委托单位
          helpFieldInstruction: itemData.helpFieldInstruction, // 辅助字段说明
          helpInstruction: itemData.helpInstruction, // 辅助字段
        },
      })
    }
    else {
      const row = res.data
      // 此处逻辑去查看/measureData 下的readme理解
      let itemTime = ''
      // 先获取检定项的更新时间
      const params = {
        id: itemData.id,
        itemCategoryName: itemData.itemCategoryName, // 检定项分类名字
        belongStandardEquipment: itemData.belongStandardEquipment, // 检校标准装置字典code
      }
      getMesureItemDetail(params).then((response) => {
        itemTime = response.data.updateTime
        // 检定项更新时间 > 检定数据更新时间,说明检定项有变
        console.log('检定项更新时间', itemTime)
        console.log('检定项数据时间', row.updateTime)
        if (row.dataSource === '自动检定系统') {
          ElMessage.warning('查询到此条数据来源于自动检定系统,请勿编辑')
        }
        else {
          if (itemTime && dayjs(itemTime).valueOf() > dayjs(row.updateTime).valueOf()) {
            ElMessageBox.confirm(
              '发现检定项发生变化,是否更新检定项?',
              '提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              },
            ).then(() => {
            // 先去缓存检定项之外的数据
              getInfo({
                id: checkoutRow.value.id,
                belongStandardEquipment: itemData.belongStandardEquipment, // 检校标准装置
                // 我的任务跳转过来如果已经配置过检定项了,到编辑页面,且用一下三个字段替代传id请求详情
                itemId: itemData.itemId, // 检定项id
                orderId: itemData.orderId, // 任务单id
                sampleId: itemData.sampleId, // 被检设备id
              }).then((res) => {
              // 先删除检定数据,再走新建
                deleteMeasureData({ id: checkoutRow.value.dataId }).then(() => {
                  $router.push({
                    path: 'measureData/add',
                    query: {
                      ...checkoutRow.value,
                      itemId: itemData.id, // 检定项id
                      itemCategoryId: itemData.itemCategoryId, // 检定项分类id
                      itemCategoryName: itemData.itemCategoryName, // 检定项分类名称
                      belongStandardEquipment: itemData.belongStandardEquipment, // 检校标准装置Code
                      belongStandardEquipmentName: itemData.belongStandardEquipmentName, // 检校标准装置名称
                      checkCycle: checkoutRow.value.checkCycle, // 检定周期
                      customerName: checkoutRow.value.customerName, // 委托单位
                      helpFieldInstruction: itemData.helpFieldInstruction, // 辅助字段说明
                      helpInstruction: itemData.helpInstruction, // 辅助字段
                    },
                  })
                })
              })
            }).catch(() => {
            // $router.push({
            //   path: 'measureData/edit',
            //   query: {
            //     ...checkoutRow.value,
            //     itemId: itemData.id, // 检定项id
            //     itemCategoryId: itemData.itemCategoryId, // 检定项分类id
            //     itemCategoryName: itemData.itemCategoryName, // 检定项分类名称
            //     belongStandardEquipment: itemData.belongStandardEquipment, // 检校标准装置Code
            //     belongStandardEquipmentName: itemData.belongStandardEquipmentName, // 检校标准装置名称
            //     checkCycle: checkoutRow.value.checkCycle, // 检定周期
            //     customerName: checkoutRow.value.customerName, // 委托单位
            //     helpFieldInstruction: itemData.helpFieldInstruction, // 辅助字段说明
            //     helpInstruction: itemData.helpInstruction, // 辅助字段
            //   },
            // })
            })
          }
          else {
            $router.push({
              path: 'measureData/edit',
              query: {
                ...checkoutRow.value,
                itemId: itemData.id, // 检定项id
                itemCategoryId: itemData.itemCategoryId, // 检定项分类id
                itemCategoryName: itemData.itemCategoryName, // 检定项分类名称
                belongStandardEquipment: itemData.belongStandardEquipment, // 检校标准装置Code
                belongStandardEquipmentName: itemData.belongStandardEquipmentName, // 检校标准装置名称
                checkCycle: checkoutRow.value.checkCycle, // 检定周期
                customerName: checkoutRow.value.customerName, // 委托单位
                helpFieldInstruction: itemData.helpFieldInstruction, // 辅助字段说明
                helpInstruction: itemData.helpInstruction, // 辅助字段
              },
            })
          }
        }
      })
    }
  })
}

// 选好检定项
const confirmSelectItem = (val: any) => {
  if (!val[0].id) {
    ElMessage.warning('此设备未配置检定项检定项,请前往检定项管理进行配置')
    return false
  }
  if (val[0].certificateId) {
    ElMessage.warning('此设备的此检定项分类已生成证书,请勿编辑')
    return false
  }
  estimateConfig(val[0])
}
// 点击编辑检定数据
const editMeasureData = (row: any) => {
  if (row.dataSource === '康斯特自动检定系统') {
    $router.push({
      path: `measureDataConst/detail/${row.dataId}`,
      query: {
        dataSource: row.dataSource,	// 数据来源(若来源于“康斯特自动检定系统”,该参数必传)
        itemId: row.itemId,	//	设备检定项表id
        orderId: row.orderId,	//	任务单id
        sampleId: row.sampleId,	//	受检设备id
      },
    })
  }
  else {
    checkoutRow.value = row
    // 查询检定项
    fetchItemData(false, row.sampleName, row.sampleModel, row.helpInstruction).then(() => {
      if (!fetchItemList.value.length) {
        ElMessage.warning('此设备没有检定项,请自查')
      }
      else if (fetchItemList.value.length === 1) { // 设备只有一个检定项
        if (!fetchItemList.value[0].id) {
          ElMessage.warning('此设备未配置检定项,请前往检定项管理进行配置')
        }
        else if (row.certificateId) {
          ElMessage.warning('此设备的此检定项分类已生成证书,请勿编辑')
        }
        else {
          estimateConfig(fetchItemList.value[0])
        }
      }
      else { // 设备检定项大于1个
        selectItemDialogRef.value.initDialog(fetchItemList.value, row.sampleId, row.orderId, row.itemCategoryId, row.itemCategoryName, row.certificateId)
      }
    })
  }
}

// -----------------------------------状态按钮------------------------------------------------
// 选择按钮变更
const changeCurrentButton = (val: string) => {
  active.value = val
  window.sessionStorage.setItem(buttonBoxActive, val)
  clearList()
}
// -------------------------------------扫描-------------------------------------------------
const scanSampleRef = ref() // 扫描收入组件ref
const QRcodeDeviceDialogRef = ref() // 扫描组件ref
const dialogTitle = ref('') // 扫描对话框标题
// scanAddMyTask
// 点击扫描增加任务
const scanAddTask = (type: 'dispatch' | 'lab', deviceType: 'scanner' | 'rfid') => {
  if (type === 'dispatch') {
    dialogTitle.value = '扫描增加待分发任务'
    if (deviceType === 'scanner') {
      QRcodeDeviceDialogRef.value.initDialog('1', '2')
    }
    else {
      scanSampleRef.value.initDialog(false, '1', '2')
    }
  }
  else if (type === 'lab') {
    dialogTitle.value = '扫描增加实验室任务'
    if (deviceType === 'scanner') {
      QRcodeDeviceDialogRef.value.initDialog('4', '1')
    }
    else {
      scanSampleRef.value.initDialog(false, '4', '1')
    }
  }
}

// 点击扫描收入
const batchScan = (type: 'scanner' | 'rfid') => {
  dialogTitle.value = '扫描收入'
  if (type === 'scanner') {
    QRcodeDeviceDialogRef.value.initDialog('3', '1')
  }
  else {
    scanSampleRef.value.initDialog(false, '3', '1')
  }
}

// 点击批量捡完
const batchOverScan = (type: 'scanner' | 'rfid') => {
  dialogTitle.value = '扫描检完'
  if (type === 'scanner') {
    QRcodeDeviceDialogRef.value.initDialog('3', '2')
  }
  else {
    scanSampleRef.value.initDialog(false, '3', '2')
  }
}

// 扫描完成
const scanOver = function (list: any, isBatchAddLabTaskDialog = false) {
  if (dialogTitle.value === '扫描增加待分发任务' || dialogTitle.value === '扫描增加实验室任务' || isBatchAddLabTaskDialog) {
    const params = list.map((item: any) => {
      return {
        orderId: item.orderId,
        requireCertifications: item.requireCertifications, // 应出具证书数量
        sampleId: item.sampleId,
      }
    })
    const loading = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(255, 255, 255, 0.6)',
    })
    scanAddMyTask(params).then((res) => {
      loading.close()
      ElMessage.success('已增加任务到检测中')
      fetchData()
    })
  }
  else if (dialogTitle.value === '扫描收入') {
    takeIn(list)
  }
  else if (dialogTitle.value === '扫描检完') {
    mearsureOver(list)
  }
  else {
    ElMessage.warning('未知操作,请联系管理员')
  }
  scanSampleRef.value.closeDialog()
}
// 批量编辑
const routeQuery = ref()
const selectBatchDialogRef = ref()
const batchEdit = async () => {
  if (!checkoutList.value.length) {
    ElMessage.warning('请先选择需要编辑的数据')
    return false
  }
  if (checkoutList.value.length > 4) {
    ElMessage.warning('最多可编辑4个')
    return false
  }
  if (checkoutList.value.findIndex((item: any) => item.certificateId) !== -1) {
    ElMessage.warning(`第${checkoutList.value.findIndex((item: any) => item.certificateId) + 1}台设备不满足编辑条件(已生成证书)`)
    return false
  }
  // 请求检定项信息
  Promise.all(checkoutList.value.map(async (item: any, index: number) => {
    try {
      const res = await getItemList({ deviceName: item.sampleName, model: item.sampleModel, helpInstruction: item.helpInstruction, limit: 999, offset: 1 })
      return Promise.resolve(res.data)
    }
    catch (error) {
      ElMessage.error(`第${index + 1}检定项查询未成功`)
      return Promise.reject(error)
    }
  })).then((res) => {
    const data = res
    routeQuery.value = data
    // 检定项信息
    data.forEach((item: any, index: number) => {
      if (!item.rows.length) {
        ElMessage.error(`第${index + 1}台设备没有检定项,请自查`)
        throw new Error(`第${index + 1}台设备没有检定项`)
      }
      if (item.rows.length === 1 && !item.rows[0].id) {
        ElMessage.error(`第${index + 1}台设备未配置检定项,请前往检定项管理进行配置`)
        throw new Error(`第${index + 1}台设备未配置检定项,请前往检定项管理进行配置`)
      }
      if (item.rows.length === 1 && item.rows[0].belongStandardEquipment !== '4') {
        ElMessage.error('仅0.02级活塞式压力计支持批量编辑')
        throw new Error('仅0.02级活塞式压力计支持批量编辑')
      }
    })
    const pistonPressure = data.map((item: any) => item.rows.filter((item: any, cindex: number) => item.belongStandardEquipment === '4'))
    if (!pistonPressure.every(item => item.length)) {
      ElMessage.error('仅0.02级活塞式压力计支持批量编辑')
      throw new Error('仅0.02级活塞式压力计支持批量编辑')
    }
    if (!pistonPressure.map((item: any) => item.map((citem: any) => citem.id)).every((item: any) => item.length)) {
      ElMessage.error(`第${pistonPressure.map((item: any) => item.map((citem: any) => citem.id)).findIndex(item => !item.length) + 1}台设备未配置0.02级活塞式压力计检定项,请前往检定项管理进行配置`)
      throw new Error(`第${pistonPressure.map((item: any) => item.map((citem: any) => citem.id)).findIndex(item => !item.length) + 1}台设备未配置0.02级活塞式压力计检定项,请前往检定项管理进行配置`)
    }
    const intersection = intersectionManyArray(...pistonPressure.map(item => item.map((citem: { itemCategoryName: string }) => citem.itemCategoryName)))
    if (!intersection.length) {
      ElMessage.warning('只允许配置同一个检定项的数据')
      throw new Error('只允许配置同一个检定项的数据')
    }
    else if (intersection.length > 1) {
      // 选择配置哪个检定项
      selectBatchDialogRef.value.initDialog(data[0].rows.filter((item: any) => intersection.includes(item.itemCategoryName)))
    }
    else {
      // 符合跳转(有编辑有新建)
      if (!pistonPressure.map(item => item.filter((citem: { itemCategoryName: string }) => citem.itemCategoryName === intersection[0])[0]).every(item => item.id)) {
        ElMessage.error(`第${pistonPressure.map(item => item.filter((citem: { itemCategoryName: string }) => citem.itemCategoryName === intersection[0])[0]).findIndex(item => !item.id) + 1}台设备0.02级活塞式压力计检定项数据未配置,请前往检定项管理进行配置`)
        throw new Error(`第${pistonPressure.map(item => item.filter((citem: { itemCategoryName: string }) => citem.itemCategoryName === intersection[0])[0]).findIndex(item => !item.id) + 1}台设备0.02级活塞式压力计检定项数据未配置,请前往检定项管理进行配置`)
      }
      const pistonPressure1 = pistonPressure.map(item => item.filter((citem: { itemCategoryName: string }) => citem.itemCategoryName === intersection[0])[0])
      Promise.all(checkoutList.value.map(async (item: any, index: number) => {
        try {
          const res = await getInfo({ belongStandardEquipment: '4', itemId: pistonPressure1[index].id, orderId: item.orderId, sampleId: item.sampleId })
          return Promise.resolve(res.data)
        }
        catch (error) {
          ElMessage.error(`第${index + 1}检定数据查询未成功`)
          return Promise.reject(error)
        }
      })).then((res) => {
        const data = res
        const batchEditRow = checkoutList.value
        data.forEach((item: any, index: number) => {
          batchEditRow[index] = {
            ...checkoutList.value[index],
            itemId: pistonPressure1[index].id, // 检定项id
            itemCategoryId: pistonPressure1[index].itemCategoryId, // 检定项分类id
            itemCategoryName: pistonPressure1[index].itemCategoryName, // 检定项分类名称
            belongStandardEquipment: pistonPressure1[index].belongStandardEquipment, // 检校标准装置Code
            belongStandardEquipmentName: pistonPressure1[index].belongStandardEquipmentName, // 检校标准装置名称
            checkCycle: checkoutList.value[index].checkCycle, // 检定周期
            customerName: checkoutList.value[index].customerName, // 委托单位
            helpFieldInstruction: pistonPressure1[index].helpFieldInstruction, // 辅助字段说明
            helpInstruction: pistonPressure1[index].helpInstruction, // 辅助字段
            pageType: item ? 'edit' : 'add',
          }
        })
        $router.push({
          path: 'myTask/batchEdit',
          query: {
            batchEdit: 'true',
            batchEditRow: JSON.stringify(batchEditRow),
            belongStandardEquipment: '4',
          },
        })
      })
    }
  })
}
const confirmSelectBatch = (select: any) => {
  console.log(select, 'select')
  const itemCategoryData = routeQuery.value.map((item: any) => item.rows).map((item: any) => item.filter((citem: any) => citem.itemCategoryName === select)[0])
  if (!itemCategoryData.every((item: any) => item.id)) {
    ElMessage.error(`第${itemCategoryData.findIndex((item: any) => !item.id) + 1}台设备未配置${select}检定项,,请前往检定项管理进行配置`)
    throw new Error(`第${itemCategoryData.findIndex((item: any) => !item.id) + 1}台设备未配置${select}检定项,,请前往检定项管理进行配置`)
  }
  Promise.all(checkoutList.value.map(async (item: any, index: number) => {
    try {
      const res = await getInfo({ belongStandardEquipment: '4', itemId: itemCategoryData[index].id, orderId: item.orderId, sampleId: item.sampleId })
      return Promise.resolve(res.data)
    }
    catch (error) {
      ElMessage.error(`第${index + 1}检定数据查询未成功`)
      return Promise.reject(error)
    }
  })).then((res) => {
    const data = res
    const batchEditRow = checkoutList.value
    data.forEach((item: any, index: number) => {
      batchEditRow[index] = {
        ...checkoutList.value[index],
        itemId: itemCategoryData[index].id, // 检定项id
        itemCategoryId: itemCategoryData[index].itemCategoryId, // 检定项分类id
        itemCategoryName: itemCategoryData[index].itemCategoryName, // 检定项分类名称
        belongStandardEquipment: itemCategoryData[index].belongStandardEquipment, // 检校标准装置Code
        belongStandardEquipmentName: itemCategoryData[index].belongStandardEquipmentName, // 检校标准装置名称
        checkCycle: checkoutList.value[index].checkCycle, // 检定周期
        customerName: checkoutList.value[index].customerName, // 委托单位
        helpFieldInstruction: itemCategoryData[index].helpFieldInstruction, // 辅助字段说明
        helpInstruction: itemCategoryData[index].helpInstruction, // 辅助字段
        pageType: item ? 'edit' : 'add',
      }
    })
    $router.push({
      path: 'myTask/batchEdit',
      query: {
        batchEdit: 'true',
        batchEditRow: JSON.stringify(batchEditRow),
        belongStandardEquipment: '4',
      },
    })
  })
}

const constDataSynchronousDialogRef = ref() // const数据同步组件ref
// 点击const数据同步
const constDataSynchronous = () => {
  constDataSynchronousDialogRef.value.initDialog()
}
// --------------------------------------导出--------------------------------------------------------
// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const param = {
      customerName: listQuery.value.customerName, //	委托方名称
      customerNo: listQuery.value.customerNo, //		委托方编号
      helpInstruction: listQuery.value.helpInstruction, //	辅助字段
      isUrgent: listQuery.value.isUrgent, //		是否加急(1是0否null全部)
      manufactureNo: listQuery.value.manufactureNo, //		出厂编号
      manufacturer: listQuery.value.manufacturer, //		生产厂家
      measureStatus: listQuery.value.measureStatus, //		检测状态(字典code,2:待检测,3:检测中,4:检测完成)
      model: listQuery.value.model, //		规格型号
      orderNo: listQuery.value.orderNo, //		任务单编号
      sampleName: listQuery.value.sampleName, //		受检设备名称
      sampleNo: listQuery.value.sampleNo, //		样品编号
      startTime: listQuery.value.startTime, //		要求检完时间开始
      endTime: listQuery.value.endTime, //		要求检完时间结束
      measureValidDateStart: listQuery.value.measureValidDateStart, //	检定有效期开始
      measureValidDateEnd: listQuery.value.measureValidDateEnd, //	检定有效期结束
      meterIdentify: listQuery.value.meterIdentify, // 计量标识
      traceDateStart: listQuery.value.traceDateStart, //	测试、校准或检定日期开始
      traceDateEnd: listQuery.value.traceDateEnd, //	测试、校准或检定日期结束
      restrictionInstruction: listQuery.value.restrictionInstruction, // 限用说明
      conclusion: listQuery.value.conclusion, // 结论
      offset: 1,
      limit: 20,
      ids: checkoutList.value.map((item: { id: string }) => item.id),
    }
    exportMyTaskList(param).then((res) => {
      exportFile(res.data, '我的任务')
      loading.close()
    })
      .catch((_) => {
        loading.close()
      })
  }
  else {
    loading.close()
    ElMessage.warning('无数据可导出数据')
  }
}

// -------------------------------------批量增加实验室任务-----------------------------------------------
const batchAddLabTaskDialogRef = ref() // 批量增加实验室任务弹框组件ref
// 点击批量增加实验室任务
const batchAddLabTask = () => {
  batchAddLabTaskDialogRef.value.initDialog()
}
// ---------------------------------------钩子-------------------------------------------------------
watch(timeRange, (val) => { // 监听时间变化
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})

watch(dateRange, (val) => { // 监听检定日期变化
  if (val) {
    listQuery.value.traceDateStart = `${val[0]}`
    listQuery.value.traceDateEnd = `${val[1]}`
  }
  else {
    listQuery.value.traceDateStart = ''
    listQuery.value.traceDateEnd = ''
  }
})
// 证书有效期
watch(dateRangeCertificateValid, (val) => { // 监听证书有效期变化
  if (val) {
    listQuery.value.measureValidDateStart = `${val[0]}`
    listQuery.value.measureValidDateEnd = `${val[1]}`
  }
  else {
    listQuery.value.measureValidDateStart = ''
    listQuery.value.measureValidDateEnd = ''
  }
})

onMounted(async () => {
  getDict().then(() => {
    if (window.sessionStorage.getItem(buttonBoxActive) != null) {
      active.value = window.sessionStorage.getItem(buttonBoxActive) as string
    }
    else {
      active.value = menu.value.find(item => item.name === '待检测')!.id as string // 待检测
    }
    listQuery.value.measureStatus = active.value // 检测状态
    fetchData(true)
  })
})
</script>

<template>
  <app-container>
    <button-box :active="active" :total-refuse="totalRefuse" :total-approval="totalApproval" :total-to-approval="totalToApproval" :menu="menu" @change-current-button="changeCurrentButton" />
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleName"
          placeholder="受检设备名称"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.model"
          placeholder="规格型号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.manufactureNo"
          placeholder="出厂编号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.helpInstruction"
          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="委托方"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item v-if="listQuery.measureStatus === '4'">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="检定日期(开始)"
          end-placeholder="检定日期(结束)"
          class="short-input"
        />
      </search-item>
      <search-item v-if="listQuery.measureStatus === '4'">
        <el-select
          v-model="listQuery.conclusion"
          placeholder="检定结论"
          filterable
          class="full-width-input"
          clearable
        >
          <el-option v-for="item in conclusionList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </search-item>
      <search-item v-if="listQuery.measureStatus === '4'">
        <el-input
          v-model.trim="listQuery.restrictionInstruction"
          placeholder="限用说明"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item v-if="listQuery.measureStatus === '4'">
        <el-select
          v-model="listQuery.meterIdentify"
          class="short-input"
          placeholder="计量标识"
          clearable
        >
          <el-option v-for="item of meterIdentifyDict" :key="item.value" :label="item.name" :value="item.name" />
        </el-select>
      </search-item>
      <search-item v-if="listQuery.measureStatus === '4'">
        <el-date-picker
          v-model="dateRangeCertificateValid"
          type="daterange"
          range-separator="至"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="证书有效期(开始)"
          end-placeholder="证书有效期(结束)"
          class="short-input"
        />
      </search-item>
      <search-item v-if="listQuery.measureStatus !== '4'">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          start-placeholder="要求检完开始时间"
          end-placeholder="要求检完结束时间"
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-batch" title="批量增加实验室任务" type="primary" @click="batchAddLabTask" />
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-scan" title="扫码枪扫描增加实验室任务" type="primary" @click="scanAddTask('lab', 'scanner')" />
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-lab" title="rfid扫描增加实验室任务" type="primary" @click="scanAddTask('lab', 'rfid')" />
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-scan" title="扫码枪扫描增加待分发任务" type="primary" @click="scanAddTask('dispatch', 'scanner')" />
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-dispatch" title="rfid扫描增加待分发任务" type="primary" @click="scanAddTask('dispatch', 'rfid')" />
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-qrcode" title="扫码枪扫描收入" type="primary" @click="batchScan('scanner')" />
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-rfid" title="rfid扫描收入" type="primary" @click="batchScan('rfid')" />
        <icon-button v-if="listQuery.measureStatus === '3'" icon="icon-edit" title="批量编辑" @click="batchEdit" />
        <icon-button v-if="listQuery.measureStatus === '3'" icon="icon-qrcode" title="扫码枪扫描检完" type="primary" @click="batchOverScan('scanner')" />
        <icon-button v-if="listQuery.measureStatus === '3'" icon="icon-rfid" title="rfid扫描检完" type="primary" @click="batchOverScan('rfid')" />
        <icon-button icon="icon-export" title="导出" @click="exportAll" />
        <icon-button v-if="listQuery.measureStatus === '3'" icon="icon-data-synchronous" title="const数据同步" type="primary" @click="constDataSynchronous" />
      </template>
      <normal-table
        :data="list" :total="total" :columns="listQuery.measureStatus === '4' ? columns_complete : 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="operateWidth">
            <template #default="{ row }">
              <el-button size="small" link type="primary" @click="handleDetail(row)">
                详情
              </el-button>
              <el-button v-if="listQuery.measureStatus === '2'" size="small" type="primary" link @click="takeIn(row)">
                收入
              </el-button>
              <el-button v-if="listQuery.measureStatus === '2' && row.currentSegmentId" size="small" type="primary" link @click="rollback(row)">
                退回
              </el-button>
              <el-button v-if="listQuery.measureStatus === '3'" size="small" link type="primary" @click="editMeasureData(row)">
                编辑检定数据
              </el-button>
              <el-button v-if="listQuery.measureStatus === '3'" size="small" type="primary" link @click="mearsureOver(row)">
                检测完成
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
      <!-- 退回弹窗 -->
      <rollback-dialog ref="rollbackRef" @on-success="fetchData(true)" />
      <!-- 批量收入弹窗 -->
      <scan-sample-dialog ref="scanSampleRef" @confirm="scanOver" />
      <!-- 选择设备的哪个检定项编辑检定数据 -->
      <select-item-dialog ref="selectItemDialogRef" @confirm="confirmSelectItem" />
      <select-batch-dialog ref="selectBatchDialogRef" @confirm="confirmSelectBatch" />
      <scan-sample-dialog ref="scanSampleRef" :title="dialogTitle" @confirm="scanOver" />

      <!-- 扫码枪扫描收入  -->
      <q-rcode-device-dialog ref="QRcodeDeviceDialogRef" @confirm="scanOver" />

      <!-- 批量增加实验室任务  -->
      <batch-add-lab-task-dialog ref="batchAddLabTaskDialogRef" @confirm="scanOver" />
    </table-container>

    <!-- const数据同步 -->
    <const-data-synchronous-dialog ref="constDataSynchronousDialogRef" />
  </app-container>
</template>

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