Newer
Older
xc-business-system / src / views / equipement / resume / week / list.vue
<!-- 周维护列表 -->
<script lang="ts" setup name="EquipmentResumeWeekList">
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { DateModelType } from 'element-plus'
import dayjs from 'dayjs'
import type { IList, IListQuery, IListQueryToMaintain } from './week-interface'
import { getStaffList } from '@/api/resource/register'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'
import buttonBox from '@/components/buttonBox/buttonBox.vue'
import type { deptType, dictType } from '@/global'
import { batchDelete, batchIgnore, exportResumeWeekMonthRecordList, getEquipmentWeekOrMonthDetail, getResumeWeekMonthList, getResumetoMaintainList } from '@/api/equipment/resume/week-month'
const $router = useRouter()
const buttonBoxActive = 'equipmentResumeWeek' // 存储在sessionstorage里面的字段名,用于记录右上角buttonbox点击状态
const active = ref('')
const loadingTable = ref(false)
const tableRef = ref() // 表格组件ref
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  checkResult: '', // 检查结果
  createTimeEnd: '', // 记录时间结束
  createTimeStart: '', // 记录时间开始
  createUserName: '', // 记录人
  logNo: '', // 记录编号
  maintainType: 1, // 保养类型 1 周维护/2 月保养
  equipmentId: '', //	设备台账id
  groupCode: '', //	部门(字典code)
  labCode: '', //	实验室(字典code)
  limit: 20,
  offset: 1,
})

