<!-- 要求、委托书及合同评审表列表详情 -->
<script name="ExamineDetail" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { ICustomerInfo } from '../info/customer-info'
import type { ICustomerExamineInfo } from './customer-examine'
import ExamineApprovalDialog from './examineApprovalDialog.vue'
import { getDictByCode } from '@/api/system/dict'
import type { IDictType } from '@/commonInterface/resource-interface'
import useUserStore from '@/store/modules/user'
import { deleteExamineRevoked, failUpdateExamine, saveExamine, submitExamine, updateDraftExamine } from '@/api/resource/examine'

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')
const status = ref<string>('')

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

const flowFormId = 'zyglyqwtsjhtpsb' // 资源管理 - 要求、委托书及合同评审表

const userInfo = useUserStore()
const route = useRoute()
const router = useRouter()
const title = ref('')

const radioItems = ref([
  { name: '基本信息', value: 'examine-basic' },
  { name: '审批详情', value: 'examine-approval' },
])

const current = ref('')
const currentLabel = ref('')

// 弹窗子组件
const apprDial = ref()
const examineRef = ref()

const examineRules = ref({
  labCode: [{ required: true, message: '实验室代码不能为空，请选择', trigger: ['change', 'blur'] }],
  groupCode: [{ required: true, message: '组别代码不能为空，请选择', trigger: ['change', 'blur'] }],
  customerContent: [{ required: true, message: '委托方信息不能为空', trigger: 'blur' }],
  measureItem: [{ required: true, message: '测试、校准或检定项目不能为空', trigger: 'blur' }],
  otherRequire: [{ required: true, message: '其他要求不能为空', trigger: 'blur' }],
  equipmentName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  performanceIndex: [{ required: true, message: '设备性能指标不能为空', trigger: 'blur' }],
  measureStatus: [{ required: true, message: '设备校准状态不能为空', trigger: 'blur' }],
  numberOfPeople: [{ required: true, message: '检定人员人数不能为空，请选择', trigger: 'blur' }],
  staffCert: [{ required: true, message: '人员持证情况不能为空', trigger: 'blur' }],
  measureMethodName: [{ required: true, message: '方法名称不能为空', trigger: 'blur' }],
  measureMethodType: [{ required: true, message: '方法类型不能为空，请选择', trigger: 'blur' }],
  measureMethodControlled: [{ required: true, message: '方法是否受控不能为空，请选择', trigger: 'blur' }],
  measureMethodConfirm: [{ required: true, message: '方法是否确认不能为空，请选择', trigger: 'blur' }],
}) // 表单验证规则

// 是否显示相关按钮
const saveButtVisable = ref<boolean>(false) // 是否显示 保存 按钮
const submitButtVisable = ref<boolean>(false) // 是否显示 提交 按钮
const flowButtsVisable = ref<boolean>(false) // 是否显示 同意和拒绝 按钮
const cancelButtVisable = ref<boolean>(false) // 是否显示 取消 按钮
const deleteButtVisable = ref<boolean>(false) // 是否显示 删除 按钮
const editButtVisable = ref<boolean>(false) // 是否显示 编辑 按钮

const examineInfo = ref<ICustomerExamineInfo>({
  id: '',
  formNo: '',
  formName: '要求、委托书及合同评审表',
  labCode: '',
  labCodeName: '',
  groupCode: '',
  groupCodeName: '',
  customerId: '',
  customerName: '',
  signUserId: '',
  signStatus: '',
  signStatusName: '',
  customerContent: '',
  measureItem: '',
  otherRequire: '',
  equipmentName: '',
  performanceIndex: '',
  measureStatus: '',
  numberOfPeople: 0,
  staffCert: '',
  measureMethodName: '',
  measureMethodType: '',
  measureMethodTypeName: '',
  measureMethodConfirm: 2,
  measureMethodControlled: 2,
  approvalStatus: '',
  approvalStatusName: '',
  appealUserId: '',
  appealUserName: '',
  processId: '',
  taskId: '',
  remark: '',
  decisionItem: '',
  createUserId: '',
  createUserName: '',
  createTime: '',
})

