<!-- 委托方详情编辑 -->
<script name="CustomerInfoDetail" lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import ApprovalDialog from '../../common/approvalDialog.vue'
import CustomerInfoBasic from './basic.vue'
import CustomerInfoBasicForEdit from './basicForEdit.vue'
import type { ICustomerInfo } from './customer-info'
import CustomerInfoStaff from './staff.vue'
import CustomerInfoOrder from './order.vue'
import CustomerInfoReport from './report.vue'
import { draftDelete, refuseApproval, revokeApproval } from '@/api/resource/customer'
import ApprovalRecordTable from '@/components/ApprovalRecord/ApprovalRecordTable.vue'

// 变量
// 从路由中传过来的参数
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: 'customer-basic' },
  { name: '委托方人员', value: 'customer-staff' },
  { name: '任务单信息', value: 'customer-order' },
  { name: '证书报告', value: 'customer-report' },
  { name: '审批详情', value: 'customer-approval' },
])

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

// 子组件
const apprDial = ref()
const refCustomerBasic = ref()
const refCustomerBasic4Edit = ref() // 可编辑的详情组件
const refCustomerStaff = ref()
const refCustomerOrder = ref()

const customerInfo = ref<ICustomerInfo>({
  id: '',
  customerNo: '',
  customerName: '',
  deptId: '',
  customerLocation: '',
  processId: '',
  taskId: '',
})

// 是否显示相关按钮
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('customerInfo') // 返回列表时 将缓存中的数据删除
  router.go(-1)
}

// 保存
const saveDraft = () => {
  if (current.value === 'customer-basic') {
    refCustomerBasic4Edit.value.saveBasicForm()
  }
  else if (current.value === 'customer-staff') {
    refCustomerStaff.value.addCustomerStaffRecords()
  }
  else {
    ElMessage.warning(`${currentLabel.value} 无需保存`)
  }
}

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

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

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

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

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

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

// 取消流程
const revokeClickedHandler = () => {
  apprDial.value.initDialog('revoke', customerInfo.value.id, customerInfo.value.taskId, customerInfo.value.processId)
}

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

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

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

    cancelButtVisable.value = false
  })
}

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

    flowButtsVisable.value = false
  })
}

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

  status.value = '1'
}

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

  type.value = 'detail'
  title.value = '委托方名录（详情）'
  hideAllOpterationButtons()
}

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

      // 新建时可以修改委托方名称
      refCustomerBasic4Edit.value.setFieldsDisable(false)

      break
    case 'update':
      title.value = '委托方名录（编辑）'

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

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

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

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

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

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

onMounted(() => {
  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>

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

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

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

      <customer-info-staff
        v-show="current === 'customer-staff'"
        ref="refCustomerStaff"
        :operation="type"
        :customer-id="customerInfo.id"
      />

      <customer-info-order v-show="current === 'customer-order'" ref="refCustomerOrder" :customer-id="customerInfo.deptId" />

      <customer-info-report v-show="current === 'customer-report'" ref="refCustomerReport" />

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