Newer
Older
xc-metering-front / src / views / tested / device / info / components / list.vue
dutingting on 29 Nov 49 KB 临时提交
<!-- 智能模型信息表格 -->
<script lang="ts" setup name="DeviceInfoList">
import { reactive, ref } from 'vue'
import print from 'print-js'
import { ElLoading, ElMessage, ElMessageBox, FIRST_LAST_KEYS } from 'element-plus'
import axios from 'axios'
import type { IlistObjType, IlistQueryType } from './interface'
import printTag from './printTag.vue'
import useUserStore from '@/store/modules/user'
import { delTextBtn, editTextBtn } from '@/utils/applyBtns'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { bindTaskHandler, cancelInfo, deleteInfo, editInfo, exportDevice, getCheckOrganization, getInfoList, getInfoListPage, getInfoListTogether, getManufacturer, importDevice, submitInfo } from '@/api/eqpt/device/info'
import { getDictByCode } from '@/api/system/dict'
// import { getUserDeptSon, getUserList } from '@/api/system/user'
import { getAdminDept, getUserDept, getUserDeptSon, getUserList } from '@/api/system/user'
import { SCHEDULE } from '@/utils/scheduleDict'
import useTemplateDownload from '@/utils/useTemplateDownload'
import { exportFile } from '@/utils/exportUtils'
import { getDeviceNameList, getModelAllList, getModelList } from '@/api/eqpt/device/model'
import { getTaskList } from '@/api/eqpt/device/task'
import task from '@/views/tested/device/task/index.vue'
import { toTreeList, underlineToHump } from '@/utils/structure'
import scanEquipmentDialog from '@/components/scanEquipmentDialog/index.vue'
import { getLocationList } from '@/api/system/installation'
import { getPostList } from '@/api/system/post'
import { getGroupList } from '@/api/eqpt/device/group'
import { getDeptList, getDeptTree, getDeptTreeList } from '@/api/system/dept'
import { keepSearchParams } from '@/utils/keepQuery'
const $props = defineProps({
  statusName: {
    type: String,
    default: '',
  },
  // 智能模型类型(1受检智能模型;2特种智能模型)
  equipmentType: {
    type: String,
    default: '1',
  },
})
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, $props.equipmentType === '1' ? 'DeviceInfo' : 'SpecialDevice')
})
const userStore = useUserStore()
const applyDict = ref<{ [key: string]: string }>({
  审批: '',
  草稿箱: '1',
  审批中: '3',
  已通过: '4',
  未通过: '5',
  已取消: '6',
})
// 切换表格标识   true:普通表格  false:聚合表格
const tableFlage = ref(sessionStorage.getItem('device-info-list-flag') ? JSON.parse(sessionStorage.getItem('device-info-list-flag') as string) : true)
watch(() => tableFlage.value, (newVal) => {
  sessionStorage.setItem('device-info-list-flag', JSON.stringify(newVal))
}, { deep: true })
// 是否折叠查询条件
const searchMore = ref(true)
const expandSearch = () => {
  searchMore.value = !searchMore.value
}
const normalTableRef = ref()
const { proxy } = getCurrentInstance() as any
const listQuery = reactive<IlistQueryType>({
  certificateValidStart: '',
  certificateValidEnd: '',
  deptIds: '', // 使用部门
  usageStatus: '', // 使用状态
  usePositionId: '', // 使用岗位
  equipmentNo: '', // 统一编号
  equipmentName: '', // 智能模型名称
  equipmentType: $props.equipmentType, // 智能模型类型(1受检智能模型;2特种智能模型)
  offset: 1,
  limit: 20,
  approvalStatus: '',
  formId: SCHEDULE.DEVICE_INFO_APPROVAL,
  model: '', // 规格型号
  manufactureNo: '', // 出厂编号
  companyId: '', // 所在单位
  directorName: '', // 负责人
  useSign: '', // 再用信息
  installLocationId: '', // 安装位置
  taskId: '', // 参试任务
  checkOrganization: '', // 检定机构
  meterIdentify: '', // 计量标识
  checkDateEnd: '',
  checkDateStart: '',
  sort: 'desc',
  orderBy: 'create_time',
  manufacturer: '', // 厂商
  groupId: '', // 分组
  directorId: '',
})
const checked = ref(true)
// watch(() => checked.value, (newVal) => {
//   if (newVal) {
//     listQuery.directorId = $props.statusName === '全部' ? userStore.id : ''
//   }
//   else {
//     listQuery.directorId = ''
//   }
// })
const columns = ref([
  // {
  //   text: '标签信息',
  //   value: 'rfid',
  //   align: 'center',
  //   sortable: 'custom',
  // },
  // {
  //   text: '统一编号',
  //   value: 'equipmentNo',
  //   align: 'center',
  //   sortable: 'custom',
  // },
  {
    text: '智能模型名称',
    value: 'equipmentName',
    align: 'center',
    filters: true,
  },
  {
    text: '规格型号',
    value: 'model',
    align: 'center',
    sortable: 'custom',
    filters: true,
  },
  {
    text: '出厂编号',
    value: 'manufactureNo',
    align: 'center',
    sortable: 'custom',
    filters: true,
  },
  {
    text: '厂商',
    value: 'manufacturer',
    align: 'center',
    // sortable: 'custom',
    filters: true,
  },
  {
    text: '所在单位',
    value: 'companyName',
    align: 'center',
    // sortable: 'custom',
    filters: true,
  },
  {
    text: '使用部门',
    value: 'deptName',
    align: 'center',
    // sortable: 'custom',
    filters: true,
  },
  {
    text: '使用岗位',
    value: 'usePosition',
    align: 'center',
    filters: true,
  },
  {
    text: '计量标识',
    value: 'meterIdentifyName',
    align: 'center',
    filters: true,
  },
  // {
  //   text: '检定周期',
  //   value: 'checkCycle',
  //   align: 'center',
  // },
  {
    text: '证书有效期',
    value: 'certificateValid',
    align: 'center',
    sortable: 'custom',
    filters: true,
  },
  {
    text: '使用状态',
    value: 'usageStatusName',
    align: 'center',
    sortable: 'custom',
    filters: true,
  },
])
const allColums = ref([
  {
    text: '分组',
    value: 'groupNames',
    align: 'center',
    // filters: true,
  },
])
const otherColums = ref([
  {
    text: '审批类型',
    value: 'approvalTypeName',
    align: 'center',
  },
  {
    text: '创建人',
    value: 'createUserName',
    align: 'center',
  },
  {
    text: '创建时间',
    value: 'createTime',
    align: 'center',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
  },
])
const togetherColums = ref([
  {
    text: '智能模型名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '数量',
    value: 'count',
    align: 'center',
  },
])
// 聚合表格实例
const togetherTableRef = ref()
// 展开表格实例
const expandTableRef = ref()
const list = ref([])
const total = ref(0)
const listLoading = ref(true)