const listQueryToMaintain: Ref<IListQueryToMaintain> = ref({
  directorId: '', //	负责人id(来自人员登记)
  directorName: '', //	负责人名字(来自人员登记)
  equipmentName: '', //	设备名称
  equipmentNo: '', //	设备编号
  groupCode: '', //	部门(字典code)
  labCode: '', //	实验室(字典code)
  model: '',
  manufactureNo: '', //	出厂编号
  manufacturer: '', //	生产厂家
  measureValidDateEnd: '', //	检定有效期结束
  measureValidDateStart: '', //	检定有效期开始
  meterStandardName: '', //	所属标准装置名称
  traceCompany: '', //	溯源单位
  maintainType: 1,
  limit: 20,
  offset: 1,
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据检定有效期
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据记录时间
const columns = ref<TableColumn[]>([ // 表头-待维护
  { text: '设备名称', value: 'equipmentName', align: 'center' },
  { text: '规格型号', value: 'model', align: 'center' },
  { text: '出厂编号', value: 'manufactureNo', align: 'center' },
  { text: '生产厂家', value: 'manufacturer', align: 'center' },
  { text: '实验室', value: 'labCodeName', align: 'center' },
  { text: '部门', value: 'groupCodeName', align: 'center' },
  { text: '负责人', value: 'directorName', align: 'center', width: '120' },
  { text: '使用状态', value: 'usageStatusName', align: 'center', width: '90' },
  { text: '溯源单位', value: 'traceCompany', align: 'center' },
  { text: '检定有效期', value: 'measureValidDate', align: 'center', width: '120' },
  // { text: '所属标准装置', value: 'meterStandardName', align: 'center', width: '120' },
  { text: '最近一次周维护时间', value: 'recentMaintainTime', align: 'center', width: '180' },
])

const columnsAllRecord = ref<TableColumn[]>([ // 表头-全部维护记录
  { text: '文件编号', value: 'logNo', align: 'center', width: '180' },
  { text: '文件名称', value: 'logName', align: 'center' },
  { text: '实验室', value: 'labCodeName', align: 'center' },
  { text: '部门', value: 'groupCodeName', align: 'center' },
  { text: '记录人', value: 'createUserName', align: 'center' },
  { text: '设备名称', value: 'equipmentName', align: 'center' },
  { text: '记录时间', value: 'createTime', align: 'center', width: '180' },
  { text: '检查结果', value: 'checkResultName', align: 'center', styleFilter: (row: { checkResultName: string }) => { return `${row.checkResultName}` === '不正常' ? 'color: red' : 'color: #1aa034' } },
])
const list = ref<IList[]>([]) // 列表
const total = ref(0) // 数据总条数
// 选中的内容
const checkoutIdList = ref<string[]>([])
const checkoutList = ref<IList[]>([])
const menu = ref([
  {
    id: '1',
    value: '1',
    name: '待维护',
  },
  {
    id: '2',
    value: '2',
    name: '全部维护记录',
  },
]) // 审批状态按钮组合

// -----------------------------------------字典--------------------------------------------------------------
const checkResultList = ref<dictType[]>([]) // 检查结果
const useDeptList = ref<deptType[]>([]) // 所属部门列表
const labDeptList = ref<deptType[]>([]) // 实验室
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
// 查询字典
const getDict = async () => {
  // 检查结果
  getDictByCode('bizMaintainCheckResult').then((response) => {
    checkResultList.value = response.data
  })
  // 实验室
  getDictByCode('bizGroupCodeEquipment').then((response) => {
    labDeptList.value = response.data
  })

  // 部门
  getDictByCode('bizGroupCode').then((response) => {
    useDeptList.value = response.data
  })
  // 获取用户列表
  getStaffList({ offset: 1, limit: 999999 }).then((res: any) => {
    userList.value = res.data.rows
  })
}
// ---------------------------------------------------------------------------------------------------------
// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutIdList.value = e.map((item: { id: string }) => item.id)
  checkoutList.value = e
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页,否则跳转第一页
    listQuery.value.offset = 1
  }
  if (active.value === '1') {
    getResumetoMaintainList(listQueryToMaintain.value).then((response) => {
      list.value = response.data.rows
      total.value = parseInt(response.data.total)
      loadingTable.value = false
    })
  }
  else {
    getResumeWeekMonthList(listQuery.value).then((response) => {
      list.value = response.data.rows
      total.value = parseInt(response.data.total)
      loadingTable.value = false
    })
  }

  // list.value = [
  //   {
  //     equipmentName: '1',
  //     logNo: '1',
  //   },
  //   {
  //     equipmentName: '2',
  //     logNo: '2',
  //   },
  // ]
}
// 清除条件
const clearList = () => {
  if (active.value === '1') { // 待维护、待保养
    listQueryToMaintain.value = {
      directorId: '', //	负责人id(来自人员登记)
      directorName: '', //	负责人名字(来自人员登记)
      equipmentName: '', //	设备名称
      equipmentNo: '', //	设备编号
      groupCode: '', //	部门(字典code)
      labCode: '', //	实验室(字典code)
      model: '',
      manufactureNo: '', //	出厂编号
      manufacturer: '', //	生产厂家
      measureValidDateEnd: '', //	检定有效期结束
      measureValidDateStart: '', //	检定有效期开始
      meterStandardName: '', //	所属标准装置名称
      maintainType: 1,
      traceCompany: '', //	溯源单位
      limit: 20,
      offset: 1,
    }
    dateRange.value = ['', '']
  }
  else {
    listQuery.value = {
      checkResult: '', // 检查结果
      createTimeEnd: '', // 记录时间结束
      createTimeStart: '', // 记录时间开始
      createUserName: '', // 记录人
      logNo: '', // 记录编号
      maintainType: 1, // 保养类型 1 周维护/2 月保养
      equipmentId: '', //	设备台账id
      groupCode: '', //	部门(字典code)
      labCode: '', //	实验室(字典code)
      limit: 20,
      offset: 1,
    }
    timeRange.value = ['', '']
  }

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

// 新建
const add = () => {
  $router.push({
    path: 'week/add',
    query: {
      currentTab: active.value,
    },
  })
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      checkResult: listQuery.value.checkResult, // 检查结果
      createTimeEnd: listQuery.value.createTimeEnd, // 记录时间结束
      createTimeStart: listQuery.value.createTimeStart, // 记录时间开始
      createUserName: listQuery.value.createUserName, // 记录人
      logNo: listQuery.value.logNo, // 记录编号
      maintainType: listQuery.value.maintainType, // 保养类型 1 周维护/2 月保养
      equipmentId: listQuery.value.equipmentId, //	设备台账id
      groupCode: listQuery.value.groupCode, //	部门(字典code)
      labCode: listQuery.value.labCode, //	实验室(字典code)
      offset: 1,
      limit: 20,
      ids: checkoutIdList.value,
    }
    exportResumeWeekMonthRecordList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '周维护.xlsx')
      loading.close()
    })
  }
  else {
    loading.close()
    ElMessage.warning('无数据可导出数据')
  }
}

