<!-- 授权代理委托书详情 -->
<script name="OrderDetail" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IOrderInfo } from './person-order'
import ApprovalDialog from '@/views/resource/common/approvalDialog.vue'
import { getDictByCode } from '@/api/system/dict'
import type { IDictType } from '@/commonInterface/resource-interface'
import useUserStore from '@/store/modules/user'
import { failUpdateOrder, orderApprDelete, refuseApproval, revokeApproval, saveToDraft, submitToFlow, updateInDraft } from '@/api/resource/order'

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

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

const flowFormId = 'zyglsqwts' // 资源管理 - 授权（代理）委托书

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

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

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

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

const orderFormRules = ref({
  labCode: [{ required: true, message: '实验室代码不能为空，请选择', trigger: ['change', 'blur'] }],
  groupCode: [{ required: true, message: '组别代码不能为空，请选择', trigger: ['change', 'blur'] }],
}) // 表单验证规则
const orderRules = ref({
  authorizePersonName: [{ required: true, message: '授权人名不能为空', trigger: 'blur' }],
  authorizeLocation: [{ required: true, message: '授权地点不能为空', trigger: 'blur' }],
  originalPerson: [{ required: true, message: '岗位原负责人不能为空', trigger: 'blur' }],
  authorizeDuty: [{ required: true, message: '授权职责不能为空', trigger: 'blur' }],
  orderDate: [{ required: true, message: '授权开始日期不能为空，请选择', trigger: 'blur' }],
  validDate: [{ 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 orderInfo = ref<IOrderInfo>({
  approvalStatus: '',
  approvalStatusName: '',
  authorizeDuty: '',
  authorizeLocation: '',
  authorizePersonName: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  decisionItem: '',
  groupCode: '',
  groupCodeName: '',
  id: '',
  labCode: '',
  labCodeName: '',
  orderDate: '',
  orderName: '计量测试站授权（代理）委托书',
  orderNo: '',
  originalPerson: '',
  processId: '',
  taskId: '',
  updateTime: '',
  validDate: '',
})

// 字典值
const labCodeDict = ref<IDictType[]>([])
const groupCodeDict = ref<IDictType[]>([])

// 逻辑
// 详情页的各个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('orderInfo') // 返回列表时 将缓存中的数据删除
  router.go(-1)
}

// 保存至草稿箱
const saveOrderInfo = () => {
  orderInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss') // 创建时间改为提交时间
  saveToDraft(orderInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      // 设置返回的委托方id和委托方编号
      orderInfo.value.orderNo = res.data.orderNo
      orderInfo.value.id = res.data.id
      id.value = res.data.id

      keyFieldsDisable.value = true
      type.value = 'update'
      status.value = '1' // 保存成功后进入草稿箱 为了不显示审批详情
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 编辑草稿箱（不走流程审批）
const updateOrderInfo = () => {
  updateInDraft(orderInfo.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 (!orderFormRef && !orderRef) { return }

  let orderValid

  // 先对表单一进行校验
  await orderFormRef.value.validate((valid: boolean) => {
    if (valid === false) {
      orderValid = false
    }
    else {
      orderValid = true
    }
  })

  if (orderValid === false) { return }

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

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

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

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

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

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

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

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

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

// 取消
const orderRevokeHandler = (param: any) => {
  revokeApproval(param).then((res) => {
    if (res.code === 200) {
      ElMessage.success('流程取消成功')
    }
    else {
      ElMessage.error(`流程取消失败：${res.message}`)
    }
    // 关闭弹窗
    apprDial.value.handleClose()

    cancelButtVisable.value = false
  })
}

// 拒绝
const orderRefuseHandler = (param: any) => {
  refuseApproval(param).then((res) => {
    if (res.code === 200) {
      ElMessage.success('拒绝审批完成')
    }
    else {
      ElMessage.error(`拒绝审批失败：${res.message}`)
    }
    // 关闭弹窗
    apprDial.value.handleClose()

    flowButtsVisable.value = false
  })
}

const getLabCodeDict = async () => {
  // 先从缓存中获取
  if (sessionStorage.getItem('bizLabCode') === null || sessionStorage.getItem('bizLabCode') === undefined) {
    // 缓存中没有则调用接口查询
    await getDictByCode('bizLabCode').then((res) => {
      if (res.code === 200) {
        labCodeDict.value = res.data
        sessionStorage.setItem('bizLabCode', JSON.stringify(labCodeDict.value)) // 放到缓存中
      }
    })
  }
  else {
    labCodeDict.value = JSON.parse(sessionStorage.getItem('bizLabCode')!)
  }
}

const getGroupCodeDict = async () => {
  // 先从缓存中获取
  if (sessionStorage.getItem('bizGroupCode') === null || sessionStorage.getItem('bizGroupCode') === undefined) {
    // 缓存中没有则调用接口查询
    await getDictByCode('bizGroupCode').then((res) => {
      if (res.code === 200) {
        groupCodeDict.value = res.data
        sessionStorage.setItem('bizGroupCode', JSON.stringify(groupCodeDict.value)) // 放到缓存中
      }
    })
  }
  else {
    groupCodeDict.value = JSON.parse(sessionStorage.getItem('bizGroupCode')!)
  }
}

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

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('orderInfo')
      orderInfo.value.createUserId = userInfo.id
      orderInfo.value.createUserName = userInfo.name
      orderInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')

      keyFieldsDisable.value = false

      break
    case 'update':
      title.value = '计量测试站授权（代理）委托书（编辑）'

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

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

      break
    case 'detail':
      title.value = '计量测试站授权（代理）委托书'
      id.value = params.id

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

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

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

// 监听 显示中文
watch(() => orderInfo.value.labCode, (newVal) => {
  labCodeDict.value = JSON.parse(sessionStorage.getItem('bizLabCode')!)

  if (labCodeDict.value.length > 0) {
    const targetList = labCodeDict.value.filter(item => item.value === newVal)
    if (targetList.length > 0) {
      orderInfo.value.labCodeName = targetList[0].name
    }
    else {
      orderInfo.value.labCodeName = ''
    }
  }
})

watch(() => orderInfo.value.groupCode, (newVal) => {
  groupCodeDict.value = JSON.parse(sessionStorage.getItem('bizGroupCode')!)

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

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

<template>
  <app-container>
    <el-form ref="orderFormRef" :model="orderInfo" :rules="orderFormRules" 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 === 'order-basic'">
          <el-row :gutter="24">
            <!-- 第一行 第一列 -->
            <el-col :span="6">
              <el-form-item label="实验室代码" prop="labCode">
                <el-select v-model="orderInfo.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="orderInfo.labCodeName" type="hidden" />
              </el-form-item>
              <el-form-item label="创建人">
                <el-input v-model="orderInfo.createUserId" type="hidden" />
                <el-input v-model="orderInfo.createUserName" :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="组别代码" prop="groupCode">
                <el-select v-model="orderInfo.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="orderInfo.groupCodeName" type="hidden" />
              </el-form-item>
              <el-form-item label="创建时间">
                <el-input v-model="orderInfo.createTime" :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="委托书编号">
                <el-input v-model="orderInfo.orderNo" placeholder="委托方编号，保存后自动生成" :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="委托书名称">
                <el-input v-model="orderInfo.orderName" :readonly="true" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </detail-page>
    </el-form>

    <el-form ref="orderRef" :model="orderInfo" :rules="orderRules" style="display: flex; white-space: nowrap; flex-wrap: wrap;">
      <template v-if="current === 'order-basic'">
        <el-input v-model="orderInfo.labCode" type="hidden" />
        <el-input v-model="orderInfo.labCodeName" type="hidden" />
        <el-input v-model="orderInfo.groupCode" type="hidden" />
        <el-input v-model="orderInfo.groupCodeName" type="hidden" />
        <el-input v-model="orderInfo.orderNo" type="hidden" />
        <el-input v-model="orderInfo.orderName" type="hidden" />
        <el-input v-model="orderInfo.createUserId" type="hidden" />
        <el-input v-model="orderInfo.createUserName" type="hidden" />
        <el-input v-model="orderInfo.createTime" type="hidden" />
        <detail-block style="margin-top: 20px; width: 100%; font-size: 1.5rem;" title="">
          <el-row :gutter="24">
            <el-col :span="24">
              <div class="order-title">
                计量测试站授权（代理）委托书
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="24" style="margin-top: 30px; padding: 0 8rem;">
            <span class="order-text">根据本站工作需要，现授权</span>

            <el-form-item label="" prop="authorizePersonName">
              <el-input
                v-model="orderInfo.authorizePersonName" placeholder="授权人名"
                :clearable="true" :disabled="type === 'detail'"
                size="large" style="width: 300px; margin: 0 10px;"
              />
            </el-form-item>

            <span class="order-text">（在</span>

            <el-form-item label="" prop="authorizeLocation">
              <el-input
                v-model="orderInfo.authorizeLocation" placeholder="授权地点：海口/西昌"
                :clearable="true" :disabled="type === 'detail'"
                size="large" style="width: 300px; margin: 0 10px;"
              />
            </el-form-item>

            <span class="order-text">）履行（代行）</span>
          </el-row>

          <el-row :gutter="24" style="margin-top: 30px; padding: 0 6rem;">
            <el-form-item label="" prop="authorizeDuty">
              <el-input
                v-model="orderInfo.authorizeDuty" placeholder="授权履行职责"
                :clearable="true" :disabled="type === 'detail'"
                size="large" style="width: 300px; margin-right: 10px;"
              />
            </el-form-item>

            <span class="order-text">职责。本委托书自</span>

            <el-form-item label="" prop="orderDate">
              <el-date-picker
                v-model="orderInfo.orderDate" type="date"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择授权开始时间" :clearable="true" :disabled="type === 'detail'"
                style="width: 300px; margin: 0 10px;" size="large"
              />
            </el-form-item>

            <span class="order-text">至（</span>

            <el-form-item label="" prop="originalPerson">
              <el-input
                v-model="orderInfo.originalPerson" placeholder="岗位原负责人"
                :clearable="true" :disabled="type === 'detail'"
                size="large" style="width: 300px; margin: 0 10px;"
              />
            </el-form-item>

            <span class="order-text">返回</span>
          </el-row>

          <el-row :gutter="24" style="margin-top: 30px; padding: 0 6rem;">
            <span class="order-text">岗位前）</span>

            <el-form-item label="" prop="validDate">
              <el-date-picker
                v-model="orderInfo.validDate" type="date"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择授权结束时间" :clearable="true" :disabled="type === 'detail'"
                style="width: 300px; margin: 0 10px;" size="large"
              />
            </el-form-item>

            <span class="order-text">有效。</span>
          </el-row>

          <el-row :gutter="24" style="margin-top: 50px;">
            <el-col :span="6" :offset="12">
              <div class="order-text">
                中国西昌卫星发射中心计量测试站
              </div>
              <div class="order-text" style="text-align: center; margin: 20px;">
                计量测试站主任（签字）
              </div>
            </el-col>
          </el-row>
        </detail-block>
      </template>
    </el-form>

    <approval-dialog
      ref="apprDial"
      @on-success="approvalSuccessHandler"
      @on-refuse="orderRefuseHandler"
      @on-revoke="orderRevokeHandler"
    />

    <template v-if="current === 'order-approval' && status !== '1'">
      <approval-record-table :process-id="orderInfo.processId" />
    </template>
  </app-container>
</template>

<style scoped>
.order-title {
  text-align: center;
  font-weight: bold;
  font-size: 2rem;
  font-family: SimSun, STSong;
  margin-bottom: 50px;
}

.order-text {
  font-family: SimSun, STSong;
  line-height: 40px;
}
</style>
