Newer
Older
xc-business-system / src / views / resource / customer / info / basicForEdit.vue
<!-- 委托方名录 可编辑基本信息 -->
<script name="CustomerInfoBasicForEdit" lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import type { ICustomerInfo } from './customer-info'
import { mobileValidator, phoneValidator, postalCodeValidator } from './customer-info'
import { failUpdateCustomerBasic, saveCustomerBasic, submitCustomerBasic, updateCustomerBasic } from '@/api/resource/customer'
import type { IDictType } from '@/commonInterface/resource-interface'
import { UploadFile } from '@/api/file'
import labDict from '/public/config/defaultLab.json'

const props = defineProps({
  operation: { type: String, default: '' },
})

const emit = defineEmits(['afterSaveDraft', 'commitSuccess'])

// 关键字段是否可以编辑
const keyFieldsDisable = ref<boolean>(true)

// 委托方所属地字典值
const customerLocationDict = ref<Array<IDictType>>([])

const customerBasicInfo = ref<ICustomerInfo>({
  id: '',
  customerNo: '',
  customerName: '',
  deptId: '',
  customerLocation: '',
  customerLocationName: '',
  contacts: '',
  mobile: '',
  phone: '',
  postalCode: '',
  address: '',
  file: '',
  remark: '',
})
const fileNameList = ref<Array<UploadUserFile>>([])

const basicFormRef = ref()

const customerBasicRules = ref({
  deptId: [{ required: true, message: '委托方名称不能为空', trigger: 'blur' }],
  customerLocation: [{ required: true, message: '委托方所属地不能为空,请选择', trigger: ['change', 'blur'] }],
  contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '座机电话不能为空', trigger: 'blur' }, { validator: mobileValidator, trigger: 'blur' }],
  phone: [{ message: '请输入符合规范的手机号码', trigger: 'blur', validator: phoneValidator }],
  postalCode: [{ message: '邮政编码为6位数字', trigger: 'blur', validator: postalCodeValidator }],
  address: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
}) // 表单验证规则

// 逻辑
// 查询人员基本信息 从缓存中直接取
const getCustomerBasicInCache = () => {
  customerBasicInfo.value = JSON.parse(sessionStorage.getItem('customerInfo')!)

  if (customerBasicInfo.value.file !== '') {
    const files = customerBasicInfo.value.file?.split(',')
    files?.forEach((f) => {
      fileNameList.value.push({ name: f, status: 'success' })
    })
  }
}

// 设置字段是否可以编辑
const setFieldsDisable = (editable: boolean) => {
  keyFieldsDisable.value = editable
}

// 保存至草稿箱
const addCustomerBase = () => {
  saveCustomerBasic(customerBasicInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      // 设置返回的委托方id和委托方编号
      customerBasicInfo.value.customerNo = res.data.customerNo
      customerBasicInfo.value.id = res.data.id
      // 返回保存后生成的id
      emit('afterSaveDraft', res.data.id, customerBasicInfo.value.deptId)
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败:${res.message}`)
    }
  })
}
// 编辑草稿箱(不走流程审批)
const updateCustomerBase = () => {
  updateCustomerBasic(customerBasicInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败:${res.message}`)
    }
  })
}

// 保存基本信息
const saveBasicForm = async () => {
  if (!basicFormRef) { return }

  await basicFormRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗?',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (props.operation === 'create') {
          addCustomerBase()
        }
        else if (props.operation === 'update') {
          updateCustomerBase()
        }
      })
    }
  })
}