// 批量忽略
const handleBatchIgnore = (row: any = null) => {
  if (!row && !checkoutIdList.value.length) {
    ElMessage.warning('请至少选择一条数据')
    return false
  }
  ElMessageBox.confirm(
    '确认忽略所选操作吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(255, 255, 255, 0.6)',
      })
      if (row && row.id) { // 单次操作
        batchIgnore([{ ...row, ignored: 1, id: '', equipmentId: row.id, createTime: '', updateTime: '' }]).then(() => {
          ElMessage.success('本次已忽略')
          fetchData()
          loading.close()
        })
      }
      else { // 批量操作
        const params = checkoutList.value.map((item) => {
          return {
            ...item,
            ignored: 1,
            equipmentId: item.id,
            createTime: '',
            updateTime: '',
            id: '',
          }
        })
        batchIgnore(params).then(() => {
          ElMessage.success('操作成功')
          tableRef.value.clearMulti()
          loading.close()
          fetchData()
        })
      }
    })
}

// 根据设备id去查询每个设备的默认提醒项目
const fetchEquipmentCheckItem = (id: any) => {
  return new Promise((resolve, reject) => {
    getEquipmentWeekOrMonthDetail({ id }).then((res) => {
      resolve(res.data)
    })
  })
}

// 比较维护项目是否完全相同
const compareCheckItem = (list: any) => {
  let comResult = true
  let diffIndex = 1
  for (let i = 1; i < list.length; i++) {
    if (
      list[0].appearanceCheckWeek !== list[i].appearanceCheckWeek
      || list[0].calibrationFactorWeek !== list[i].calibrationFactorWeek
      || list[0].folderCheckWeek !== list[i].folderCheckWeek
      || list[0].functionCheckWeek !== list[i].functionCheckWeek
      || list[0].oilCheckWeek !== list[i].oilCheckWeek
      || list[0].powerCheckWeek !== list[i].powerCheckWeek
      || list[0].softwareCheckWeek !== list[i].softwareCheckWeek
    ) {
      comResult = false
      diffIndex = i
      break
    }
  }
  return {
    comResult, diffIndex,
  }
}
// 比较配置是否相同
const compareConfig = () => {
  return new Promise((resolve, reject) => {
    const tempResultArr: any = []
    Promise.all(checkoutList.value.map(async (item) => {
      const res = await fetchEquipmentCheckItem(item.id)
      tempResultArr.push(res)
    })).then(() => {
      console.log('各个配置', tempResultArr)
      const { comResult, diffIndex } = compareCheckItem(tempResultArr)
      resolve({ comResult, diffIndex })
    })
      .catch(() => ElMessage.warning('存在设备查询默认维护项目失败'))
  })
}

// 批量记录
const batchRecord = async () => {
  if (checkoutIdList.value.length < 2) {
    ElMessage.warning('请至少选择2条数据')
    return false
  }
  const tempArr = checkoutList.value.map((item) => {
    return {
      equipmentName: item.equipmentName! + item.model + item.manufactureNo,
      equipmentId: item.id,
    }
  })
  // 先比较所选的几个设备的默认配置是否相同,完全相同才可以进行编辑
  const { comResult, diffIndex }: any = await compareConfig()
  console.log(comResult)
  console.log(diffIndex)

  if (comResult) { // 几个设备的默认配置完全相同
    $router.push({
      path: 'week/add',
      query: {
        // 这里带上设备id,名称,型号,出厂编号
        fromTab: 'batchToBeMaintained',
        equipmentArr: JSON.stringify(tempArr), //		设备台账id
      },
    })
  }
  else { // 几个设备的默认配置不同
    // 这里已第一个为基准,下面的设备如果找到与第一个设备的维护项目不同,就
    ElMessage.warning(`【${checkoutList.value[diffIndex].equipmentName}】设备的默认维护项目不同,不支持批量操作。`)
    return false
  }
}

