<!-- 印章使用登记详情 -->
<script name="SealNoteDetail" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { ISealInfo } from '../list/seal-info'
import type { ISealNoteInfo } from './seal-note'
import NoteApprovalDialog from './noteApprovalDialog.vue'
import FilterSeal from './filterSealNote.vue'
import useUserStore from '@/store/modules/user'
import { deleteSealNoteRevoked, draftUpdateSealNote, failUpdateNote, saveSealNote, submitSealNote } from '@/api/resource/seal'

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

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

const flowFormId = 'zyglyzsydj' // 资源管理 - 印章使用登记

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

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

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

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

const sealNoteRules = ref({
  sealNo: [{ required: true, message: '印章编号不能为空，请选择', trigger: ['change', 'blur'] }],
  applyReason: [{ 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 sealNoteInfo = ref<ISealNoteInfo>({
  id: '',
  noteFormNo: '',
  noteFormName: '印章使用登记',
  applyDeptId: '',
  applyDeptName: '',
  applyTime: '',
  applyReason: '',
  applyUserId: '',
  applyUserName: '',
  sealId: '',
  sealNo: '',
  sealName: '',
  sealType: '',
  sealTypeName: '',
  approverId: '',
  approverName: '',
  createUserId: '',
  createUserName: '',
  taskId: '',
  processId: '',
  approvalStatus: '',
  remark: '',
})

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

// 保存至草稿箱
const saveSealNoteInfo = () => {
  sealNoteInfo.value.applyTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss') // 申请时间改为提交时间
  saveSealNote(sealNoteInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      // 设置返回的使用登记表编号
      sealNoteInfo.value.noteFormNo = res.data.noteFormNo
      sealNoteInfo.value.id = res.data.id
      id.value = res.data.id

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

// 编辑草稿箱（不走流程审批）
const updateSealNoteInfo = () => {
  draftUpdateSealNote(sealNoteInfo.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 (!sealNoteRef) { return }

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

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

          type.value = 'detail'
          hideAllOpterationButtons()
        }
        else {
          ElMessage.error(`印章使用登记表 ${sealNoteInfo.value.noteFormNo} 提交失败：${res.message}`)
        }
      })
    })
  }
  else {
    // 之前已经在流程中的表单 保存提交
    await sealNoteRef.value.validate((valid: boolean) => {
      if (valid === true) {
        failUpdateNote(sealNoteInfo.value).then((res) => {
          if (res.code === 200) {
          // 提示保存成功
            ElMessage.success(`印章使用登记表 ${sealNoteInfo.value.noteFormNo} 提交成功`)

            type.value = 'detail'
            hideAllOpterationButtons()
          }
          else {
          // 提示失败信息
            ElMessage.error(`印章使用登记表 ${sealNoteInfo.value.noteFormNo} 提交失败：${res.message}`)
          }
        })
      }
    })
  }
}

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

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

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

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

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

// 显示筛选委托方名录的弹窗
const showFilterSeal = () => {
  refSealFilter.value.showOrHideFilterDialog(true)
}

// 选择委托方名录
const sealSelectedHandler = (row: ISealInfo) => {
  refSealFilter.value.showOrHideFilterDialog(false)

  sealNoteInfo.value.sealId = row.id
  sealNoteInfo.value.sealNo = row.sealNo
  sealNoteInfo.value.sealName = row.sealName
  sealNoteInfo.value.sealTypeName = row.sealTypeName
}

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('sealNoteInfo')
      sealNoteInfo.value.createUserId = userInfo.id
      sealNoteInfo.value.createUserName = userInfo.name
      sealNoteInfo.value.applyUserId = userInfo.id
      sealNoteInfo.value.applyUserName = userInfo.name
      sealNoteInfo.value.applyDeptId = userInfo.deptId
      sealNoteInfo.value.applyDeptName = userInfo.deptName
      sealNoteInfo.value.applyTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')

      keyFieldsDisable.value = false

      break
    case 'update':
      title.value = '印章使用登记表（编辑）'

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

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

      break
    case 'detail':
      title.value = '印章使用登记表'
      id.value = params.id

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

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

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

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

<template>
  <app-container>
    <el-form ref="sealNoteRef" :model="sealNoteInfo" :rules="sealNoteRules" 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 === 'sealNote-basic'">
          <el-row :gutter="24">
            <!-- 第一行 第一列 -->
            <el-col :span="6">
              <el-form-item label="登记表编号">
                <el-input v-model="sealNoteInfo.noteFormNo" placeholder="登记表编号，保存后自动生成" :disabled="true" />
              </el-form-item>

              <el-form-item label="申请时间">
                <el-input v-model="sealNoteInfo.applyTime" :readonly="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="登记表名称">
                <el-input v-model="sealNoteInfo.noteFormName" :disabled="true" />
              </el-form-item>

              <el-form-item label="印章编号" prop="sealNo">
                <el-input v-model="sealNoteInfo.sealNo" :readonly="true" :disabled="type === 'detail'" @click="showFilterSeal" />
                <el-input v-model="sealNoteInfo.sealId" type="hidden" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="申请部门">
                <el-input v-model="sealNoteInfo.applyDeptName" :readonly="true" :disabled="type === 'detail'" />
                <el-input v-model="sealNoteInfo.applyDeptId" type="hidden" />
              </el-form-item>

              <el-form-item label="印章名称">
                <el-input v-model="sealNoteInfo.sealName" :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="申请人">
                <el-input v-model="sealNoteInfo.applyUserName" :disabled="type === 'detail'" />
              </el-form-item>

              <el-form-item label="印章类型">
                <el-input v-model="sealNoteInfo.sealTypeName" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="18">
              <el-form-item label="申请原因" prop="applyReason">
                <el-input v-model="sealNoteInfo.applyReason" :disabled="type === 'detail'" />
              </el-form-item>
            </el-col>

            <el-col :span="18">
              <el-form-item label="备注">
                <el-input v-model="sealNoteInfo.remark" :disabled="type === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </detail-page>
    </el-form>

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

    <filter-seal ref="refSealFilter" @record-selected="sealSelectedHandler" />

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