// 提交委托方
const submitBasicForm = async () => {
  ElMessageBox.confirm(`是否提交审批单 ${customerBasicInfo.value.customerNo}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    submitCustomerBasic({
      formId: 'zyglwtfml',
      id: customerBasicInfo.value.id,
    }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`审批单 ${customerBasicInfo.value.customerNo} 提交成功`)
        emit('commitSuccess', customerBasicInfo.value)
      }
      else {
        ElMessage.error(`审批单 ${customerBasicInfo.value.customerNo} 提交失败:${res.message}`)
      }
    })
  })
}

// 保存并提交审批单 重新进入流程审批
const failUpdateSubmitBasicForm = async () => {
  if (!basicFormRef) { return }
  await basicFormRef.value.validate((valid: boolean) => {
    if (valid === true) {
      failUpdateCustomerBasic(customerBasicInfo.value).then((res) => {
        if (res.code === 200) {
          // 提示保存成功
          ElMessage.success(`审批单 ${customerBasicInfo.value.customerNo} 提交成功`)
          emit('commitSuccess', customerBasicInfo.value)
        }
        else {
          // 提示失败信息
          ElMessage.error(`审批单 ${customerBasicInfo.value.customerNo} 提交失败:${res.message}`)
        }
      })
    }
  })
}

const getFileListNames = () => {
  customerBasicInfo.value.file = ''
  fileNameList.value.forEach((file) => {
    customerBasicInfo.value.file += `${file.name},`
  })
  customerBasicInfo.value.file = customerBasicInfo.value.file?.substring(0, customerBasicInfo.value.file.length - 1)
}

// 上传请求
const uploadFile: any = (file: any) => {
  const fd = new FormData()
  fd.append('multipartFile', file.file)
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  UploadFile(fd).then((res) => {
    if (res.code === 200) {
      ElMessage.success('上传成功')

      fileNameList.value.pop() // 手动将选择文件时添加的数据去掉
      fileNameList.value.push({
        name: res.data[0],
        status: 'success',
      })

      getFileListNames()
      // customerBasicInfo.value.file = res.data[0]
      loading.close()
    }
  }).catch(() => {
    loading.close()
    ElMessage.error('上传失败')
  })
}

// 删除已上传的文件
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  getFileListNames()
}

// 监听 显示中文 立即监听
watch(() => customerBasicInfo.value.customerLocation, (newVal) => {
  customerLocationDict.value = JSON.parse(sessionStorage.getItem('customerLocationDict')!)

  if (customerLocationDict.value !== undefined && customerLocationDict.value !== null && customerLocationDict.value.length > 0) {
    const targetList = customerLocationDict.value.filter(item => item.value === newVal)
    if (targetList.length > 0) {
      customerBasicInfo.value.customerLocationName = targetList[0].name
    }
    else {
      customerBasicInfo.value.customerLocationName = ''
    }
  }
}, { immediate: true })

defineExpose({
  getCustomerBasicInCache,
  setFieldsDisable,
  saveBasicForm,
  submitBasicForm,
  failUpdateSubmitBasicForm,
})
</script>

<template>
  <app-container>
    <el-form ref="basicFormRef" :model="customerBasicInfo" :rules="customerBasicRules" label-position="right" label-width="110px" border stripe>
      <el-row :gutter="24">
        <!-- 第一行 第一列 -->
        <el-col :span="6">
          <el-form-item label="委托方编号">
            <el-input v-model="customerBasicInfo.customerNo" placeholder="委托方编号,保存后自动生成" :readonly="true" :disabled="true" />
          </el-form-item>
          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="customerBasicInfo.contacts" placeholder="请输入联系人,必填项" tabindex="3" :clearable="true" />
          </el-form-item>
        </el-col>

        <!-- 第一行 第二列 -->
        <el-col :span="6">
          <el-form-item label="委托方名称" prop="deptId">
            <dept-select v-model="customerBasicInfo.deptId" placeholder="请选择委托方" tabindex="1" style="width: 100%;" :disabled="keyFieldsDisable" />
          </el-form-item>
          <el-form-item label="座机电话" prop="mobile">
            <el-input v-model="customerBasicInfo.mobile" placeholder="请输入座机(区号-号码)" tabindex="4" :clearable="true" />
          </el-form-item>
        </el-col>

        <!-- 第一行 第三列 -->
        <el-col :span="6">
          <el-form-item label="委托方所属地" prop="customerLocation">
            <el-select v-model="customerBasicInfo.customerLocation" placeholder="请选择委托方所属地" tabindex="2" style="width: 100%;" :clearable="true">
              <el-option v-for="dict in customerLocationDict" :key="dict.id" :label="dict.name" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="customerBasicInfo.phone" placeholder="请输入手机号码" tabindex="5" :clearable="true" />
          </el-form-item>
        </el-col>

        <!-- 第一行 第四列 -->
        <el-col :span="6">
          <el-form-item label="默认检定实验室">
            <el-select v-model="customerBasicInfo.defaultLab" placeholder="请选择默认检定实验室" tabindex="2" style="width: 100%;" :clearable="true">
              <el-option v-for="dict in labDict" :key="dict.id" :label="dict.name" :value="dict.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="邮编" prop="postalCode">
            <el-input v-model="customerBasicInfo.postalCode" placeholder="请输入邮政编码" tabindex="6" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="24">
        <!-- 第一列 -->
        <el-col :span="12">
          <el-form-item label="地址" prop="address">
            <el-input v-model="customerBasicInfo.address" placeholder="请输入地址" tabindex="7" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="customerBasicInfo.remark" placeholder="请输入备注信息" tabindex="8" type="textarea" :clearable="true" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="附件">
            <el-input v-model="customerBasicInfo.file" type="hidden" />
            <el-upload
              v-model:file-list="fileNameList"
              multiple
              :http-request="uploadFile"
              :on-remove="handleRemove"
            >
              <el-button type="primary">
                上传
              </el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </app-container>
</template>