// 字典值
const labCodeDict = ref<IDictType[]>([])
const groupCodeDict = ref<IDictType[]>([])
const methodTypeDict = ref<IDictType[]>([])
const yesOrNoDict = ref([
  { id: '1', value: 1, name: '是' },
  { id: '0', value: 0, name: '否' },
])

// 逻辑
// 详情页的各个tab切换操作
const radioChangeHandler = (newVal: string | number | boolean) => {
  const radioTarget = radioItems.value.filter(item => item.name === newVal)
  if (radioTarget.length > 0) {
    currentLabel.value = radioTarget[0].name
    current.value = radioTarget[0].value
  }
  else {
    currentLabel.value = radioItems.value[0].name
    current.value = radioItems.value[0].value
  }
}

// 将所有流程操作的按钮隐藏
const hideAllOpterationButtons = () => {
  saveButtVisable.value = false
  submitButtVisable.value = false
  flowButtsVisable.value = false
  cancelButtVisable.value = false
  deleteButtVisable.value = false
  editButtVisable.value = false
}

// 根据审批状态显示对应的流程操作按钮
const showOperationButtonByStatus = () => {
  switch (status.value) {
    case '1':
      // 草稿箱：保存、提交按钮可见
      saveButtVisable.value = true
      submitButtVisable.value = true
      break

    case '2':
      // 待审批：同意、拒绝按钮可见
      flowButtsVisable.value = true
      break

    case '3':
      // 审批中：取消按钮可见
      cancelButtVisable.value = true
      break

    case '5':
      // 未通过：编辑 按钮可见
      editButtVisable.value = true
      break

    case '6':
      // 已取消：编辑 删除按钮可见
      editButtVisable.value = true
      deleteButtVisable.value = true
      break

    default:
      // 默认不显示所有的操作按钮
      hideAllOpterationButtons()
      break
  }
}

// 关闭
const resetForm = () => {
  sessionStorage.removeItem('examineInfo') // 返回列表时 将缓存中的数据删除
  router.go(-1)
}

// 保存至草稿箱
const saveExamineInfo = () => {
  examineInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss') // 创建时间改为提交时间
  saveExamine(examineInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      // 设置返回的评审表单编号和id
      examineInfo.value.formNo = res.data.formNo
      examineInfo.value.id = res.data.id
      id.value = res.data.id

      type.value = 'update'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 编辑草稿箱（不走流程审批）
const updateSuggestInfo = () => {
  updateDraftExamine(examineInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 编辑按钮点击事件处理函数
const editClickedHandler = () => {
  type.value = 'update'
  title.value = '要求、委托书及合同评审表（编辑）'

  // 隐藏编辑按钮 显示提交按钮
  editButtVisable.value = false
  submitButtVisable.value = true
}

// 新建时保存后的处理 获取返回的id
const saveButtonHandler = async () => {
  if (!examineRef) { return }

  await examineRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (type.value === 'create') {
          saveExamineInfo()
        }
        else if (type.value === 'update') {
          updateSuggestInfo()
        }
      })
    }
  })
}

// 提交按钮
const submitButtonHandler = async () => {
  if (examineInfo.value === null || examineInfo.value.processId === undefined || examineInfo.value.processId === '') {
    // 流程id为空 表示还未进入流程中 直接提交
    ElMessageBox.confirm(`是否提交审批表 ${examineInfo.value.formNo}`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      submitExamine({
        formId: flowFormId,
        id: examineInfo.value.id,
      }).then((res) => {
        if (res.code === 200) {
          ElMessage.success(`审批表 ${examineInfo.value.formNo} 提交成功`)

          type.value = 'detail'
          hideAllOpterationButtons()
        }
        else {
          ElMessage.error(`审批表 ${examineInfo.value.formNo} 提交失败：${res.message}`)
        }
      })
    })
  }
  else {
    // 之前已经在流程中的表单 保存提交
    await examineRef.value.validate((valid: boolean) => {
      if (valid === true) {
        failUpdateExamine(examineInfo.value).then((res) => {
          if (res.code === 200) {
          // 提示保存成功
            ElMessage.success(`审批表 ${examineInfo.value.formNo} 提交成功`)

            type.value = 'detail'
            hideAllOpterationButtons()
          }
          else {
          // 提示失败信息
            ElMessage.error(`审批表 ${examineInfo.value.formNo} 提交失败：${res.message}`)
          }
        })
      }
    })
  }
}

