Newer
Older
smart-metering-front / src / views / device / deviceMaintenance / components / maintenanceDetail.vue
dutingting on 11 Apr 2023 18 KB 设备检修列表修改
<!-- 设备检修列表新增、编辑、详情 -->
<script lang="ts" setup name="maintenanceDetail">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import dayjs from 'dayjs'
import type { IlistPageAddTypes, columnsType, returnRowType } from '../checkList_interface'
import { addEquipmentApply, equipmentApplyInfo, failUpdateEquipmentApply, submitEquipmentApply, updateEquipmentApply } from '@/api/device/checkList'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import { getUserList } from '@/api/system/user'
import type { deptType } from '@/views/device/standingBook/standingBook-interface'
import type { userType } from '@/views/system/user/user-interface'
import { cancelApproval, fetchApproval } from '@/api/approval'
import { SCHEDULE } from '@/utils/scheduleDict'
import addRow from '@/views/device/stateManage/components/selectDevice.vue'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import ApprovalRecord from '@/components/ApprovalRecord/ApprovalRecord.vue'
import useUserStore from '@/store/modules/user'

const user = useUserStore() // 用户信息
const approvalRecord = ref() // 审批流程组件ref
const infoId = ref('') // id
const from = ref('') // reject代表未通过-驳回
const buttonArray = ref<string[]>([])
const pageType = ref('add') // 页面类型: add,edit, detail
const textMap: { [key: string]: string } = {
  add: '新建',
  edit: '编辑',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
// 表单验证规则
const rules = ref({
  applyName: [{ required: true, message: '申请名称不能为空', trigger: ['blur', 'change'] }],
  applyUnit: [{ required: true, message: '申请单位不能为空', trigger: ['blur', 'change'] }],
  applyPerson: [{ required: true, message: '申请人不能为空', trigger: ['blur', 'change'] }],
  time: [{ required: true, message: '检修时间不能为空', trigger: ['blur', 'change'] }],
})

const ruleFormRef = ref<FormInstance>()
const useDeptList = ref<deptType[]>([]) // 使用部门列表
const usePersonList = ref<userType[]>([]) // 使用人列表
const usePersonOptions = ref<userType[]>([]) // 申请人列表(用户)--模糊搜索数据
const applyPersonLoading = ref(false)
const formInline = ref<IlistPageAddTypes>({
  acceptanceCheckId: '', // 检修申请id
  applyDesc: '', // 申请说明
  applyName: '', // 申请名称
  applyNo: '', // 申请编号
  applyPerson: '', // 申请人
  applyPersonName: '', // 申请人姓名
  applyType: '8', // 申请类型
  applyTypeName: '', // 申请类型名称
  applyUnit: '', // 申请单位
  applyUnitName: '', // 申请单位名称
  approvalStatus: '', // 审批状态
  approvalStatusName: '', // 审批状态名称
  createTime: '', // 创建时间
  createUser: '', // 创建人
  equipmentInfoList: [], // 设备详情列表
  equipmentList: [], // 设备列表
  id: '', // 主键
  isDel: '', // 删除id
  overhaulPerson: '',
  processId: '', // 审批id
  processResult: '',
  remark: '', // 备注
  taskId: '', // 任务id
  time: '',
  updateTime: '', // 更新时间
  version: '', // 版本号
})

// 审批弹窗开关
const applyShow = ref(false)
// 审批弹窗信息收集
const applyList = ref({
  select: '',
  epilog: '',
  approval: '',
  approvalTime: '',
})

// 检修设备列表表头
const columns = ref<columnsType[]>([
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
    required: true,
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
    width: '160px',
    required: true,
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
    required: true,
  },
  {
    text: '测量范围',
    value: 'mesureRange',
    align: 'center',
    required: true,
  },
  {
    text: '使用部门',
    value: 'useDeptName',
    align: 'center',
    required: true,
  },
  {
    text: '使用人',
    value: 'usePersonName',
    align: 'center',
    required: true,
  },
  {
    text: '管理状态',
    value: 'managerStateName',
    align: 'center',
    required: true,
  },
  {
    text: '有效日期',
    value: 'validDate',
    align: 'center',
    required: true,
    width: '120px',
  },
])

// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
// -------------------------路由参数------------------------------------
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  // if (pageType.value === 'detail') {
  //   buttonArray.value = ['同意', '驳回', '拒绝']
  // }
  // else
  if (pageType.value === 'edit') {
    buttonArray.value = ['保存']
  }
  else {
    buttonArray.value = ['提交', '保存']
  }
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
if ($route.query && $route.query.from) {
  from.value = $route.query.from as string
}
// -------------------------------------------------------------------------