// 获取列表数据
const fetchData = (isNowPage = true) => {
  list.value = []
  listLoading.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页,否则跳转第一页
  //   listQuery.offset = 1
  // }
  getInfoListPage({ ...listQuery, directorId: $props.statusName === '全部' && checked.value ? userStore.id : '' }, $props.statusName).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    // normalTableRef.value.handleChecked()
    listLoading.value = false
    // 整理筛选行数据
    columns.value.forEach((item: any, index: number) => {
      const filters = [] as any[]
      list.value.forEach((child: any, cindex: number) => {
        filters.push({
          text: child[item.value],
          value: child[item.value],
        })
      })
      const array = [] as any[]
      filters.forEach((xitem: any) => {
        if (!array.map((citem: any) => citem.text).filter(c => c == xitem.text).length) {
          array.push(xitem)
        }
      })
      item.filters = array
    })
  }).catch((_) => {
    listLoading.value = false
  })
}
// 排序条件发生变化
const sortChange = ({ column }: any) => {
  if (column.order === 'ascending') {
    listQuery.sort = 'asc'
    // console.log(column.prop)
    // console.log('升序')
  }
  else if (column.order === 'descending') {
    listQuery.sort = 'desc'
    // console.log(column.prop)
    // console.log('倒叙')
  }
  console.log(underlineToHump(column.prop), column.prop)
  let data = underlineToHump(column.prop)
  if (data.split('_')[data.split('_').length - 1] === 'name') {
    data = data.split('_').slice(0, data.split('_').length - 1).join('_')
    console.log(data, 'data')
  }
  listQuery.orderBy = data
  fetchData()
}
// 获取使用状态列表
const useStatusList = ref()
// 智能模型名称
const deviceNameList = ref<string[]>([])
// 智能模型分类
const deviceTypeList = ref<{ id: string; value: string; name: string }[]>([])
// 再用信息
const useSignList = ref<{ id: string; value: string; name: string }[]>([])
// 任务列表
const taskList = ref<{ id: string; value: string; name: string }[]>([])
// 计量标识
const meterIdentifyList = ref<{ id: string; value: string; name: string }[]>()
// 分组
const groupList = ref<{ id: string; value: string; name: string }[]>()
// 安装位置
const installLocationList = ref<any[]>([])
// 使用岗位
const usePositionList = ref<any[]>([])
// 负责人
const userList = ref<any[]>([])
// 规格型号
const modelList = ref<any[]>([])
const allList = ref<any[]>([])
// 所在单位
const companyInfo = ref<any>({})
const companyList = ref<{ id: string; value: string; name: string }[]>([])
// 部门
const deptList = ref<{ id: string; value: string; name: string }[]>([])
const deptListAll = ref<{ id: string; value: string; name: string }[]>([])
// 智能模型在用信息
const inUseList = ref<{ id: string; value: string; name: string }[]>()
// 厂商
const manufacturerList = ref<{ id: string; value: string; name: string }[]>()
// 检定(校准)机构
const checkOrganizationList = ref<{ id: string; value: string; name: string }[]>()
const fetchUseStatus = () => {
  getDictByCode('eqptDeviceUseStatus').then((res) => {
    useStatusList.value = res.data
  })
  getDictByCode('eqptDeviceInUse').then((res) => {
    useSignList.value = res.data
  })
  // 智能模型分类
  getDictByCode('eqptDeviceType').then((res) => {
    deviceTypeList.value = res.data
  })
  // 智能模型名称
  getDeviceNameList({ equipmentType: $props.equipmentType }).then((res) => {
    deviceNameList.value = res.data
  })
  // 规格型号
  getModelAllList({ equipmentType: $props.equipmentType }).then((res) => {
    allList.value = res.data
    modelList.value = Array.from(new Set(res.data.filter((item: any) => item.model).map((item: any) => item.model))).sort()
  })
  // 参试任务
  getTaskList({ limit: 9999, offset: 1 }).then((res) => {
    taskList.value = res.data.rows.map((item: any) => ({ name: item.taskName, value: item.id, id: item.id }))
  })
  getDictByCode('eqptMeterIdentify').then((res) => {
    meterIdentifyList.value = res.data
    meterIdentifyList.value?.push({ name: '空', id: '1', value: '66' })
  })
  // 安装位置
  getLocationList().then((res) => {
    // console.log(res.data, '安装位置')
    installLocationList.value = res.data
  })
  // 使用岗位
  getPostList({}).then((res) => {
    usePositionList.value = res.data
  })
  // 负责人
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    userList.value = res.data.rows
  })
  // 分组
  getGroupList({ offset: 1, limit: 99999 }).then((res) => {
    // console.log(res.data, '分组')
    groupList.value = res.data.rows.map((item: any) => ({ name: item.groupName, id: item.id, value: item.id }))
  })
  // 厂商
  getManufacturer().then((res) => {
    manufacturerList.value = res.data.map((item: any) => ({ name: item, id: item, value: item }))
  })
  // 检定(校准)机构
  getCheckOrganization().then((res) => {
    checkOrganizationList.value = res.data.map((item: any) => ({ name: item, id: item, value: item }))
  })

  // 单位部门
  // getDeptTree({ pid: '0' }).then((res) => {
  // // 单位
  // companyList.value = res.data.filter((item: any) => item.pid === '0').map((item: any) => ({ id: item.id, value: item.id, name: item.fullName }))
  // console.log(companyList, 'companyList')
  // // 部门
  // deptList.value = res.data.filter((item: any) => item.pid !== '0' && item.pids.split(',').length === 3).map((item: any) => ({ id: item.id, value: item.id, name: item.fullName }))
  // deptListAll.value = JSON.parse(JSON.stringify(deptList.value))
  // })
  // getUserDeptSon({}).then((res) => {
  //   deptList.value = res.data.map((item: any) => ({ id: item.id, value: item.id, name: item.fullName }))
  // })
  getUserDept().then((res) => {
    companyInfo.value = res.data
    if (res.data.fullName === '顶级' || res.data.version === '1' || res.data.version === 1) {
      getAdminDept({}).then((res) => {
        companyList.value = res.data.map((item: any) => ({ id: item.id, value: item.id, name: item.fullName }))
      })
    }
    else {
      companyList.value = [
        {
          name: res.data.fullName,
          value: res.data.id,
          id: res.data.id,
        },
      ]
    }
  })
  getDictByCode('eqptDeviceInUse').then((res) => {
    inUseList.value = res.data
  })
}
fetchUseStatus()
// 监听智能模型名称下拉框,修改规格型号和辅助字段
watch(() => listQuery.equipmentName, (newVal) => {
  if (newVal) {
    listQuery.model = ''
    // 修改规格型号和辅助字段列表
    const data = allList.value.filter(item => item.equipmentName === newVal)
    modelList.value = Array.from(new Set(data.filter(item => item.model).map(item => item.model))).sort()
  }
  else {
    listQuery.model = ''
    modelList.value = Array.from(new Set(allList.value.filter(item => item.model).map(item => item.model))).sort()
  }
})
// 监听单位,修改部门
watch(() => listQuery.companyId, (newVal) => {
  listQuery.deptIds = ''
  if (newVal) {
    // getUserDeptSon({ companyId: newVal }).then((res) => {
    //   deptList.value = res.data.map((item: any) => ({ id: item.id, value: item.id, name: item.fullName }))
    // })
    getDeptTreeList({ pid: newVal }).then((res) => {
      deptList.value = toTreeList(res.data.map((item: any) => ({ ...item, label: item.name, value: item.id }))) as any[]
    })
  }
  else {
    deptList.value = []
  }
}, {
  deep: true,
})
// 证书有效期开始结束时间
// const datetimerange = ref()
// watch(() => datetimerange.value, (newVal) => {
//   listQuery.certificateValidStart = ''
//   listQuery.certificateValidEnd = ''
//   if (Array.isArray(newVal)) {
//     if (newVal.length) {
//       listQuery.certificateValidStart = `${newVal[0]} 00:00:00`
//       listQuery.certificateValidEnd = `${newVal[1]} 23:59:59`
//     }
//   }
// })
// // const datetimerange1 = ref()
// watch(() => datetimerange1.value, (newVal) => {
//   listQuery.checkDateStart = ''
//   listQuery.checkDateEnd = ''
//   if (Array.isArray(newVal)) {
//     if (newVal.length) {
//       listQuery.checkDateStart = `${newVal[0]} 00:00:00`
//       listQuery.checkDateEnd = `${newVal[1]} 23:59:59`
//     }
//   }
// })
// 重置
const reset = (refresh = true) => {
  // datetimerange.value = []
  // datetimerange1.value = []
  listQuery.equipmentNo = ''
  listQuery.equipmentName = ''
  listQuery.usageStatus = ''
  listQuery.usePositionId = ''
  listQuery.certificateValidEnd = ''
  listQuery.certificateValidStart = ''
  listQuery.model = ''
  listQuery.deptIds = ''
  listQuery.manufactureNo = ''
  listQuery.companyId = ''
  listQuery.directorName = ''
  listQuery.useSign = ''
  listQuery.installLocationId = ''
  listQuery.checkOrganization = ''
  listQuery.checkDateStart = ''
  listQuery.checkDateEnd = ''
  listQuery.taskId = ''
  listQuery.meterIdentify = ''
  listQuery.sort = 'desc'
  listQuery.orderBy = 'create_time'
  listQuery.manufacturer = ''
  listQuery.groupId = ''
  listQuery.directorId = ''
  checked.value = true
  modelList.value = Array.from(new Set(allList.value.filter(item => item.model).map(item => item.model))).sort()
  listQuery.offset = 1
  listQuery.limit = 20
  if (refresh) {
    search()
  }
}
// 页数发生变化后的操作,可能是页码变化,可能是每页容量变化,此函数必写
const changePage = (val: { size: number; page: number }) => {
  if (val && val.size) {
    listQuery.limit = val.size
  }
  if (val && val.page) {
    listQuery.offset = val.page
  }
  // search()
  fetchData()
}
// 获取聚合表格数据
const togetherLoading = ref(true)
const togetherList = ref([])
const fetchTogetherData = () => {
  togetherList.value = [[]] as any
  togetherLoading.value = true
  getInfoListTogether({ ...listQuery, directorId: $props.statusName === '全部' && checked.value ? userStore.id : '' }).then((res) => {
    togetherList.value = res.data
    togetherLoading.value = false
    // 收起展开
  })
}
// 获取展开行内表格数据
const expandLoading = ref(true)
const expandList = ref([])
const fetchExpandData = (params: any) => {
  expandLoading.value = true
  getInfoList({ ...listQuery, limit: undefined, offset: undefined, ...params, directorId: $props.statusName === '全部' && checked.value ? userStore.id : '' }).then((res) => {
    expandList.value = res.data
    // 获取聚合表格选中,判断展开表格是否需要全选
    const selectList = togetherTableRef.value.getSelectionRows()
    if (selectList.length) {
      const select = selectList.filter((item: any) => item.equipmentName === params.equipmentName)
      if (select.length) {
        nextTick(() => {
          expandTableRef.value.toggleAllSelection()
        })
      }
    }
    expandLoading.value = false
  })
}
const getRowKeys = (row: any) => { // 获取当前行id
  return row.equipmentName // 这里看这一行中需要根据哪个属性值是id
}

