<script lang="ts" setup name="ApprovalDialog">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import useUserStore from '@/store/modules/user'
import { fetchApproval, submitApproval } from '@/api/approval'
import { changeWorkbenchApproveStatus } from '@/api/workbench/workbench'
import { getUserList } from '@/api/system/user'
import { addApprovalUser, updatePublishTime } from '@/api/system/process'
import { myExecutiveDone } from '@/api/business/schedule/task'
import { certificatePrintByProcess } from '@/api/business/lab/cert'
/**
 * 审批弹窗
 */
const props = defineProps({
  /**
   * 提示文字
   */
  title: {
    type: String,
    default: '审批操作',
  },
  // 流程最后一个节点的名字
  lastName: {
    type: String,
    required: true,
  },
  module: {
    type: String,
  },
})
const emit = defineEmits(['onSuccess'])
// 弹窗显示状态
const dialogVisible = ref(false)
const publishTime = ref('') // 发布时间
// 是否展示 下一节点审批节点 审批人
const isShowUser = ref(false)
// 默认表单
const defaultFormData = {
  type: '', // 审批类型
  taskId: '', // 任务id
  comments: '', // 备注
  user: '', // 当前用户
  approvalTime: '', // 当前时间
  userList: [] as any,
  processId: '',
}
// 弹窗类型 agree同意 refuse拒绝 reject驳回 revoke取消
const type = ref('agree')
// 表单数据对象
const formData = reactive({ ...defaultFormData })

// 保存按钮加载状态
const btnLoading = ref(false)

// agree同意 refuse拒绝 reject驳回 revoke取消
const userInfo = useUserStore()
const decisionItem = ref('')
const sampleId = ref('')
const orderId = ref('')

// ---------------表单提交--------------------------------
// 表单对象
const dataFormRef = ref<FormInstance>()
// 校验规则
const rules: FormRules = reactive({
  comments: [{ required: true, message: '审批结论必填', trigger: ['blur', 'change'] }],
  userList: [{ required: true, message: '批准人必选', trigger: ['blur', 'change'] }],
})
const dataId = ref()
const isInvalid = ref(false)
const measurePersonId = ref('') // 检定员id
/**
 * 初始化审批弹窗
 * @param type 审批类型
 * @param taskId  任务id
 * @param id
 * @param decisionItemParam 控制审批按钮
 * @param processId
 * @param sampleId 样品id
 * @param orderId 委托方id
 * @param invalid 是否替代原证书
 * @param measurePersonIdParam 检定员id
 */