// 流程审批-同意
const approvalAgreeHandler = () => {
  apprDial.value.initDialog('agree', examineInfo.value.id, examineInfo.value.taskId, '')
}

// 流程审批-拒绝
const approvalRefuseHandler = () => {
  apprDial.value.initDialog('refuse', examineInfo.value.id, examineInfo.value.taskId, '')
}

// 取消（撤回审批单）
const revokeClickedHandler = () => {
  apprDial.value.initDialog('revoke', examineInfo.value.id, examineInfo.value.taskId, examineInfo.value.processId)
}

// 删除（只有已取消的可以在详情中删除）
const deleteClickedHandler = () => {
  ElMessageBox.confirm(
    `确认删除审批表 ${examineInfo.value.formNo} 吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteExamineRevoked({ id: examineInfo.value.id, taskId: examineInfo.value.taskId }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`审批表 ${examineInfo.value.formNo} 删除成功`)
        resetForm()
      }
      else {
        ElMessage.error(`审批表 ${examineInfo.value.formNo} 删除失败：${res.message}`)
      }
    })
  })
}

// 流程操作之后刷新
const approvalSuccessHandler = (type: string) => {
  if (type === 'agree' || type === 'refuse') {
    flowButtsVisable.value = false
  }
  else if (type === 'revoke') {
    cancelButtVisable.value = false
  }
}

const getLabCodeDict = async () => {
  await getDictByCode('bizLabCode').then((res) => {
    if (res.code === 200) {
      labCodeDict.value = res.data
    }
  })
}

const getGroupCodeDict = async () => {
  await getDictByCode('bizGroupCode').then((res) => {
    if (res.code === 200) {
      groupCodeDict.value = res.data
    }
  })
}

const getMethodTypeDict = async () => {
  await getDictByCode('bizMeasureMethodType').then((res) => {
    if (res.code === 200) {
      methodTypeDict.value = res.data
    }
  })
}

const initDict = () => {
  getLabCodeDict()
  getGroupCodeDict()
  getMethodTypeDict()
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''
  status.value = params.status !== undefined ? params.status : ''

  // 默认显示第一个tab内容
  current.value = radioItems.value[0].value
  currentLabel.value = radioItems.value[0].name

  switch (params.type) {
    case 'create' :
      title.value = '要求、委托书及合同评审表（新增）'
      saveButtVisable.value = true
      submitButtVisable.value = true

      sessionStorage.removeItem('examineInfo')
      examineInfo.value.createUserId = userInfo.id
      examineInfo.value.createUserName = userInfo.name
      examineInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')

      keyFieldsDisable.value = false

      break
    case 'update':
      title.value = '要求、委托书及合同评审表（编辑）'

      examineInfo.value = JSON.parse(sessionStorage.getItem('examineInfo')!)

      // 判断显示哪些流程操作按钮
      showOperationButtonByStatus()
      keyFieldsDisable.value = true

      break
    case 'detail':
      title.value = '要求、委托书及合同评审表'
      id.value = params.id

      examineInfo.value = JSON.parse(sessionStorage.getItem('examineInfo')!)

      // 查看详情时所有的操作按钮都隐藏
      showOperationButtonByStatus()
      keyFieldsDisable.value = true

      break
    default:
      title.value = ''
      keyFieldsDisable.value = true
      break
  }
}

// 监听 显示中文
watch(() => examineInfo.value.labCode, (newVal) => {
  if (labCodeDict.value.length > 0) {
    const targetList = labCodeDict.value.filter(item => item.value === newVal)
    if (targetList.length > 0) {
      examineInfo.value.labCodeName = targetList[0].name
    }
    else {
      examineInfo.value.labCodeName = ''
    }
  }
})

watch(() => examineInfo.value.groupCode, (newVal) => {
  if (groupCodeDict.value.length > 0) {
    const targetList = groupCodeDict.value.filter(item => item.value === newVal)
    if (targetList.length > 0) {
      examineInfo.value.groupCodeName = targetList[0].name
    }
    else {
      examineInfo.value.groupCodeName = ''
    }
  }
})

onMounted(() => {
  initDict()
  initDialog(route.query)
})
</script>

<template>
  <app-container>
    <el-form ref="examineRef" :model="examineInfo" :rules="examineRules" label-position="right" label-width="110px" border stripe>
      <detail-page :title="`${title}`">
        <template #btns>
          <el-button v-if="editButtVisable" type="primary" @click="editClickedHandler()">
            编辑
          </el-button>

          <template v-if="flowButtsVisable">
            <el-button type="primary" @click="approvalAgreeHandler">
              同意
            </el-button>
            <el-button type="danger" @click="approvalRefuseHandler">
              拒绝
            </el-button>
          </template>

          <el-button v-if="submitButtVisable" :disabled="id === ''" type="primary" @click="submitButtonHandler">
            提交
          </el-button>
          <el-button v-if="saveButtVisable" type="primary" @click="saveButtonHandler">
            保存
          </el-button>

          <el-button v-if="deleteButtVisable" type="danger" @click="deleteClickedHandler">
            删除
          </el-button>
          <el-button v-if="cancelButtVisable" type="info" @click="revokeClickedHandler">
            取消
          </el-button>

          <el-button type="info" @click="resetForm()">
            关闭
          </el-button>
        </template>

        <el-radio-group v-model="currentLabel" style="margin-bottom: 20px;" @change="radioChangeHandler">
          <el-radio-button v-for="item in radioItems" :key="item.value" :label="item.name" :disabled="id === ''" />
        </el-radio-group>

        <template v-if="current === 'examine-basic'">
          <el-row :gutter="24">
            <!-- 第一行 第一列 -->
            <el-col :span="6">
              <el-form-item label="实验室代码" prop="labCode">
                <el-select v-model="examineInfo.labCode" placeholder="请选择实验室代码" :disabled="keyFieldsDisable" style="width: 100%;">
                  <el-option v-for="dict in labCodeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
                </el-select>
                <el-input v-model="examineInfo.labCodeName" type="hidden" />
              </el-form-item>

              <el-form-item label="创建人">
                <el-input v-model="examineInfo.createUserName" :readonly="true" />
                <el-input v-model="examineInfo.createUserId" type="hidden" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="组别代码" prop="groupCode">
                <el-select v-model="examineInfo.groupCode" placeholder="请选择组别代码" :disabled="keyFieldsDisable" style="width: 100%;">
                  <el-option v-for="dict in groupCodeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
                </el-select>
                <el-input v-model="examineInfo.groupCodeName" type="hidden" />
              </el-form-item>

              <el-form-item label="创建时间">
                <el-input v-model="examineInfo.createTime" :readonly="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="评审表编号">
                <el-input v-model="examineInfo.formNo" placeholder="评审表编号，保存后自动生成" :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="评审表名称">
                <el-input v-model="examineInfo.formName" :readonly="true" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-input v-model="examineInfo.customerContent" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.measureItem" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.otherRequire" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.equipmentName" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.performanceIndex" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.measureStatus" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.numberOfPeople" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.staffCert" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.measureMethodName" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.measureMethodType" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.measureMethodControlled" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.measureMethodConfirm" type="hidden" />
            </el-col>
            <el-col :span="6">
              <el-input v-model="examineInfo.remark" type="hidden" />
            </el-col>
          </el-row>
        </template>
      </detail-page>

      <template v-if="current === 'examine-basic'">
        <el-form :model="examineInfo" :rules="examineRules" label-position="top">
          <detail-block title="委托方要求">
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="委托方信息（名称、地址、联系人、联系电话等）" prop="customerContent">
                  <el-input v-model="examineInfo.customerContent" placeholder="请填写委托方信息" type="textarea" rows="5" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="测试、校准或检定项目" prop="measureItem">
                  <el-input v-model="examineInfo.measureItem" placeholder="请填写测试、校准或检定项目" type="textarea" rows="5" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="其他要求（完成时限、证书报告出具、计量标识张贴等）" prop="otherRequire">
                  <el-input v-model="examineInfo.otherRequire" placeholder="请填写其他要求" type="textarea" rows="5" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>
          </detail-block>
        </el-form>

        <el-form :model="examineInfo" :rules="examineRules" label-position="right" label-width="250">
          <detail-block :title="`本站能力 （实验室代码：${examineInfo.labCode}）`">
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="测试、校准或检定设备名称" prop="equipmentName">
                  <el-input v-model="examineInfo.equipmentName" placeholder="请填写测试、校准或检定设备名称" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="测试、校准或检定设备性能指标" prop="performanceIndex">
                  <el-input v-model="examineInfo.performanceIndex" placeholder="请填写测试、校准或检定设备性能指标" type="textarea" rows="5" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="测试、校准或检定设备校准状态" prop="measureStatus">
                  <el-input v-model="examineInfo.measureStatus" placeholder="请填写测试、校准或检定设备校准状态" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="测试、校准或检定人员人数" prop="numberOfPeople">
                  <el-input-number v-model="examineInfo.numberOfPeople" :step="1" :precision="0" :min="0" :clearable="true" controls-position="right" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="测试、校准或检定人员持证情况" prop="staffCert">
                  <el-input v-model="examineInfo.staffCert" placeholder="请填写测试、校准或检定人员持证情况" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>
          </detail-block>
        </el-form>

        <el-form :model="examineInfo" :rules="examineRules" label-position="right" label-width="250">
          <detail-block title="测试、校准或检定方法">
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="测试、校准或检定方法名称" prop="measureMethodName">
                  <el-input v-model="examineInfo.measureMethodName" placeholder="请填写测试、校准或检定方法名称" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="测试、校准或检定方法类型" prop="measureMethodType">
                  <el-radio-group v-model="examineInfo.measureMethodType" :clearable="true" :disabled="type === 'detail'">
                    <el-radio v-for="dict in methodTypeDict" :key="dict.id" :label="dict.value">
                      {{ dict.name }}
                    </el-radio>
                  </el-radio-group>
                  <el-input v-model="examineInfo.measureMethodTypeName" type="hidden" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="测试、校准或检定方法受控" prop="measureMethodControlled">
                  <el-radio-group v-model="examineInfo.measureMethodControlled" :clearable="true" :disabled="type === 'detail'">
                    <el-radio v-for="dict in yesOrNoDict" :key="dict.id" :label="dict.value">
                      {{ dict.name }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="方法是否确认" prop="measureMethodConfirm">
                  <el-radio-group v-model="examineInfo.measureMethodConfirm" :clearable="true" :disabled="type === 'detail'">
                    <el-radio v-for="dict in yesOrNoDict" :key="dict.id" :label="dict.value">
                      {{ dict.name }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </detail-block>
        </el-form>

        <el-form :model="examineInfo" :rules="examineRules" label-position="right" label-width="110">
          <detail-block title="">
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="其他事项">
                  <el-input v-model="examineInfo.remark" placeholder="请填写其他事项" :clearable="true" :disabled="type === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>
          </detail-block>
        </el-form>
      </template>
    </el-form>

    <examine-approval-dialog ref="apprDial" @on-success="approvalSuccessHandler" />

    <template v-if="current === 'examine-approval'">
      <detail-page title="审批详情">
        审批详情
      </detail-page>
    </template>
  </app-container>
</template>