// 监听聚合表格多选
// watch(() => togetherTableRef.value?.getSelectionRows(), (newVal, oldVal) => {
//   console.log(newVal, 'newVal')handler
// }, {
//   deep: true,
// })

// 表格被选中的行
const selectList = ref<any[]>([])
// 表格多选
const multiSelect = (row: any[]) => {
  selectList.value = row
}
// 控制展开行
const expands = ref<any[]>([])
const expandChange = (row: any, expandedRows: any) => {
  if (expandedRows.length) {
    expands.value = []
    if (row) {
      expands.value.push(row.equipmentName)
    }
  }
  else {
    expands.value = []
  }
}
watch(() => expands.value, (newVal) => {
  fetchExpandData({ equipmentName: newVal[0] })
},
{
  deep: true,
})
const togetherSelect = (selection: any, row: any) => {
  if (selection.includes(row)) {
    // 勾选
    console.log('勾选')
    if (expands.value && expands.value[0] === row.equipmentName) {
      expandTableRef.value.toggleAllSelection()
    }
  }
  else {
    // 取消勾选
    console.log('取消勾选')
    if (expands.value && expands.value[0] === row.equipmentName) {
      expandTableRef.value.toggleAllSelection()
    }
  }
}
const expandSelect = (selection: any, row: any) => {
  if (selection.length === expandList.value.length) {
    // 全选
    console.log('全选')
    // 获取聚合
    console.log(expands.value[0])
    const data = togetherList.value.filter((item: any) => item.equipmentName === expands.value[0])
    console.log(data)
    if (data.length) {
      nextTick(() => {
        togetherTableRef.value.toggleRowSelection(data[0], true)
      })
    }
  }
  else {
    // 全不选
    console.log('全不选')
    // 获取聚合
    const data = togetherList.value.filter((item: any) => item.equipmentName === expands.value[0])
    if (data.length) {
      nextTick(() => {
        togetherTableRef.value.toggleRowSelection(data[0], false)
      })
    }
  }
}
// 查询数据
async function search() {
  if (tableFlage.value) {
    // 普通表格
    fetchData(false)
  }
  else {
    // 聚合表格
    await fetchTogetherData()
    // 先判断是否有展开行
    if (expands.value.length) {
      fetchExpandData({ equipmentName: expands.value[0] })
    }
  }
}
const $router = useRouter()
// 新建编辑操作
const handler = (row: IlistObjType, type: string) => {
  // 当角色是操作手时,只有负责人是自己时可以编辑/删除
  if ($props.statusName === '全部' && userStore.roleNames.length === 1 && userStore.roleNames[0] === '操作手' && type === 'update') {
    if (row.directorName !== userStore.name) {
      ElMessage.warning('负责人不是自己,不可编辑')
      return
    }
  }
  $router.push({
    path: `/${$props.equipmentType === '1' ? 'dinfo' : 'speciallist'}/${type}`,
    query: {
      row: JSON.stringify(row),
      id: row.id,
      statusName: $props.statusName,
      equipmentType: $props.equipmentType,
    },
  })
}
// 导出列表
const exportList = () => {
  if (tableFlage.value) {
    // 普通表格
    if (list.value.length) {
      console.log(listQuery, 'listQuerylistQuerylistQuery')
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(255, 255, 255, 0.8)',
      })
      const data = {
        ...listQuery,
        offset: undefined,
        limit: undefined,
        ids: selectList.value.map(item => item.id),
        directorId: $props.statusName === '全部' && checked.value ? userStore.id : '',
      }
      exportDevice(data).then((res) => {
        exportFile(res.data, $props.equipmentType === '1' ? '智能模型信息' : '特种智能模型')
        loading.close()
      })
        .catch((_) => {
          loading.close()
        })
    }
    else {
      ElMessage.warning('无可导出内容')
    }
  }
  else {
    // 聚合表格
    if (expandTableRef.value.getSelectionRows().map((item: any) => item.id).length) {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(255, 255, 255, 0.8)',
      })
      const data = {
        ...listQuery,
        offset: undefined,
        limit: undefined,
        ids: expandTableRef.value.getSelectionRows().map((item: any) => item.id),
      }
      exportDevice(data).then((res) => {
        exportFile(res.data, $props.equipmentType === '1' ? '智能模型信息' : '特种智能模型')
        loading.close()
      })
        .catch((_) => {
          loading.close()
        })
    }
    else {
      ElMessage.warning('无可导出内容')
    }
  }
}
const fileRef = ref() // 文件上传input,获取input的引用
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('file', event.target.files[0])
    // fd.append('equipmentType', $props.equipmentType)
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    axios({
      url: `${window.localStorage.getItem('baseURL-eqpt')!}/equipment/info/import?equipmentType=${$props.equipmentType}`,
      method: 'post',
      data: fd,
      headers: { token: userStore.token },
    }).then((res) => {
      fileRef.value.value = ''
      const response = res.data
      loading.close()
      if (response.code === 200) {
        ElMessage.success(response.message)
        fetchData()
      }
      else {
        ElMessage({
          message: response.message,
          type: 'warning',
          duration: 0,
          showClose: true,
        })
      }
    }).catch(() => {
      fileRef.value.value = ''
      loading.close()
      ElMessage.error('上传失败')
    })
    //     export function importDevice(data: object, deviceType: string) {
    //   return request({
    //     url: `/equipment/info/import?equipmentType=${deviceType}`,
    //     method: 'post',
    //     data,
    //   })
    // }
    // importDevice(fd, $props.equipmentType).then((res) => {
    //   if (res.code === 200) {
    //     ElMessage.success('上传成功')
    //     fileRef.value.value = ''
    //     loading.close()

    //     fetchData(true)
    //   }
    //   else {
    //     fileRef.value.value = ''
    //     // ElMessage.error(res.message)
    //     loading.close()
    //   }
    // }).catch(() => {
    //   fileRef.value.value = ''
    //   // ElMessage.error(err.message)
    //   loading.close()
    // })
  }
}
// 导入
const importList = () => {
  fileRef.value.click()
}
// 绑定参试任务
const taskRef = ref()
const bindTask = () => {
  if (!selectList.value.length) {
    ElMessage.warning('请先选择需要绑定的智能模型')
    return
  }
  taskRef.value.initDialog()
}
// 确认绑定
const bindIds = (ids: string[]) => {
  console.log(ids, '参数任务ids')
  // bindTaskHandler()
  // 判断是 普通表格还是 聚合表格
  if (tableFlage.value) {
    // 普通表格
    const data = {
      equipmentIds: selectList.value.map(item => item.id),
      taskIds: ids,
    }
    bindTaskHandler(data).then((res) => {
      ElMessage.success('绑定成功')
      fetchData()
    })
  }
  else {
    const data = {
      equipmentNames: togetherTableRef.value.getSelectionRows().map((item: any) => item.equipmentName),
      equipmentIds: expandTableRef.value.getSelectionRows().map((item: any) => item.id),
      taskIds: ids,
    }
    bindTaskHandler(data).then((res) => {
      ElMessage.success('绑定成功')
      //
      fetchTogetherData()
      search()
    })
  }
}
// 详情
const detail = (row: IlistObjType) => {
  if ($props.statusName === '草稿箱' || $props.statusName === '未通过' || $props.statusName === '已取消') {
    handler(row, 'update')
  }
  else {
    $router.push({
      path: `/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/detail`,
      query: {
        row: JSON.stringify(row),
        id: row.id,
        statusName: $props.statusName,
        equipmentType: $props.equipmentType,
      },
    })
  }
}
// 删除
const valiate = (val: string | any) => {
  if (val) {
    return true
  }
  else {
    return false
  }
}
// 删除
const delHandler = (row: IlistObjType) => {
  if ($props.statusName === '全部') {
    // 当角色是操作手时,只有负责人是自己时可以编辑/删除
    if (userStore.roleNames.length === 1 && userStore.roleNames[0] === '操作手') {
      if (row.directorName !== userStore.name) {
        ElMessage.warning('负责人不是自己,不可删除')
        return
      }
    }
    // 删除智能模型
    ElMessageBox.prompt('请填写删除原因', '确认删除', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputValidator: valiate,

      inputErrorMessage: '请输入原因',
    })
      .then(({ value }) => {
        console.log(row, 'row')
        editInfo({
          approvalType: '3',
          equipmentId: row.id,
          id: null,
        }).then((res) => {
          // ElMessage.success('操作成功')
          // search()
          submitInfo({ id: res.data, formId: SCHEDULE.DEVICE_INFO_APPROVAL, reason: value, processId: row.processId }).then((res) => {
            ElMessage.success('操作成功')
            search()
          })
        })
        // ElMessage({
        //   type: 'success',
        //   message: `Your email is:${value}`,
        // })
      })
  }
  else {
    ElMessageBox.confirm(
      '确认删除此记录吗?',
      '确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
    // 分删除智能模型和删除记录
      deleteInfo({ id: row.id }).then((res) => {
        ElMessage.success('操作成功')
        // close()
        search()
      })
    })
  }
}
// 取消
const canHandler = (row: IlistObjType) => {
  ElMessageBox.confirm(
    '确认取消此申请吗?',
    '确认',
    {

      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    cancelInfo({ id: row.id, processInstanceId: row.processId, comments: '' }).then((res) => {
      ElMessage.success('操作成功')
      // close()
      search()
    })
  })
}
// 提交
const submit = (row: any) => {
  ElMessageBox.confirm(
    '确认提交吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    submitInfo({ id: row.id, formId: SCHEDULE.DEVICE_INFO_APPROVAL }).then((res) => {
      ElMessage.success('已提交')
      search()
    })
  })
}
// 同意拒绝
const approvalDialogRef = ref()
const approveHandler = (row: any, type: string) => {
  approvalDialogRef.value.initDialog(type, row.taskId, row.processId, row.id)
}