function initDialog(
  type: string,
  taskId: string,
  id: string,
  decisionItemParam = '1',
  processId?: string,
  sampleIdParam = '',
  orderIdParam = '',
  invalid = false,
  measurePersonIdParam = '',
) {
  console.log('流程实例id--processId', processId)
  console.log('同意-样品id', sampleIdParam)
  console.log('同意-委托书id', orderIdParam)
  console.log('是否替代', invalid)
  console.log('检定员id', measurePersonIdParam)
  if (type === 'agree') { // 同意的时候判断是否显示选择下一个节点审批人
    isShowUser.value = true
    getApprovalRecord(processId!)
  }
  dataId.value = id
  decisionItem.value = `${decisionItemParam}`
  formData.type = type
  formData.taskId = taskId
  formData.user = userInfo.name
  formData.userList = []
  formData.approvalTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  formData.comments = ''
  formData.processId = processId!
  sampleId.value = sampleIdParam!
  orderId.value = orderIdParam!
  isInvalid.value = invalid
  measurePersonId.value = measurePersonIdParam
  dialogVisible.value = true
}
// 提交表单
function submitForm() {
  if (dataFormRef) {
    dataFormRef.value?.validate((valid: boolean) => {
      if (valid) {
        // if (formData.userList.includes(userInfo.id)) {
        //   ElMessage.warning('下一节点审批人不能含有当前用户')
        //   return
        // }
        btnLoading.value = true
        const handleApproval = async () => {
          await submitApproval(formData.type, { taskId: formData.taskId, comments: formData.comments })
          ElMessage.success('审批完成')
          btnLoading.value = false
          dialogVisible.value = false
          emit('onSuccess')
        }
        if (formData.type === 'agree') {
          if (isShowUser.value) {
            addApprovalUser({
              assignees: formData.userList,
              processInstanceId: formData.processId,
            }).then(() => {
              handleApproval().then(() => {
                certificatePrintByProcess(dataId.value)
              })
            })
          }
          else {
            handleApproval().then(async () => {
              if (publishTime.value !== '') {
                await updatePublishTime({
                  id: dataId.value,
                  issuanceDate: publishTime.value,
                }).then(() => {
                  console.log('更新发布时间完成')
                })
              }
              // 生成证书
              certificatePrintByProcess(dataId.value).then(() => {
                const params = {
                  orderId: orderId.value,
                  sampleId: sampleId.value,
                  measurePersonId: measurePersonId.value,
                }
                if (!isInvalid.value) {
                  // 自动检测完成
                  myExecutiveDone([params]).then(() => {
                    console.log('自动检测完成成功')
                  })
                }
              })
            })
          }
          // .then(() => {
          //   // ElMessage.success('审批完成')
          //   btnLoading.value = false
          //   dialogVisible.value = false
          //   emit('onSuccess')
          // })
        }
        else {
          handleApproval()
        }
        // 改变总工作台审批提醒的已处理状态
        if (sessionStorage.getItem('workbenchApproveParams')) {
          const row = JSON.parse(sessionStorage.getItem('workbenchApproveParams')!)
          changeWorkbenchApproveStatus({
            id: row.id,
            status: 1,
            businessId: row.businessId,
            decisionItem: Number(row.decisionItem),
            formId: row.formId,
            processId: row.processId,
            taskId: row.taskId,
          })
        }
        // if (formData.type) {
        //   submitApproval(formData.type, { taskId: formData.taskId, comments: formData.comments }).then((res) => {
        //     if (formData.type === 'agree') {
        //       certificatePrintByProcess(dataId.value).then(() => {
        //         ElMessage.success('审批完成')
        //         btnLoading.value = false
        //         dialogVisible.value = false
        //         emit('onSuccess')
        //       })
        //     }
        //     else {
        //       ElMessage.success('审批完成')
        //       btnLoading.value = false
        //       dialogVisible.value = false
        //       emit('onSuccess')
        //     }

        //     // 改变总工作台审批提醒的已处理状态
        //     if (sessionStorage.getItem('workbenchApproveParams')) {
        //       const row = JSON.parse(sessionStorage.getItem('workbenchApproveParams')!)
        //       changeWorkbenchApproveStatus({
        //         id: row.id,
        //         status: 1,
        //         businessId: row.businessId,
        //         decisionItem: Number(row.decisionItem),
        //         formId: row.formId,
        //         processId: row.processId,
        //         taskId: row.taskId,
        //       })
        //     }
        //   }).catch((_) => {
        //     btnLoading.value = false
        //   })
        // }
      }
    })
  }
}
// 关闭弹窗
function handleClose() {
  btnLoading.value = false
  dialogVisible.value = false
}
// 获取审批记录 根据当前节点判断显示 审批人选择
function getApprovalRecord(processId: string) {
  fetchApproval(processId).then((res) => {
    console.log(res.data, 'res')
    if (res.data.length) {
      const data = res.data[res.data.length - 1]
      if (data.length) {
        console.log('最后一个审批人名字', data[data.length - 1].taskName)
        console.log('config文件里面定义的最后一个审批人的名字', props.lastName)
        console.log('是否显示选择下一个节点审批人表单', !(data[data.length - 1].taskName === props.lastName))
        if (data[data.length - 1].taskName === props.lastName) {
          isShowUser.value = false
        }
      }
    }
  })
}

// 获取审批人
const userList = ref<any[]>([])
const fetchDict = () => {
  // getUserList({ offset: 1, limit: 99999 }).then((res) => {
  //   userList.value = res.data.rows
  // })
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    userList.value = res.data.rows
  })
}
fetchDict()
// ----------------------- 以下是暴露的方法内容 ----------------------------
defineExpose({ initDialog })
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="审批操作"
    width="800"
    :before-close="handleClose"
  >
    <el-form
      ref="dataFormRef"
      v-loading="btnLoading"
      label-position="left"
      label-width="85px"
      :model="formData"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="审批意见:">
            <el-radio-group v-model="formData.type" disabled>
              <el-radio label="agree" size="large">
                同意
              </el-radio>
              <el-radio v-if="decisionItem !== '3'" label="reject" size="large">
                驳回
              </el-radio>
              <el-radio v-if="decisionItem !== '2'" label="refuse" size="large">
                拒绝
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="审批结论:" prop="comments">
            <el-input
              v-model="formData.comments"
              :rows="4"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isShowUser && formData.type === 'agree'" :gutter="24">
        <el-col :span="24">
          <el-form-item label="批准人:" prop="userList">
            <el-select v-model="formData.userList" filterable multiple placeholder="批准人" style="width: 100%;">
              <el-option v-for="(item) in userList" :key="item.id" :label="item.name" :value="item.id">
                <span style="float: left;">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px;">{{ item.deptName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="7">
          <el-form-item label="审批人:">
            <el-input
              v-model="formData.user"
              placeholder="审批人"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审批时间:">
            <el-input
              v-model="formData.approvalTime"
              style="width: 100%;"
              placeholder="审批时间"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="发布时间:">
            <el-date-picker
              v-model="publishTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="发布时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :loading="btnLoading" @click="submitForm">
        提交
      </el-button>
      <el-button type="info" @click="handleClose">
        取消
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
// 样式
</style>