// 页数发生变化后的操作,可能是页码变化,可能是每页容量变化,此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    if (active.value === '1') {
      listQueryToMaintain.value.limit = val.size
    }
    else {
      listQuery.value.limit = val.size
    }
  }
  if (val && val.page) {
    if (active.value === '1') {
      listQueryToMaintain.value.offset = val.page
    }
    else {
      listQuery.value.offset = val.page
    }
  }
  fetchData(true)
}

// 操作
const handleEdit = (row: IList, val: string) => {
  const tempArr = [{
    equipmentName: row.equipmentName! + row.model + row.manufactureNo,
    equipmentId: row.id,
  }]
  switch (val) {
    case 'delete':
      ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      )
        .then(() => {
          batchDelete({ ids: [row.id] }).then((res) => {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            fetchData(true)
          })
        })
      break
    case 'ignore': // 忽略本次
      handleBatchIgnore(row)
      break
    case 'record': // 周维护记录
      $router.push({
        path: 'week/add',
        query: {
          // 这里带上设备id,名称,型号,出厂编号
          fromTab: 'toBeMaintained',
          equipmentArr: JSON.stringify(tempArr), //		设备台账id
        },
      })
      break
    default:
      $router.push({
        path: `week/${val}/${row.id}`,
      })
      break
  }
}

// ---------------------------------------切换tab---------------------------------------------------------------------
// 切换tab状态
const changeCurrentButton = (val: string) => {
  active.value = val // 此时的tab
  window.sessionStorage.setItem(buttonBoxActive, val) // 记录tab状态
  tableRef.value.clearMulti()
  clearList() // 刷新
}

// ---------------------------------------钩子----------------------------------------------
watch(timeRange, (val) => { // 监听记录时间
  if (val) {
    listQuery.value.createTimeStart = `${val[0]}`
    listQuery.value.createTimeEnd = `${val[1]}`
  }
  else {
    listQuery.value.createTimeStart = ''
    listQuery.value.createTimeEnd = ''
  }
})

