<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <BreadcrumbBack />
      <div class="breadcrumb-title">{{ headerTitle }}</div>
    </div>
    <main class="safety-platform-container__main">
      <component ref="dynamicComponentRef" :is="dynamicComponent" :id="id" />
    </main>
    <footer class="safety-platform-container__footer" v-if="type !== 'view'">
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </footer>
  </div>
  <BasicDialog ref="basicDialogRef" title="提交审批" @refresh="closeDialog">
    <template #form>
      <div class="form">
        <el-form ref="approvalFormRef" :model="approvalForm">
          <el-form-item label="审批描述：" label-position="top">
            <el-input v-model="approvalForm.description" placeholder="请输入审批描述" type="textarea" />
          </el-form-item>
          <div class="form-item">
            <span>审批流程：</span>
            <template v-for="item in approvalNodeList" :key="item.id">
              <el-form-item
                :label="`第${item.approvalOrder}步：${item.nodeDescription}（${APPROVAL_TYPE_MAP[item.approvalType]}）`"
                label-position="top"
                :prop="item.approverType !== APPROVER_TYPE.FIX ? `approvers.${item.id}` : ''"
                :rules="{ required: true, message: '请选择审批人员', trigger: 'change' }"
              >
                <el-input
                  v-if="item.approverType === APPROVER_TYPE.FIX"
                  :model-value="item.approverInfoList.map((info) => info.approverName).join(',')"
                  disabled
                ></el-input>
                <el-select
                  v-else
                  v-model="approvalForm.approvers[item.id]"
                  placeholder="请选择审批人员"
                  value-key="id"
                  filterable
                  remote
                  collapse-tags
                  collapse-tags-tooltip
                  :max-collapse-tags="2"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  multiple
                >
                  <el-option
                    v-for="option in userOptions"
                    :key="option.id"
                    :label="`${option.realname}（${option.username}）${option.deptName}`"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </div>
        </el-form>
      </div>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleSubmitApproval">提交</el-button>
      <el-button @click="basicDialogRef.closeDialog">取消</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { useRoute, useRouter } from 'vue-router';
  import { ref, computed, defineAsyncComponent, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicDialog from '@/components/BasicDialog.vue';
  import { useEmergencySuppliesHook } from '@/views/emergency/emergency-supplies/src/hook';
  import type { FileItem } from '@/components/UploadFiles/types.ts';
  import type { AddEmergencyPlanForm } from '@/types/emergency-plan';
  import type { ApprovalNodeInstanceType } from '@/views/system/approval/types';
  import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';
  import { createEmergencyPlan, editEmergencyPlan, submitApprovalProcess } from '@/api/emergency-plan';
  import { getApprovalNodeInstanceList } from '@/api/approval/approval';
  import { APPROVAL_TYPE_MAP, APPROVER_TYPE } from './src/constant';
  import { formatAttachment } from '@/components/UploadFiles/utils';

  const route = useRoute();
  const router = useRouter();
  const type = String(route.query.type);
  const id = Number(route.query.id);
  const planId = ref<number>();
  const approvalFormRef = ref();
  const approvalForm = reactive({
    description: '',
    approvers: {} as Record<number, any[]>,
  });

  const approvalNodeList = ref<ApprovalNodeInstanceType[]>([]);
  const dynamicComponentRef = ref();
  const basicDialogRef = ref();
  const headerTitle = computed(() => {
    const title = '应急预案';
    if (type === 'add') {
      return `添加${title}`;
    } else if (type === 'edit') {
      return `编辑${title}`;
    }
    return `${title}详情`;
  });
  const dynamicComponent = computed(() => {
    if (type === 'add') {
      return defineAsyncComponent(() => import('./src/components/AddManagementDetail.vue'));
    } else if (type === 'edit') {
      return defineAsyncComponent(() => import('./src/components/EditManagementDetail.vue'));
    }
    return defineAsyncComponent(() => import('./src/components/ViewManagementDetail.vue'));
  });
  const { userOptions, loading, remoteMethod } = useEmergencySuppliesHook();

  const createPlanManagementItemFunc = async (formData: AddEmergencyPlanForm) => {
    const attachmentListRes: FileItem[] = await Promise.all(formData.uploadFile.map((item) => formatAttachment(item)));
    const createParam = {
      planName: formData.planName,
      planType: formData.planType,
      eventType: formData.eventType,
      deptId: formData.deptId,
      deptName: formData.deptName,
      professionalTestSite: formData.professionalTestSite,
      approvalTemplateId: formData.approvalTemplateId,
      appendix: JSON.stringify(attachmentListRes),
    };
    return await createEmergencyPlan(createParam);
  };
  const editPlanManagementItemFunc = async (formData: AddEmergencyPlanForm) => {
    const attachmentListRes: FileItem[] = await Promise.all(formData.uploadFile.map((item) => formatAttachment(item)));
    const editParam = {
      id,
      planName: formData.planName,
      planType: formData.planType,
      eventType: formData.eventType,
      deptId: formData.deptId,
      deptName: formData.deptName,
      professionalTestSite: formData.professionalTestSite,
      approvalTemplateId: formData.approvalTemplateId,
      appendix: JSON.stringify(attachmentListRes),
    };
    await editEmergencyPlan(editParam);
  };
  const getApprovalNode = async (id: number) => {
    const res = await getApprovalNodeInstanceList(id);
    approvalNodeList.value = res.approvalNodeInfoList || [];
  };
  const handleSubmit = async () => {
    if (!dynamicComponentRef.value) return;
    const message = type === 'add' ? '添加' : '修改';
    const res = await dynamicComponentRef.value.handleValidate();
    if (!res) return;
    const data = dynamicComponentRef.value.getFormData();
    if (type === 'add') {
      const res = await createPlanManagementItemFunc(data);
      planId.value = res;
    } else {
      await editPlanManagementItemFunc(data);
      planId.value = id;
    }
    ElMessage.success(`${message}成功`);
    getApprovalNode(data.approvalTemplateId);
    basicDialogRef.value.openDialog();
  };

  const refreshForm = () => {
    approvalFormRef.value?.resetFields();
    approvalForm.description = '';
  };

  const closeDialog = () => {
    refreshForm();
    basicDialogRef.value.closeDialog();
  };

  const handleSubmitApproval = () => {
    approvalFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        // 构造后端需要的数据格式
        const approvalData = {
          planId: planId.value!,
          approvalDescription: approvalForm.description,
          approvalInfoList: approvalNodeList.value.map((node) => {
            let approverIdList: number[] = [];
            if (node.approverType === APPROVER_TYPE.FIX) {
              approverIdList = node.approverInfoList.map((info) => info.approverId);
            } else if (approvalForm.approvers[node.id]) {
              approverIdList = approvalForm.approvers[node.id];
            }
            return {
              approvalOrder: node.approvalOrder,
              approverIdList,
            };
          }),
        };
        await submitApprovalProcess(approvalData);
        ElMessage.success('提交成功');
        basicDialogRef.value.closeDialog();
        router.back();
      }
    });
  };
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use './src/styles/info-common.scss' as *;
  .form {
    display: flex;
    flex-direction: column;
    gap: 40px;
  }
  .form-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
</style>