const changeTable = () => {
  tableFlage.value = !tableFlage.value
  reset(false)
  search()
  // if (tableFlage.value) {
  //   //  获取普通表格数据
  //   fetchData()
  // }
  // else {
  //   // 获取聚合表格数据
  //
  fetchTogetherData()
  // }
}

// ----------------------------------------------扫描----------------------------------------------------
const scanEquipmentRef = ref()
// 点击扫描查看绑定标签的智能模型
const scan = () => {
  // 参数:是标签绑定
  scanEquipmentRef.value.initDialog(false)
}
// ------------------------------------------------------------------------------------------------------
// 打印标签
const hidden = ref(true)
const printDiv = ref()
const printList = () => {
  if (!list.value.length) {
    ElMessage.warning('无可打印数据')
    return
  }
  if (!selectList.value.length) {
    ElMessage.warning('请先选择需要打印的数据')
    return
  }

  // console.log(printIframeRef.value.contentWindow)
  // const printIframe = printIframeRef.value
  // const html = printDiv.value.innerHTML
  // console.log(html, 'html')
  // printIframe.setAttribute('srcdoc', html)
  // printIframe.onload = function () {
  //   console.log(printIframe.contentWindow)
  //   // 去掉iframe里面的dom的body的padding margin的默认数值
  //   printIframe.contentWindow.document.body.style.padding = '0px'
  //   printIframe.contentWindow.document.body.style.margin = '0px'
  //   // 开始打印
  //   printIframe.contentWindow.focus()
  //   printIframe.contentWindow.print()
  // }
  hidden.value = false
  setTimeout(() => {
    hidden.value = true
  }, 100)
  setTimeout(() => {
    print({
      printable: 'printDiv',
      type: 'html',
      // targetStyles: ['*'],
      // style: '@page {margin:0mm 0mm ;resolution: 1000dpi;}',
      style: '@media print { @page { margin: 0mm;resolution: 500dpi; } body{margin:0 0px}}',
      // onPrintDialogClose: true,
      // targetStyles: ['*'], // 使用dom的所有样式,很重要
      targetStyle: '*',
      targetStyles: '*',
      // scanStyles: true,
      // 解决字体样式失效的问题
      font_size: '',
    })
  })
}
// 审批状态发生变化
watch(() => $props.statusName, (newVal) => {
  if (newVal) {
    listQuery.approvalStatus = applyDict.value[newVal] as string
    if (newVal === '全部') {
      search()
    }
    else {
      fetchData()
      tableFlage.value = true
    }
  }
},
{
  deep: true,
  immediate: true,
})
const permUrl = ref({
  edit: `/tested/device/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/edit`,
  del: `/tested/device/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/delete`,
  submit: `/tested/device/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/submit`,
  cancel: `/tested/device/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/cancel`,
  agree: `/tested/device/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/agree`,
  reject: `/tested/device/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/reject`,
  add: `/tested/device/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/add`,
  import: `/tested/device/${$props.equipmentType === '1' ? 'info' : 'speciallist'}/import`,
})

