<template>
  <BasicDialog ref="basicDialogRef" title="提交审批" @refresh="refreshFromData">
    <template #form>
      <el-form ref="formRef" :model="formData" label-width="auto">
        <el-form-item prop="approvalDescription" label="审批描述">
          <el-input v-model="formData.approvalDescription" placeholder="请输入审批描述" />
        </el-form-item>
        <el-form-item
          v-for="(item, index) in formData.approverListInfo"
          :key="item.approvalOrder"
          :label="`第${item.approvalOrder + 1}步，${item.deptName}（${item.approvalType ? '或签' : '会签'}）`"
          :prop="'approverListInfo.' + index + '.approverList'"
          :rules="{ required: true, message: '请选择审批人', trigger: 'change' }"
        >
          <el-select
            v-model="item.approverList"
            placeholder="请输入审批人"
            value-key="id"
            filterable
            multiple
            remote
            :disabled="!item.approverType"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option v-for="item in userOptions" :key="item.id" :label="item.realname" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleSumbit">提交</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import BasicDialog from '@/components/BasicDialog.vue';
  import { DrillApprovalItem, DrillApprovalRuleForm } from '../types';
  import type { QueryUserInfoByUserNameRes } from '@/types/person-group/type';
  import { queryUserInfoByUserName } from '@/api/system/person-group';
  import { FormInstance } from 'element-plus';

  const props = defineProps<{
    approvalData: DrillApprovalItem[];
  }>();
  const emits = defineEmits<{
    (e: 'filled', data: DrillApprovalRuleForm): void;
  }>();

  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const formRef = ref<FormInstance>();

  const openDialog = () => {
    initForm(props.approvalData);
    basicDialogRef.value?.openDialog();
  };

  const closeDialog = () => {
    if (!basicDialogRef.value) return;
    clearForm();
    basicDialogRef.value.closeDialog();
  };

  const formData = reactive<DrillApprovalRuleForm>({
    approvalDescription: '',
    approverListInfo: [],
  });
  function initForm(originalData: DrillApprovalItem[]) {
    // 初始化转换结果
    const result: {
      approvalOrder: number;
      approvalType: number;
      approverType: number;
      deptName: string;
      approverList: any[];
      approverIds?: number[];
      // approverName: string[];
    }[] = [];
    // 遍历原始数据数组
    originalData.forEach((item) => {
      if (item.approverType === 0) {
        // 固定

        // 收集当前审批环节的所有审批人ID和名称
        const approverIds: number[] = [];
        const approverNames: string[] = [];
        // 默认为第一个流程项的部门名称
        let deptName = '';
        // 处理流程列表
        item.processInfoList.forEach((process, index) => {
          // 收集审批人信息
          approverIds.push(process.approverId);
          approverNames.push(process.approverName);
          // 设置部门名称（取第一个流程项的部门名称）
          if (index === 0) {
            deptName = process.approvalDeptName;
          }
        });
        // 添加到转换结果中
        result.push({
          approvalOrder: item.approvalOrder,
          approverType: item.approverType,
          approvalType: item.processInfoList[0].approvalType,
          deptName,
          approverList: approverNames,
          approverIds: approverIds,
          // approverName: approverNames,
        });
      } else {
        // 自选
        result.push({
          approvalOrder: item.approvalOrder,
          approverType: item.approverType,
          approvalType: item.processInfoList[0].approvalType,
          deptName: '',
          approverList: [],
          // approverId: [],
          // approverName: [],
        });
      }
    });

    formData.approverListInfo = result;
  }

  function clearForm() {
    formData.approvalDescription = '';
    formData.approverListInfo = [];
  }

  const handleSumbit = async () => {
    const validate = await new Promise((resolve) => {
      formRef.value?.validate((valid: boolean) => {
        resolve(valid);
      });
    });
    if (!validate) return;
    emits('filled', formData);
  };

  // const handleCancel = () => {
  //   if (!basicDialogRef.value) return;
  //   clearForm();
  //   basicDialogRef.value.closeDialog();
  // };

  // 人员选择
  const userOptions = ref<QueryUserInfoByUserNameRes[]>([]);
  const loading = ref<boolean>(false);
  const remoteMethod = async (query: string) => {
    if (!query) {
      userOptions.value = [];
      return;
    }
    loading.value = true;
    userOptions.value = await queryUserInfoByUserName(query);
    loading.value = false;
  };

  const refreshFromData = () => {
    formRef.value?.clearValidate();
  };

  defineExpose({
    openDialog,
    closeDialog,
  });
</script>

<style scoped></style>