// 表格选中的数组
const SelectionList = ref<object[]>([])
// 取消
const handleCancel = () => {
  const params = {
    processInstanceId: formInline.value.processId!,
    comments: '取消审批',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    cancelApproval(params).then(() => {
      ElMessage.success('取消成功')
    })
  })
}
const approvalDialog = ref()
// 点击数据后的操作按钮
const clickBtn = (buttonType: string) => {
  switch (buttonType) {
    case '同意':
      approvalDialog.value.initDialog('agree', formInline.value.taskId)
      break
    case '驳回':
      approvalDialog.value.initDialog('reject', formInline.value.taskId)
      break
    case '拒绝':
      approvalDialog.value.initDialog('refuse', formInline.value.taskId)
      break
    case '取消':
      handleCancel()
      break
  }
}
// 获取详情信息
const getInfo = () => {
  equipmentApplyInfo({ id: infoId.value }).then((res) => {
    Object.keys(res.data).map((item) => {
      if (typeof (res.data[item]) === 'number') {
        res.data[item] = res.data[item].toString()
      }
    })
    formInline.value = res.data
    formInline.value.equipmentInfoList = res.data.equipmentInfoList.map((item: any) => {
      return {
        ...item,
        validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : '',
      }
    })
  })
}
if (pageType.value !== 'add') {
  getInfo()
}
// 保存后的id
const addId = ref('')

// 保存
const save = async (formEl: FormInstance | undefined) => {
  if (!formInline.value.equipmentInfoList.length) {
    ElMessage.warning('要求设备检修列表不能为空')
    return
  }
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗?',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        // 处理数据
        if (formInline.value.equipmentInfoList && formInline.value.equipmentInfoList.length) {
          formInline.value.equipmentList = formInline.value.equipmentInfoList.map((item: any) => {
            return {
              equipmentId: item.id,
            }
          })
        }
        else {
          formInline.value.equipmentList = []
        }
        if (pageType.value === 'add') { // 新建
          addEquipmentApply(formInline.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('保存成功')
              addId.value = res.data
            }
          })
        }
        else if (pageType.value === 'edit') { // 编辑
          if (from.value === 'reject') { // 未通过-驳回的编辑
            failUpdateEquipmentApply(formInline.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('保存成功')
                close()
              }
            })
          }
          else {
            updateEquipmentApply(formInline.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('保存成功')
                close()
              }
            })
          }
        }
      })
    }
  })
}
// 提交
const submit = () => {
  if (addId.value === '') {
    ElMessage.warning('请先保存')
  }
  else {
    submitEquipmentApply({ id: addId.value, formId: SCHEDULE.DEVICE_FIX_APPROVAL }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('已提交')
        close()
      }
    })
  }
}

const addRowRef = ref()
// 点击批量增加
const batchIncrease = () => {
  addRowRef.value.initDialog({ title: '' })
}

// 删除行
const removeRow = () => {
  if (SelectionList.value.length > 0) {
    // 删除行
    formInline.value.equipmentInfoList = formInline.value.equipmentInfoList.filter((item) => {
      return !SelectionList.value.includes(item)
    })
    // 删除给equipmentList重新赋值
    // formInline.value.equipmentList = []
    // formInline.value.equipmentInfoList.forEach((item: returnRowType, index: number) => {
    //   formInline.value.equipmentList.push({ equipmentId: item.id })
    // })
  }
  else {
    ElMessage.warning('请先选择需要删除的数据')
  }
}
// 表格多选框
const handleSelectionChange = (e: any) => {
  SelectionList.value = e
}

// 检修设备列表-选好设备了
const confirmSelectDevice = (row: returnRowType[]) => {
  row.forEach((item: returnRowType) => {
    // 只添加列表里不存在的
    const findIndex = formInline.value.equipmentInfoList.findIndex((i: any) => item.id === i.id)
    if (findIndex === -1) {
      formInline.value.equipmentInfoList.push(item)
    }
  })
}