onActivated(() => {
  // 从编辑或者新增页面回来需要重新获取列表数据
  // $router.options.history.state.forward 上一次路由地址
  if (!($router.options.history.state.forward as string || '').includes('detail')) {
    console.log('需要重新获取列表')
    search()
  }
})
</script>

<template>
  <app-container>
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialogRef" @on-success="search" />
    <!-- 参试任务弹窗 -->
    <task ref="taskRef" @confirm="bindIds" />
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <!-- <search-item>
        <el-input v-model.trim="listQuery.equipmentNo" placeholder="统一编号" clearable />
      </search-item> -->
      <search-item>
        <el-select v-model.trim="listQuery.equipmentName" clearable filterable placeholder="智能模型名称">
          <el-option v-for="(item, index) in deviceNameList" :key="index" :label="item" :value="item" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model.trim="listQuery.model" clearable filterable placeholder="规格型号">
          <el-option v-for="item in modelList" :key="item" :label="item" :value="item" />
        </el-select>
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.manufactureNo" placeholder="出厂编号" />
      </search-item>
      <search-item>
        <!-- <el-input v-model.trim="listQuery.manufacturer" placeholder="厂商" /> -->
        <el-select v-model="listQuery.manufacturer" clearable filterable placeholder="厂商">
          <el-option v-for="item in manufacturerList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </search-item>
      <search-item>
        <!-- <dept-select v-model="listQuery.companyId" :need-top="false" placeholder="所在单位" /> -->
        <el-select v-model="listQuery.companyId" clearable filterable placeholder="所在单位">
          <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </search-item>
      <search-item>
        <!-- <dept-select v-model="listQuery.deptIds" :need-top="false" placeholder="使用部门" /> -->
        <!-- <el-select v-model="listQuery.deptIds" clearable filterable placeholder="使用部门">
          <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select> -->
        <el-tree-select
          v-model="listQuery.deptIds"
          style="width: 100%;"
          :data="deptList"
          :render-after-expand="false"
          check-strictly
          placeholder="部门"
        />
      </search-item>
      <search-item v-show="$props.statusName === '全部'">
        <el-checkbox v-model="checked" size="large" checked>
          只看我负责的
        </el-checkbox>
      </search-item>
      <!-- 折叠查询条件 -->
      <template #searchMore>
        <icon-button v-show="searchMore" icon="icon-zhankai" title="展开查询条件" style="margin-bottom: 10px;" @click="expandSearch" />
        <icon-button v-show="!searchMore" icon="icon-zhankai" title="折叠查询条件" style="margin-bottom: 10px;transform: rotate(180deg);" @click="expandSearch" />
      </template>
      <span v-show="!searchMore">
        <search-item>
          <el-select v-model="listQuery.meterIdentify" clearable placeholder="计量标识">
            <el-option v-for="item in meterIdentifyList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item>
          <!-- <el-input v-model.trim="listQuery.checkOrganization" placeholder="检定(校准)机构" /> -->
          <el-select v-model="listQuery.checkOrganization" clearable filterable placeholder="检定(校准)机构">
            <el-option v-for="item in checkOrganizationList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </search-item>
        <search-item>
          <!-- <el-input v-model.trim="listQuery.directorName" placeholder="负责人" clearable /> -->
          <el-select v-model="listQuery.directorName" clearable filterable placeholder="负责人" style="width: 100%;">
            <el-option v-for="(item) in userList" :key="item.id" :label="item.name" :value="item.name">
              <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>
          <el-date-picker
            v-model="listQuery.certificateValidStart"
            type="date"
            placeholder="证书有效期开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD 00:00:00"
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="listQuery.certificateValidEnd"
            type="date"
            placeholder="证书有效期结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD 23:59:59"
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="listQuery.checkDateStart"
            type="date"
            placeholder="检定(校准)开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD 00:00:00"
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="listQuery.checkDateEnd"
            type="date"
            placeholder="检定(校准)结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD 23:59:59"
          />
        </search-item>
        <!-- <search-item>
          <el-date-picker
            v-model="datetimerange" type="daterange" value-format="YYYY-MM-DD"
            format="YYYY-MM-DD" range-separator="至" start-placeholder="证书有效期开始时间" end-placeholder="证书有效期结束时间"
          />
        </search-item> -->
        <!-- <search-item>
          <el-date-picker
            v-model="datetimerange1" type="daterange" value-format="YYYY-MM-DD"
            format="YYYY-MM-DD" range-separator="至" start-placeholder="检定(校准)开始时间" end-placeholder="检定(校准)结束时间"
          />
        </search-item> -->
        <search-item>
          <el-select v-model="listQuery.usageStatus" clearable placeholder="使用状态">
            <el-option v-for="item in useStatusList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item>
          <el-select v-model="listQuery.useSign" clearable placeholder="在用信息">
            <el-option v-for="item in inUseList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item>
          <!-- <el-input v-model.trim="listQuery.usePosition" placeholder="使用岗位" clearable /> -->
          <el-select v-model="listQuery.usePositionId" filterable clearable placeholder="使用岗位">
            <el-option v-for="item in usePositionList" :key="item.id" :label="item.positionName" :value="item.id" />
          </el-select>
        </search-item>
        <search-item>
          <!-- <el-input v-model.trim="listQuery.installLocation" placeholder="安装位置" clearable /> -->
          <el-select v-model="listQuery.installLocationId" filterable clearable placeholder="安装位置">
            <el-option v-for="item in installLocationList" :key="item.id" :label="item.installLocation" :value="item.id" />
          </el-select>
        </search-item>
        <search-item>
          <el-select v-model="listQuery.taskId" clearable placeholder="参试任务">
            <el-option v-for="item in taskList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item>
          <el-select v-model="listQuery.groupId" clearable placeholder="分组">
            <el-option v-for="item in groupList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
          <!-- <el-input v-model.trim="listQuery.groupId" placeholder="分组" clearable /> -->
        </search-item>

        <!-- <search-item>
          <el-select v-model="listQuery.useSign" placeholder="在用信息" clearable>
            <el-option v-for="item in useSignList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </search-item> -->
      </span>
    </search-area>
    <table-container>
      <template v-if="$props.statusName === '全部'" #btns-right>
        <icon-button icon="icon-print" title="打印标签" @click="printList" />
        <icon-button icon="icon-change" title="切换列表状态" @click="changeTable" />
        <icon-button icon="icon-rfid" title="扫描" @click="scan" />
        <icon-button v-if="proxy.hasPerm(permUrl.add)" icon="icon-add" title="新增" @click="handler({} as any, 'create')" />
        <icon-button v-if="proxy.hasPerm(permUrl.import)" icon="icon-import" title="批量导入" @click="importList" />
        <icon-button icon="icon-template" title="模板下载" @click="useTemplateDownload('智能模型信息管理模块')" />
        <icon-button icon="icon-export" title="导出" @click="exportList" />
        <icon-button icon="icon-task" title="参试任务" @click="bindTask" />
        <input ref="fileRef" style="display: none;" type="file" accept=".xls,.xlsx" @change="onFileChange">
      </template>
      <div v-if=" tableFlage ">
        <!-- 普通表格 -->
        <normal-table
          v-show=" tableFlage "
          ref="normalTableRef" :data="list" :total="total" :columns="$props.statusName === '全部' ? [...columns, ...($props.equipmentType === '2' ? [] : allColums)] as any : columns as any" :query="listQuery"
          :list-loading="listLoading"
          :is-showmulti-select="true" :is-multi="true" @sort-change="sortChange" @change="changePage" @multi-select="multiSelect"
        >
          <template #columns>
            <!-- 全部状态 -->
            <!-- <template v-if="$props.statusName === '全部' ">

              <el-table-column
                v-for=" column of allColums " :key=" column.value "
                :label=" column.text " :prop=" column.value " :align=" column.align "
                :show-overflow-tooltip="true"
                :sortable="column.sortable"
              />
            </template> -->
            <!-- 其他审批状态 -->
            <template v-if="$props.statusName !== '全部' ">
              <el-table-column
                v-for=" column of otherColums " :key="column.value"
                :label=" column.text "
                :prop=" column.value " :align=" column.align "
                :show-overflow-tooltip="true"
              />
            </template>
            <el-table-column label="操作" width="160" align="center">
              <template #default=" scope ">
                <el-button link type="primary" size="small" @click="detail(scope.row)">
                  查看
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.edit.if({ approvalStatusName: $props.statusName }, permUrl.edit)" link type="primary" size="small"
                  @click="handler(scope.row, 'update')"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.agree.if({ approvalStatusName: $props.statusName }, permUrl.agree)" link type="primary" size="small"
                  @click="approveHandler(scope.row, 'agree')"
                >
                  同意
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.reject.if({ approvalStatusName: $props.statusName }, permUrl.reject)" link type="primary" size="small"
                  @click="approveHandler(scope.row, 'refuse')"
                >
                  拒绝
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.submit.if({ approvalStatusName: $props.statusName }, permUrl.submit)" link type="primary" size="small"
                  @click="submit(scope.row)"
                >
                  提交
                </el-button>

                <el-button
                  v-if="proxy.buttonPerm.cancel.if({ approvalStatusName: $props.statusName }, permUrl.cancel)" link type="primary" size="small"
                  @click="canHandler(scope.row)"
                >
                  取消
                </el-button>
                <el-button
                  v-if="proxy.buttonPerm.delete.if({ approvalStatusName: $props.statusName }, permUrl.del)" link type="danger" size="small"
                  @click="delHandler(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </div>
      <div v-if=" !tableFlage ">
        <!-- 展开行表格 -->
        <!-- 头部 -->
        <normal-table
          v-show=" !tableFlage " class="nortable-header" :data=" [] " :total=" 0 " :columns="togetherColums as any" :options="
            {
              needIndex: false, // 是否需要序号列
              border: true, // 是否需要上方边框
            }
          " :pagination=" false " :is-showmulti-select=" false " :query="{}"
        >
          <!-- <template #columns>
            <el-table-column label="操作" width="160" align="center" />
          </template> -->
        </normal-table>
        <!-- 身体 -->
        <el-table
          v-show=" !tableFlage "
          ref="togetherTableRef" v-loading=" togetherLoading " :data=" togetherList " border style="width: 100%;"
          :row-key=" getRowKeys " :expand-row-keys=" expands " :show-header=" false " @expand-change=" expandChange "
          @select="togetherSelect"
        >
          <!-- <el-table-column type="selection" width="38" /> -->
          <el-table-column type="expand" width="38">
            <template #default>
              <!-- 展开表格身体 -->
              <!-- <normal-table
            <template #default>
              <normal-table

                :data=" expandList " :total=" 0 " :columns=" columns " :list-loading=" expandLoading " :options="
                  {
                    needIndex: false, // 是否需要序号列
                    border: true, // 是否需要上方边框
                  }
                " :pagination=" false " :is-showmulti-select=" true " :show-header=" false " :query="{}"
              /> -->
              <el-table
                ref="expandTableRef"
                v-loading=" expandLoading " :data=" expandList " border style="width: 100%;" @select="expandSelect"
              >
                <el-table-column type="selection" width="38" />
                <el-table-column v-for="item in columns" :key="item.value" :label="item.text" :prop="item.value" align="center" />
                <!-- <el-table-column v-for="item in allColums" :key="item.value" :label="item.text" :prop="item.value" align="center" /> -->
                <el-table-column label="操作" width="160" align="center">
                  <template #default=" scope ">
                    <el-button link type="primary" size="small" @click="detail(scope.row)">
                      查看
                    </el-button>
                    <el-button
                      v-if="proxy.buttonPerm.edit.if({ approvalStatusName: $props.statusName }, permUrl.edit)" link type="primary" size="small"
                      @click="handler(scope.row, 'update')"
                    >
                      编辑
                    </el-button>
                    <el-button
                      v-if="proxy.buttonPerm.agree.if({ approvalStatusName: $props.statusName }, permUrl.agree)" link type="primary" size="small"
                      @click="approveHandler(scope.row, 'agree')"
                    >
                      同意
                    </el-button>
                    <el-button
                      v-if="proxy.buttonPerm.reject.if({ approvalStatusName: $props.statusName }, permUrl.reject)" link type="primary" size="small"
                      @click="approveHandler(scope.row, 'refuse')"
                    >
                      拒绝
                    </el-button>
                    <el-button
                      v-if="proxy.buttonPerm.submit.if({ approvalStatusName: $props.statusName }, permUrl.submit)" link type="primary" size="small"
                      @click="submit(scope.row)"
                    >
                      提交
                    </el-button>
                    <el-button
                      v-if="proxy.buttonPerm.cancel.if({ approvalStatusName: $props.statusName }, permUrl.cancel)" link type="primary" size="small"
                      @click="canHandler(scope.row)"
                    >
                      取消
                    </el-button>
                    <el-button
                      v-if="proxy.buttonPerm.delete.if({ approvalStatusName: $props.statusName }, permUrl.del)" link type="danger" size="small"
                      @click="delHandler(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="智能模型名称" prop="equipmentName" align="center" />
          <el-table-column label="数量" align="center">
            <template #default=" scope ">
              共计{{ scope.row.count }}台
            </template>
          </el-table-column>
        </el-table>
      </div>
    </table-container>
  </app-container>
  <!-- 扫描 -->
  <scan-equipment-dialog ref="scanEquipmentRef" title="扫描查询智能模型" />
  <!-- 标签打印组件 -->
  <div id="printDiv" ref="printDiv" :class="{ 'hidden-page': hidden }">
    <print-tag v-for="item of selectList" :key="item" :data="item" />
  </div>
</template>

<style lang="scss" scoped>
.nortable-header {
  ::v-deep(.el-table__body-wrapper) {
    display: none;
  }
}

::v-deep(.el-table__expanded-cell) {
  padding: 0;
}

.hidden-page {
  display: none;
}
</style>