<!-- 委托方意见登记表详情 -->
<script name="FileChangeFormDetail" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IFileChangeForm, IFileChangeInfo } from './change-interface'
import FileSelectDialog from './fileSelectDialog.vue'
import type { IDictType } from '@/commonInterface/resource-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import type { IFileInfo as ISysDocFileInfo } from '@/views/resource/system/sysDoc/sysDoc-interface'
import type { IFileInfo as IMethodFileInfo } from '@/views/resource/technology/method/method-interface'
import ApprovalDialog from '@/views/resource/common/approvalDialog.vue'
import ApprovalRecordTable from '@/components/ApprovalRecord/ApprovalRecordTable.vue'
import useUserStore from '@/store/modules/user'
import { getDictByCode } from '@/api/system/dict'
import { detailFileChangeForm, failUpdateChangeForm, refuseApproval, revokeApproval, revokeDelete, saveChangeForm, submitChangeForm, updateDraftChangeForm } from '@/api/resource/fileChange'

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

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

const flowFormId = 'zyglwjggsq' // 资源管理 - 文件变更申请单

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

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

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

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

const changeFormRules = ref({
  labCode: [{ required: true, message: '实验室代码不能为空，请选择', trigger: ['change', 'blur'] }],
  groupCode: [{ required: true, message: '组别代码不能为空，请选择', trigger: ['change', 'blur'] }],
  changeReason: [{ required: true, message: '更改原因不能为空', trigger: 'blur' }],
  changeContent: [{ 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 changeForm = ref<IFileChangeForm>({
  id: '',
  formNo: '',
  formName: '文件更改申请单',
  labCode: '',
  labCodeName: '',
  groupCode: '',
  groupCodeName: '',
  changeReason: '',
  changeContent: '',
  processId: '',
  taskId: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  fileList: [],
})
const fileColumns = ref<Array<TableColumn>>([
  { text: '文件类型', value: 'categoryName', align: 'center', width: '300' },
  { text: '文件编号', value: 'fileNo', align: 'center', width: '200' },
  { text: '文件名称', value: 'fileName', align: 'center' },
]) // 表头

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

const fileRecordSelected = ref<IFileChangeInfo[]>([])

// 逻辑
// 详情页的各个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 = () => {
  router.go(-1)
}

// 新增
const addEditableRow = () => {
  refFileSelect.value.showRecordDialog(true, '新增')
}

const delFileRecords = () => {
  if (fileRecordSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
    return
  }

  changeForm.value.fileList = changeForm.value.fileList.filter(item => fileRecordSelected.value.includes(item) === false)
}

const fileMultiSelect = (e: any) => {
  fileRecordSelected.value = e
}

// 根据id查询详情
const detailById = async (id: string) => {
  await detailFileChangeForm({ id }).then((res) => {
    if (res.code === 200) {
      changeForm.value = res.data
      changeForm.value.fileList = changeForm.value.fileList.map((item) => {
        return {
          ...item,
          categoryName: item.fileCategory.toString() === '1' ? '体系文件' : (item.fileCategory.toString() === '2' ? '现行测试标准检定方法' : ''),
        }
      })
    }
  })
}

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

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

// 编辑草稿箱（不走流程审批）
const updateFileChangeForm = () => {
  updateDraftChangeForm(changeForm.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 (!changeFormRef) { return }

  if (changeForm.value.fileList.length === 0) {
    ElMessage.error('文件列表不能为空，请选择文件')
    return
  }

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

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

          type.value = 'detail'
          hideAllOpterationButtons()
        }
        else {
          ElMessage.error(`文件更改申请单 ${changeForm.value.formNo} 提交失败：${res.message}`)
        }
      })
    })
  }
  else {
    // 之前已经在流程中的表单 保存提交
    await changeFormRef.value.validate((valid: boolean) => {
      if (valid === true) {
        failUpdateChangeForm(changeForm.value).then((res) => {
          if (res.code === 200) {
          // 提示保存成功
            ElMessage.success(`文件更改申请单 ${changeForm.value.formNo} 提交成功`)

            type.value = 'detail'
            hideAllOpterationButtons()
          }
          else {
          // 提示失败信息
            ElMessage.error(`文件更改申请单 ${changeForm.value.formNo} 提交失败：${res.message}`)
          }
        })
      }
    })
  }
}

// 选定文件返回
const appendFileToList = (rows: ISysDocFileInfo[] | IMethodFileInfo[], category: string) => {
  rows.forEach((row) => {
    const existList = changeForm.value.fileList.filter(file => file.fileId === row.id)
    if (existList.length === 0) {
      changeForm.value.fileList.push({
        id: '',
        fileId: row.id,
        fileNo: row.fileNo,
        fileName: row.fileName,
        fileCategory: category,
        categoryName: category === '1' ? '体系文件' : (category === '2' ? '现行测试标准检定方法' : ''),
      })
    }
  })
}

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

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

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

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

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

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

    cancelButtVisable.value = false
  })
}

// 拒绝
const refuseHandler = (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
      }
    })
  }
  else {
    labCodeDict.value = JSON.parse(sessionStorage.getItem('bizLabCode')!)
  }
}

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

const initDict = async () => {
  await getLabCodeDict()
  await 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

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

      keyFieldsDisable.value = false

      break
    case 'update':
      title.value = '文件更改申请单（编辑）'

      detailById(id.value)

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

      break
    case 'detail':
      title.value = '文件更改申请单'
      id.value = params.id

      detailById(id.value)

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

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

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

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

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

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

            <el-col :span="6">
              <el-form-item label="申请单名称">
                <el-input v-model="changeForm.formName" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </detail-page>

      <template v-if="current === 'change-form-basic'">
        <table-container title="文件列表">
          <template v-if="type !== 'detail'" #btns-right>
            <el-button type="primary" @click="addEditableRow">
              增加行
            </el-button>
            <el-button type="info" @click="delFileRecords">
              删除行
            </el-button>
          </template>

          <!-- 表格区域 -->
          <normal-table
            :data="changeForm.fileList" :columns="fileColumns"
            :pagination="false"
            :is-showmulti-select="type !== 'detail'"
            @multi-select="fileMultiSelect"
          >
            <template #preColumns>
              <el-table-column label="序号" width="55" align="center">
                <template #default="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
            </template>
          </normal-table>
        </table-container>

        <detail-block title="">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="更改原因" prop="changeReason">
                <el-input v-model="changeForm.changeReason" placeholder="请填写更改原因" type="textarea" rows="3" :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="changeContent">
                <el-input v-model="changeForm.changeContent" placeholder="请填写更改内容" type="textarea" rows="5" :clearable="true" :disabled="type === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
        </detail-block>
      </template>
    </el-form>

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

    <file-select-dialog ref="refFileSelect" @records-selected="appendFileToList" />

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