<!-- 审批弹窗-审批人自选使用 -->
<script lang="ts" setup name="ApprovalDialogCustom">
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 { getUserList } from '@/api/system/user'
import { addApprovalUser } from '@/api/system/process'
/**
 * 审批弹窗
 */
const props = defineProps({
  /**
   * 提示文字
   */
  title: {
    type: String,
    default: '审批操作',
  },
  // 流程最后一个节点的名字
  lastName: {
    type: String,
    required: true,
  },
  approvalModule: { // 审批的菜单模块
    type: String,
    default: '',
  },
})
const emit = defineEmits(['onSuccess', 'refuse', 'reject'])
// 弹窗显示状态
const dialogVisible = ref(false)
// 默认表单
const defaultFormData = {
  type: '', // 审批类型
  taskId: '', // 任务id
  comments: '', // 备注
  user: '', // 当前用户
  approvalTime: '', // 当前时间
  id: '',
  userList: [] as any,
  processId: '',
}
// 弹窗类型 agree同意 refuse拒绝 reject驳回 revoke取消
const type = ref('agree')
// 表单数据对象
const formData = reactive({ ...defaultFormData })
// 是否展示 下一节点审批节点 审批人
const isShowUser = ref(false)
// 保存按钮加载状态
const btnLoading = ref(false)

// agree同意 refuse拒绝 reject驳回 revoke取消
const userInfo = useUserStore()

// ---------------表单提交--------------------------------
// 表单对象
const dataFormRef = ref<FormInstance>()
// 校验规则
const rules: FormRules = reactive({
  comments: [{ required: true, message: '审批结论必填', trigger: ['blur', 'change'] }],
  userList: [{ required: true, message: '节点审批人必选', trigger: ['blur', 'change'] }],
})
/**
 * 初始化审批弹窗
 * @param type 审批类型
 * @param taskId 任务id
 * @param id 列表id
 */
function initDialog(type: string, taskId: string, id?: string, processId?: string) {
  console.log('流程实例id--processId', processId)
  if (type === 'agree') { // 同意的时候判断是否显示选择下一个节点审批人
    isShowUser.value = true
    getApprovalRecord(processId!)
  }

  formData.type = type
  formData.taskId = taskId
  formData.user = userInfo.name
  formData.approvalTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  formData.userList = []
  formData.processId = processId!
  formData.comments = ''
  formData.id = id!
  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
        if (formData.type === 'agree') {
          const agree = () => {
            submitApproval(formData.type, { taskId: formData.taskId, comments: formData.comments }).then((res) => {
              ElMessage.success('审批完成')
              btnLoading.value = false
              dialogVisible.value = false
              emit('onSuccess')
            }).catch((_) => {
              btnLoading.value = false
            })
          }

          if (isShowUser.value) {
            addApprovalUser({
              assignees: formData.userList,
              processInstanceId: formData.processId,
            }).then(() => {
              agree()
            })
          }
          else {
            agree()
          }
        }
        else if (formData.type === 'reject') {
          dialogVisible.value = false
          btnLoading.value = false
          emit('reject', formData.comments, formData.taskId, formData.id)
        }
        else if (formData.type === 'refuse') {
          dialogVisible.value = false
          btnLoading.value = false
          emit('refuse', formData.comments, formData.taskId, formData.id)
        }
      }
    })
  }
}
// 关闭弹窗
function handleClose() {
  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>
  <div class="approval-dialog">
    <el-dialog
      v-model="dialogVisible"
      title="审批操作"
      width="700"
      :before-close="handleClose"
    >
      <el-form
        ref="dataFormRef"
        label-position="left"
        label-width="140px"
        :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 label="reject" size="large">
                  驳回
                </el-radio>
                <el-radio 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>
              <div v-if="props.approvalModule === 'fileApproval'" style="color: red;font-size: 11px;">
                <span v-if="isShowUser">***注意：《作业指导书》请选择专业组长审核；程序文件、质量手册等选择质量负责人审核***</span>
                <span v-if="!isShowUser">***注意：《作业指导书》请选择技术负责人；程序文件、质量手册等选择主任审核***</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="审批人:">
              <el-input
                v-model="formData.user"
                placeholder="审批人"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间:">
              <el-input
                v-model="formData.approvalTime"
                style="width: 100%;"
                placeholder="审批时间"
                disabled
              />
            </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>
  </div>
</template>

<style lang="scss">
.approval-dialog {
  .el-radio__label {
    display: block !important;
  }
}
</style>