watch(dateRange, (val) => { // 监听检定有效期
  if (val) {
    listQueryToMaintain.value.measureValidDateStart = `${val[0]}`
    listQueryToMaintain.value.measureValidDateEnd = `${val[1]}`
  }
  else {
    listQueryToMaintain.value.measureValidDateStart = ''
    listQueryToMaintain.value.measureValidDateEnd = ''
  }
})

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

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <search-area :need-clear="true" @search="searchList" @clear="clearList">
        <search-item v-if="active === '2'">
          <el-input v-model.trim="listQuery.logNo" placeholder="文件编号" class="short-input" clearable />
        </search-item>
        <search-item v-if="active === '1'">
          <el-input v-model.trim="listQueryToMaintain.equipmentName" placeholder="设备名称" class="short-input" clearable />
        </search-item>
        <search-item v-if="active === '1'">
          <el-input v-model.trim="listQueryToMaintain.model" placeholder="规格型号" class="short-input" clearable />
        </search-item>
        <search-item v-if="active === '1'">
          <el-input v-model.trim="listQueryToMaintain.manufactureNo" placeholder="出厂编号" class="short-input" clearable />
        </search-item>
        <search-item v-if="active === '1'">
          <el-input v-model.trim="listQueryToMaintain.manufacturer" placeholder="生产厂家" class="short-input" clearable />
        </search-item>
        <search-item v-if="active === '1'">
          <el-select
            v-model="listQueryToMaintain.labCode"
            placeholder="实验室"
            class="short-input"
            filterable
            clearable
          >
            <el-option v-for="item in labDeptList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item v-if="active === '1'">
          <el-select
            v-model="listQueryToMaintain.groupCode"
            placeholder="部门"
            class="short-input"
            filterable
            clearable
          >
            <el-option v-for="item in useDeptList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item v-if="active === '2'">
          <el-select
            v-model="listQuery.labCode"
            placeholder="实验室"
            class="short-input"
            filterable
            clearable
          >
            <el-option v-for="item in labDeptList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item v-if="active === '2'">
          <el-select
            v-model="listQuery.groupCode"
            placeholder="部门"
            class="short-input"
            filterable
            clearable
          >
            <el-option v-for="item in useDeptList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item v-if="active === '2'">
          <el-input v-model.trim="listQuery.createUserName" placeholder="记录人" class="short-input" clearable />
        </search-item>
        <search-item v-if="active === '1'">
          <el-select
            v-model="listQueryToMaintain.directorId"
            placeholder="负责人"
            class="short-input"
            filterable
            clearable
          >
            <el-option v-for="item in userList" :key="item.id" :label="item.staffName" :value="item.id" />
          </el-select>
        </search-item>
        <search-item v-if="active === '1'">
          <el-input v-model.trim="listQueryToMaintain.traceCompany" placeholder="溯源单位" class="short-input" clearable />
        </search-item>
        <search-item v-if="active === '1'">
          <el-date-picker
            v-model="dateRange"
            class="short-input"
            type="daterange"
            range-separator="至"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            start-placeholder="检定有效期(开始)"
            end-placeholder="检定有效期(结束)"
          />
        </search-item>
        <!-- <search-item v-if="active === '1'">
          <el-input v-model.trim="listQueryToMaintain.meterStandardName" placeholder="所属标准装置" class="short-input" clearable />
        </search-item> -->
        <search-item v-if="active === '2'">
          <el-date-picker
            v-model="timeRange"
            class="short-input"
            type="datetimerange"
            range-separator="至"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="记录时间(开始)"
            end-placeholder="记录时间(结束)"
          />
        </search-item>
        <search-item v-if="active === '2'">
          <el-select
            v-model="listQuery.checkResult"
            placeholder="检查结果"
            class="short-input"
            filterable
            clearable
          >
            <el-option v-for="item in checkResultList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <icon-button v-if="active === '1'" icon="icon-batch" title="批量记录" type="primary" @click="batchRecord" />
          <icon-button v-if="active === '1'" icon="icon-batch-ignore" title="批量忽略" type="primary" @click="handleBatchIgnore" />
          <icon-button v-if="active === '2'" icon="icon-add" title="新建" type="primary" @click="add" />
          <icon-button v-if="active === '2'" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        </template>
        <normal-table
          ref="tableRef"
          :data="list" :total="total" :columns="active === '1' ? columns : columnsAllRecord" :query="active === '1' ? listQueryToMaintain : 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">
                <span v-if="active === '1'">{{ (listQueryToMaintain.offset - 1) * listQueryToMaintain.limit + scope.$index + 1 }}</span>
                <span v-if="active === '2'">{{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
          </template>
          <template #columns>
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="150"
            >
              <template #default="{ row }">
                <el-button
                  v-if="active === '1'"
                  size="small"
                  type="primary"
                  link
                  @click="handleEdit(row, 'record')"
                >
                  周维护记录
                </el-button>
                <el-button
                  v-if="active === '1'"
                  size="small"
                  type="primary"
                  link
                  @click="handleEdit(row, 'ignore')"
                >
                  忽略本次
                </el-button>
                <el-button
                  v-if="active === '2'"
                  size="small"
                  type="primary"
                  link
                  @click="handleEdit(row, 'detail')"
                >
                  查看
                </el-button>
                <el-button
                  v-if="active === '2'"
                  size="small"
                  link
                  type="primary"
                  @click="handleEdit(row, 'edit')"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="active === '2'"
                  size="small"
                  type="danger"
                  link
                  @click="handleEdit(row, 'delete')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
    <!-- 右上角按钮集合 -->
    <button-box :active="active" :show-bridge="false" :menu="menu" @change-current-button="changeCurrentButton" />
  </div>
</template>