<!-- 合格供方名录详情 -->
<script name="SupplierDetail" lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import type { IDictType, ISupplierInfo } from './supplier-interface'
import SupplierApprovalDialog from './supplierApprovalDialog.vue'
import SupplierInfoBasic from './basic.vue'
import SupplierInfoBasicForEdit from './basicForEdit.vue'
import SupplierInfoStaff from './staff.vue'
import { getDictByCode } from '@/api/system/dict'
import { draftDelete } from '@/api/resource/supplier'

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

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

const radioItems = ref([
  { name: '基本信息', value: 'supplier-basic' },
  { name: '供方人员', value: 'supplier-staff' },
  { name: '业务能力', value: 'supplier-ability' },
  { name: '关联评价表', value: 'supplier-evaluate' },
])
const current = ref('')
const currentLabel = ref('')

// 子组件
const approvalDialog = ref()
const refSupplierBasic = ref()
const refSupplierBasic4Edit = ref() // 可编辑的详情组件
const refSupplierStaff = ref()

// 字典值
const supplierTypeDict = ref<Array<IDictType>>([])

// 是否显示相关按钮
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) // 是否显示 编辑 按钮

// 逻辑
// 详情页的各个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 '0':
      // 全部（名录）：保存按钮可见
      if (type.value === 'update') {
        saveButtVisable.value = true
      }
      else {
        saveButtVisable.value = false
      }
      break

    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('supplierInfo') // 返回列表时 将缓存中的数据删除
  router.go(-1)
}

// 保存
const saveDraft = () => {
  if (current.value === 'supplier-basic') {
    refSupplierBasic4Edit.value.saveBasicForm()
  }
  else if (current.value === 'supplier-staff') {
    refSupplierStaff.value.addSupplierStaffRecords()
  }
  else {
    ElMessage.warning(`${currentLabel.value} 无需保存`)
  }
}

// 提交
const submitFlow = () => {
  const supplierInfo: ISupplierInfo = JSON.parse(sessionStorage.getItem('supplierInfo')!)
  if (supplierInfo === null || supplierInfo.processId === undefined || supplierInfo.processId === '') {
    // 流程id为空 表示还未进入流程中 直接提交
    refSupplierBasic4Edit.value.submitBasicForm()
  }
  else {
    // 之前已经在流程中的表单 先保存 再提交
    refSupplierBasic4Edit.value.failUpdateSubmitBasicForm()
  }
}

// 编辑按钮点击事件处理函数
const editClickedHandler = () => {
  type.value = 'update'
  title.value = '供方名录（编辑）'

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

  // 调用子组件的方法
  // 切换了组件所有需要初始化数据
  refSupplierBasic4Edit.value.getSupplierBasicInCache()
}

// 流程审批-拒绝
const approvalRefuseHandler = () => {
  const supplierInfo: ISupplierInfo = JSON.parse(sessionStorage.getItem('supplierInfo')!)
  approvalDialog.value.initDialog('refuse', supplierInfo.id, supplierInfo.taskId, '')
}

// 流程审批-同意
const approvalAgreeHandler = () => {
  const supplierInfo: ISupplierInfo = JSON.parse(sessionStorage.getItem('supplierInfo')!)
  approvalDialog.value.initDialog('agree', supplierInfo.id, supplierInfo.taskId, '')
}

// 取消流程
const revokeClickedHandler = () => {
  const supplierInfo: ISupplierInfo = JSON.parse(sessionStorage.getItem('supplierInfo')!)
  approvalDialog.value.initDialog('revoke', supplierInfo.id, supplierInfo.taskId, supplierInfo.processId)
}

// 删除审批单
const deleteClickedHandler = () => {
  const supplierInfo: ISupplierInfo = JSON.parse(sessionStorage.getItem('supplierInfo')!)
  ElMessageBox.confirm(`是否删除审批单 ${supplierInfo.supplierNo}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    draftDelete({ id: id.value }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`审批单 ${supplierInfo.supplierNo} 删除成功`)
        resetForm()
      }
      else {
        ElMessage.error(`审批单 ${supplierInfo.supplierNo} 删除失败: ${res.message}`)
      }
    })
  })
}

// 流程审批（同意、拒绝、取消）结束后的操作 将按钮都隐藏（本身就不能编辑了）
const approvalSuccessHandler = (type: string) => {
  if (type === 'agree' || type === 'refuse') {
    flowButtsVisable.value = false
  }
  else if (type === 'revoke') {
    cancelButtVisable.value = false
  }
}

// 新建时保存后的处理 获取返回的id
const saveDraftHandler = (idRet: string) => {
  id.value = idRet
}

// 提交后的处理 显示详情页且不能编辑
const commitSuccessHandler = (supplierInfo: ISupplierInfo) => {
  // 在详情页显示
  refSupplierBasic.value.initDialog(supplierInfo)

  type.value = 'detail'
  title.value = '合格供方名录（详情）'
  hideAllOpterationButtons()
}

// 获取供应商类型字典值
const getSupplierTypeDict = () => {
  if (sessionStorage.getItem('bizSupplierType') === null) {
    getDictByCode('bizSupplierType').then((res) => {
      if (res.code === 200) {
        supplierTypeDict.value = res.data
        sessionStorage.setItem('bizSupplierType', JSON.stringify(supplierTypeDict.value))
      }
    })
  }
  else {
    supplierTypeDict.value = JSON.parse(sessionStorage.getItem('bizSupplierType')!)
  }
}

const getDict = async () => {
  getSupplierTypeDict()
}

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('supplierInfo')

      // 新建时可以修改供方名称
      refSupplierBasic4Edit.value.setFieldsDisable(false)

      break
    case 'update':
      title.value = '合格供方名录（编辑）'

      // 判断显示哪些流程操作按钮
      showOperationButtonByStatus()

      // 调用子组件的方法
      refSupplierBasic4Edit.value.getSupplierBasicInCache()
      if (status.value === '0') {
        // 全部状态下的编辑 供方名称不能修改
        refSupplierBasic4Edit.value.setFieldsDisable(true)
      }
      else {
        refSupplierBasic4Edit.value.setFieldsDisable(false)
      }
      break
    case 'detail':
      title.value = '合格供方名录（详情）'
      id.value = params.id

      // 查看详情时所有的操作按钮都隐藏
      showOperationButtonByStatus()

      // 调用子组件的方法
      refSupplierBasic.value.getSupplierBasicInCache()
      break
    default:
      title.value = ''
      break
  }
}

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

<template>
  <app-container>
    <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="submitFlow">
          提交
        </el-button>
        <el-button v-if="saveButtVisable" type="primary" @click="saveDraft">
          保存
        </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>

      <supplier-approval-dialog ref="approvalDialog" @on-success="approvalSuccessHandler" />

      <supplier-info-basic
        v-show="current === 'supplier-basic' && type === 'detail'" ref="refSupplierBasic"
        :operation="type"
      />

      <supplier-info-basic-for-edit
        v-show="current === 'supplier-basic' && type === 'update' || type === 'create'" ref="refSupplierBasic4Edit"
        :operation="type"
        @after-save-draft="saveDraftHandler"
        @commit-success="commitSuccessHandler"
      />

      <supplier-info-staff
        v-show="current === 'supplier-staff'" ref="refSupplierStaff"
        :operation="type"
        :supplier-id="id"
      />
    </detail-page>
  </app-container>
</template>