// 选好申请人 userId用户id
const changeSelectReceiver = (userId: string) => {
  // 在用户列表里找到选择的接收人的名字
  const name = usePersonList.value.find(item => item.id === userId)!.name
  // dataForm.value.reciever = name
}
// 选择器模糊查询--申请人
const remoteMethod = (query: string) => {
  if (query) {
    applyPersonLoading.value = true
    setTimeout(() => {
      applyPersonLoading.value = false
      usePersonOptions.value = usePersonList.value.filter((item) => {
        return item.name.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  }
  else {
    usePersonOptions.value = usePersonList.value
  }
}
// 审批弹窗的关闭
const applyListClose = () => {
  applyShow.value = false
}
// 审批弹窗的提交
const applyListSubmit = () => {
  console.log(applyList.value)
  if (applyList.value.select == '') {
    return ElMessage.error('必须选择审批意见')
  }
  applyListClose()
}
// 获取部门列表
const fetchDeptTreeList = () => {
  getDeptTreeList().then((res) => {
  // 转成树结构
    useDeptList.value = toTreeList(res.data, '0', true)
  })
}
// 获取用户列表
const fetchUserList = () => {
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    usePersonList.value = res.data.rows
    usePersonOptions.value = res.data.rows
  })
}
const approvalRecordData = ref([]) // 审批流程数据
// 查询审批记录
function getApprovalRecord(processId: string) {
  if (pageType.value !== 'add') {
    if (processId) {
      fetchApproval(processId).then((res) => {
        approvalRecordData.value = res.data
      })
    }
    else {
      ElMessage.warning('流程实例id为空')
    }
  }
}
// 审批结束回调
const approvalSuccess = () => {
  getInfo()
}
onMounted(async () => {
  formInline.value.applyName = '设备检修申请' // 申请名称固定
  formInline.value.applyUnit = user.deptId // 申请单位
  formInline.value.applyUnitName = user.deptName // 申请单位名称
  formInline.value.applyPerson = user.id // 申请人
  formInline.value.applyPersonName = user.name // 申请人名称
  formInline.value.time = dayjs().format('YYYY-MM-DD HH:mm:ss') // 申请时间
  await fetchUserList()
  await fetchDeptTreeList()
  formInline.value.processId = $route.params.processId as string // 任务id
  formInline.value.approvalStatusName = $route.params.approvalStatusName as string // 任务id
  if (formInline.value.approvalStatusName !== '草稿箱') {
    getApprovalRecord(formInline.value.processId) // 查询审批记录
  }
})
</script>

<template>
  <app-container>
    <detail-page :title="`${$route.meta.title}-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType === 'add'" type="primary" @click="submit">
          提交
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="formInline"
        label-position="right"
        label-width="110px"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="申请编号:">
              <el-input
                v-model.trim="formInline.applyNo"
                :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请名称:">
              <el-input
                v-model.trim="formInline.applyName"
                :placeholder="pageType === 'detail' ? '' : '请输入申请名称'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请单位:">
              <!-- <dept-select
                v-model="formInline.applyUnit"
                :data="useDeptList"
                :placeholder="pageType === 'detail' ? '' : '请选择申请单位'"
                :disabled="pageType === 'detail'"
              /> -->
              <el-input
                v-model="formInline.applyUnitName"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人:">
              <!-- <el-select
                v-model="formInline.applyPerson"
                :placeholder="pageType === 'detail' ? '' : '请选择申请人'"
                :disabled="pageType === 'detail'"
                style="width: 100%;"
                filterable
                remote
                remote-show-suffix
                :remote-method="remoteMethod"
                :loading="applyPersonLoading"
                @change="changeSelectReceiver"
              >
                <el-option
                  v-for="item in usePersonOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select> -->
              <el-input
                v-model="formInline.applyPersonName"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="检修时间:" prop="time">
              <el-date-picker
                v-model="formInline.time"
                type="datetime"
                style="width: 100%;"
                :placeholder="pageType === 'detail' ? '' : '请选择检修时间'"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model.trim="formInline.remark"
                :placeholder="pageType === 'detail' ? '' : '请填写备注'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="检修设备列表">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="batchIncrease">
          批量增加
        </el-button>
        <!-- <el-button type="primary" @click="addRoow">
          增加行
        </el-button> -->
        <el-button type="info" @click="removeRow">
          删除行
        </el-button>
      </template>
      <el-table
        :data="formInline.equipmentInfoList"
        border
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="center" label="序号" width="60" type="index" />
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          align="center"
          :label="item.text"
          :width="item.width"
          :prop="item.value"
        >
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
    <detail-block v-if="formInline.approvalStatusName !== '草稿箱' && pageType !== 'add'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    <!-- 借用设备列表 -->
    <add-row ref="addRowRef" @add="confirmSelectDevice" />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
.top-info {
  width: 100%;
  height: 50px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10px;
  background-color: #fff;

  .title {
    width: 75%;
    text-align: center;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px;
  width: 100%;
  height: 6vh;
  margin-top: 10px;
  background-color: rgb(255 255 255);
}

.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      display: none;
    }
  }
}
</style>