<template>
  <main class="safety-platform-container__main">
    <el-alert
      v-if="rejectReason && (Number(approvalStatus) === 3)"
      type="error"
      :title="'不通过原因：' + rejectReason"
      show-icon
      class="detail-reject-alert"
    />

    <div class="select-box-ao">
      <div class="select-box--item_new">
        <span>
          <span style="color: red;">*</span>
          审批流程
          ：
        </span>
        <el-select
          class="select-box--item__select"
          v-model="form.approvalTemplateId"
          placeholder="审批流程"
          filterable
          :disabled="isViewMode || isAuditMode"
          popper-class="el-scrollbar--custom"
        >
          <el-option v-for="item in approvalList" :key="item.id" :label="item.templateName" :value="item.id" />
        </el-select>
      </div>

      <div class="select-box--item_new" v-if="!isCreateMode">
        <span>
          <span style="color: red;">*</span>
          申请单号
          ：
        </span>
        {{ form.applyNo }}
      </div>
    </div>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="120px"
      class="purchase-apply-form"
    >
      <!-- 申请单号：仅非新增时显示；查看/审核为纯文本 -->
      <!-- <el-form-item v-if="!isCreateMode" label="申请单号" prop="applyNo" required>
        <span v-if="isViewMode || isAuditMode" class="apply-no-text">{{ form.applyNo || '-' }}</span>
        <el-input
          v-else
          v-model="form.applyNo"
          placeholder="申请单号"
          readonly
          class="apply-no-input"
        />
      </el-form-item> -->

      <!-- 劳防用品明细表 -->
      <div class="table-section">
        <el-table :data="form.itemList" border size="default" class="items-table">
          <el-table-column type="index" label="编号" width="100" align="center" />
          <el-table-column label="劳防用品名称" min-width="140">
            <template #default="{ row }">
              <span v-if="isViewMode || isAuditMode">{{ row.ppeName || row.equipmentName || '-' }}</span>
              <el-select
                v-else
                v-model="row.equipmentName"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                @change="onPpeSelect(row, $event)"
              >
                <el-option
                  v-for="item in ppeOptions"
                  :key="item.id"
                  :label="item.ppeName"
                  :value="item.ppeName"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="样式照片" min-width="420" align="center">
            <template #default="{ row }">
              <span v-if="isViewMode || isAuditMode">{{ getStylePhotoDisplay(row) }}</span>
              <UploadFiles
                v-else
                label="选择附件"
                :file-list="getRowFileList(row)"
                :max-count="1"
                @uploadSuccess="(list: FileItem[]) => onStylePhotoSuccess(row, list)"
              />
            </template>
          </el-table-column>
          <el-table-column label="物品尺寸/鞋码" min-width="150">
            <template #default="{ row }">
              <span v-if="isViewMode || isAuditMode">{{ row.sizeOrShoeSize || row.specSize || '-' }}</span>
              <el-input
                v-else
                v-model="row.specSize"
                placeholder="请输入..."
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="需求数量" min-width="150">
            <template #default="{ row }">
              <span v-if="isViewMode || isAuditMode">{{ row.requiredQty ?? row.applyNum ?? '-' }}</span>
              <el-input-number
                v-else
                v-model="row.applyNum"
                :min="1"
                :precision="0"
                placeholder="请输入..."
                controls-position="right"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="规格、型号、类型" min-width="200">
            <template #default="{ row }">
              <span v-if="isViewMode || isAuditMode">{{ row.specModelType || row.model || '-' }}</span>
              <el-input
                v-else
                v-model="row.model"
                placeholder="请输入..."
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="单价/元" min-width="150">
            <template #default="{ row }">
              <span v-if="isViewMode || isAuditMode">{{ row.unitPrice ?? '-' }}</span>
              <el-input
                v-else
                type="number"
                v-model="row.unitPrice"
                placeholder="请输入..."
              />
            </template>
          </el-table-column>
          <el-table-column label="商品编号" min-width="150">
            <template #default="{ row }">
              <!-- v-if="isViewMode || isAuditMode || isCreateMode" -->
              <span>{{ row.productNo || row.equipmentId || '-' }}</span>
              <!-- <el-input
                v-else
                v-model="row.productNo"
                placeholder="请输入..."
                clearable
              /> -->
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150">
            <template #default="{ row }">
              <span v-if="isViewMode || isAuditMode">{{ row.remark || '-' }}</span>
              <el-input
                v-else
                v-model="row.remark"
                placeholder="请输入..."
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column v-if="!isViewMode && !isAuditMode" label="操作" width="150" fixed="right" align="center">
            <template #default="{ $index }">
              <el-button type="primary" circle size="small" @click="addRow">
                <el-icon><Plus /></el-icon>
              </el-button>
              <el-button
                type="danger"
                circle
                size="small"
                :disabled="form.itemList.length <= 1"
                @click="removeRow($index)"
              >
                <el-icon><Minus /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <!-- 审核不通过原因 -->
    <el-dialog
      v-model="showRejectDialog"
      title="审核不通过"
      width="400px"
      destroy-on-close
      @close="rejectReason = ''"
    >
      <el-input
        v-model="rejectReason"
        type="textarea"
        :rows="3"
        placeholder="请输入审核不通过原因"
      />
      <template #footer>
        <el-button @click="showRejectDialog = false">取消</el-button>
        <el-button type="danger" :loading="auditSubmitting" @click="handleAuditReject">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 选择审核人：点击提交时弹出 -->
    <el-dialog
      v-model="showApproverDialog"
      title="选择审核人"
      width="480px"
      destroy-on-close
      @close="resetApproverForm"
    >
      <el-form ref="approverFormRef" :model="approverForm" :rules="approverFormRules" label-width="100px">
        <el-form-item label="部门名称" prop="deptId" required>
          <el-select
            v-model="approverForm.deptId"
            placeholder="选择审核部门名称"
            clearable
            filterable
            style="width: 100%"
            @change="onApproverDeptChange"
          >
            <el-option
              v-for="item in deptOptions"
              :key="item.id"
              :label="item.deptName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门审核人" prop="approverId" required>
          <el-select
            v-model="approverForm.approverId"
            placeholder="选择部门审核人"
            clearable
            filterable
            style="width: 100%"
            :disabled="!approverForm.deptId"
          >
            <el-option
              v-for="item in approverOptions"
              :key="item.id"
              :label="item.realname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showApproverDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleApproverSave">保存</el-button>
      </template>
    </el-dialog>

    <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>

  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <template v-if="isCreateMode || isEditMode">
      <el-button type="primary" :loading="submitting" @click="onPrimaryClick">
        {{ isCreateMode ? '提交' : '保存' }}
      </el-button>
    </template>
    <template v-if="isAuditMode">
      <el-button type="success" :loading="auditSubmitting" @click="handleAuditPass">
        审核通过
      </el-button>
      <el-button type="danger" :loading="auditSubmitting" @click="showRejectDialog = true">
        审核不通过
      </el-button>
    </template>
  </footer>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, reactive } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import { Plus, Minus } from '@element-plus/icons-vue';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import type { FileItem } from '@/components/UploadFiles/types';
  import { queryPersonalProtectiveEquipmentList } from '@/api/production-safety/personal-protective-equipment';
  import type { PersonalProtectiveEquipment } from '@/api/production-safety/personal-protective-equipment';
  import { useEmergencyHook } from '@/views/emergency/src/hoos';
  import {
    queryPurchaseApplyDetail,
    savePurchaseApply,
    updatePurchaseApply,
    auditPurchaseApply,
    submitApprovalProcess,
    saveThePurchaseRequest,
    type PersonalProtectiveEquipmentPurchaseApply,
    type PurchaseApplyItem,
    type PpePurchaseApplyDetail,
    type SavePpePurchaseApplyReq,
    type ApprovalInfoItem,
  } from '@/api/production-safety/personal-protective-equipment-purchase-apply';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { DeptTree } from '@/types/dept/type';
  import { getUserList } from '@/api/system/user-operate';
  import type { UserLisItem } from '@/api/system/user-operate';
  import BasicDialog from '@/components/BasicDialog.vue';
  import type { ApprovalNodeInstanceType } from '@/views/system/approval/types';
  import { APPROVAL_TYPE_MAP, APPROVER_TYPE } from '../configs/constant';
  import { useEmergencySuppliesHook } from '@/views/emergency/emergency-supplies/src/hook';
  import { getApprovalNodeInstanceList } from '@/api/approval/approval';
  import { i } from 'vite/dist/node/types.d-jgA8ss1A';
  import { te } from 'element-plus/es/locale';

  const { approvalList, getApprovalList } =
  useEmergencyHook()
  const basicDialogRef = ref();
  const approvalFormRef = ref();
  const approvalForm = reactive({
    description: '',
    approvers: {} as Record<number, any[]>,
  });

  const approvalNodeList = ref<ApprovalNodeInstanceType[]>([]);
  const { userOptions, loading, remoteMethod } = useEmergencySuppliesHook();

  const router = useRouter();
  const route = useRoute();
  const formRef = ref<FormInstance>();
  const submitting = ref(false);
  const auditSubmitting = ref(false);
  const showRejectDialog = ref(false);

  const planId = ref<string>(route.query.id as string || '');

  const showApproverDialog = ref(false);
  const approverFormRef = ref<FormInstance>();
  const approverForm = reactive<{ deptId: number | null; approverId: number | null }>({
    deptId: null,
    approverId: null,
  });
  const approverFormRules: FormRules = {
    deptId: [{ required: true, message: '请选择审核部门名称', trigger: 'change' }],
    approverId: [{ required: true, message: '请选择部门审核人', trigger: 'change' }],
  };
  const deptOptions = ref<{ id: number; deptName: string }[]>([]);
  const approverOptions = ref<UserLisItem[]>([]);

  const operate = computed(() => (route.query.operate as string) || 'inventory-create');
  const currentId = computed(() => Number(route.query.id));
  const approvalOrder = ref<string>(route.query.approvalOrder as string || '');
  const rejectReason = ref<string>(route.query.rejectReason as string || '');
  const approvalStatus = ref<string>(route.query.approvalStatus as string || '');
  
  /** 从列表带入的申请单号/申请人/部门（无主表查询接口时用于展示） */
  const mainFromQuery = computed(() => ({
    applyCode: route.query.applyCode as string | undefined,
    applicantName: route.query.applicantName as string | undefined,
    deptName: route.query.deptName as string | undefined,
  }));

  const isCreateMode = computed(() => operate.value === 'inventory-create');
  const isEditMode = computed(() => operate.value === 'inventory-edit');
  const isViewMode = computed(() => operate.value === 'inventory-view');
  const isAuditMode = computed(() => operate.value === 'audit');

  const ppeOptions = ref<PersonalProtectiveEquipment[]>([]);

  const defaultItem = (): PurchaseApplyItem => ({
    ppeName: '',
    ppeId: undefined,
    stylePhoto: '',
    sizeOrShoeSize: '',
    requiredQty: undefined,
    specModelType: '',
    unitPrice: undefined,
    productNo: '',
    remark: '',
  });
  
  const form = reactive<PersonalProtectiveEquipmentPurchaseApply & { itemList: PurchaseApplyItem[] }>({
    applyNo: '',
    approvalTemplateId: route.query.templateId,
    itemList: [defaultItem()],
  });

  const formRules: FormRules = {
    applyNo: [{ required: true, message: '申请单号不能为空', trigger: 'blur' }],
  };

  function getRowFileList(row: PurchaseApplyItem): FileItem[] {
    if (row.pictureUrl && typeof row.pictureUrl === 'string') {
      return [{ fileId: 0, fileName: '样式图', fileType: 'image', fileSize: '', fileUrl: row.pictureUrl }];
    }
    if (!row.stylePhoto) return [];
    try {
      const parsed = typeof row.stylePhoto === 'string' ? JSON.parse(row.stylePhoto) : row.stylePhoto;
      const arr = Array.isArray(parsed) ? parsed : [parsed];
      return arr.map((f: any) => ({
        fileId: f.fileId ?? 0,
        fileName: f.fileName ?? '样式图',
        fileType: f.fileType ?? 'image',
        fileSize: f.fileSize ?? '',
        fileUrl: f.fileUrl,
      }));
    } catch {
      return [];
    }
  }

  /** 查看/审核时样式照片列仅显示文件名或链接文本 */
  function getStylePhotoDisplay(row: PurchaseApplyItem): string {
    if (row.pictureUrl) return row.pictureUrl;
    const list = getRowFileList(row);
    if (!list.length) return '-';
    return list.map((f) => f.fileName).filter(Boolean).join('、') || '-';
  }

  function onStylePhotoSuccess(row: PurchaseApplyItem, list: FileItem[]) {
    row.stylePhoto = JSON.stringify(
      list.map((f) => ({ fileUrl: f.fileUrl, fileName: f.fileName, fileId: f.fileId, fileType: f.fileType, fileSize: f.fileSize })),
    );
  }

  /** 后端明细行 → 表单行 */
  function detailToItem(d: PpePurchaseApplyDetail): PurchaseApplyItem {
    return {
      ...defaultItem(),
      id: d.id,
      ppeApplyId: d.ppeApplyId,
      equipmentId: d.equipmentId,
      equipmentName: d.equipmentName,
      ppeName: d.equipmentName,
      ppeId: d.equipmentId,
      specSize: d.specSize,
      sizeOrShoeSize: d.specSize,
      applyNum: d.applyNum,
      requiredQty: d.applyNum,
      model: d.model,
      specModelType: d.model,
      unitPrice: d.unitPrice,
      pictureUrl: d.pictureUrl,
      stylePhoto: d.pictureUrl ?? '',
      remark: d.remark,
      productNo: d.productNo,
    };
  }

  /** 表单行 → 后端明细行 */
  function itemToDetail(it: PurchaseApplyItem): PpePurchaseApplyDetail {
    return {
      id: it.id,
      ppeApplyId: it.ppeApplyId ?? currentId.value,
      equipmentId: it.equipmentId ?? it.ppeId,
      equipmentName: it.equipmentName ?? it.ppeName,
      specSize: it.specSize ?? it.sizeOrShoeSize,
      applyNum: it.applyNum ?? it.requiredQty,
      model: it.model ?? it.specModelType,
      unitPrice: it.unitPrice,
      pictureUrl: it.pictureUrl ?? (typeof it.stylePhoto === 'string' ? it.stylePhoto : undefined),
      remark: it.remark,
      productNo: it.productNo,
    };
  }

  function onPpeSelect(row: PurchaseApplyItem, ppeName: string) {
    const found = ppeOptions.value.find((p) => p.ppeName === ppeName);
    if (found?.id) {
      row.ppeId = found.id;
      row.equipmentId = found.id;
      row.productNo = String(found.id);
    }
  }

  function addRow() {
    form.itemList.push(defaultItem());
  }

  function removeRow(index: number) {
    if (form.itemList.length <= 1) return;
    form.itemList.splice(index, 1);
  }

  /** 劳防用品名称下拉：使用 queryPersonalProtectiveEquipmentList，名称用 ppeName */
  async function loadPpeOptions() {
    try {
      const res = await queryPersonalProtectiveEquipmentList({
        pageNumber: 1,
        pageSize: 500,
        queryParam: {},
      } as QueryPageRequest<any>);
      // const list = res?.records ?? res?.list ?? [];
      const resAny = res as any;
      const list = resAny?.records ?? resAny?.list ?? [];
      ppeOptions.value = (list as PersonalProtectiveEquipment[]).map((item) => ({
        ...item,
        ppeName: item.ppeName ?? (item as any).name ?? '',
      }));
    } catch (e) {
      console.error('加载劳防用品列表失败:', e);
    }
  }

  async function getDetail() {
    if (!currentId.value) return;
    try {
      form.applyNo = mainFromQuery.value.applyCode ?? '';
      const res = await queryPurchaseApplyDetail(currentId.value);
      if (res && Array.isArray(res) && res.length) {
        form.itemList = res.map((d) => detailToItem(d));
      } else if (res && Array.isArray(res)) {
        form.itemList = [defaultItem()];
      }
    } catch (e) {
      console.error('获取采购申请详情失败:', e);
      ElMessage.error('获取详情失败');
    }
  }

  function buildSubmitPayload(extra?: { approvalInfoList?: ApprovalInfoItem[]; approvalDescription?: string; templateId?: number | undefined;}): SavePpePurchaseApplyReq {
    const ppePurchaseApplyDetails = form.itemList
      .filter((it) => it.ppeName || it.equipmentName)
      .map((it) => itemToDetail(it));
    return {
      id: currentId.value || undefined,
      applyCode: form.applyNo ? Number(form.applyNo) : undefined,
      applicantName: mainFromQuery.value.applicantName,
      deptName: mainFromQuery.value.deptName,
      saveOrSubmit: isCreateMode.value ? 1 : 0,
      ppePurchaseApplyDetails,
      templateId: form.approvalTemplateId,
      ...extra,
    };
  }

  /** 扁平化部门树为选项列表 */
  function flattenDeptTree(nodes: DeptTree[], result: { id: number; deptName: string }[] = []): { id: number; deptName: string }[] {
    if (!nodes?.length) return result;
    for (const node of nodes) {
      if (node.id != null && node.deptName) result.push({ id: node.id, deptName: node.deptName });
      if (node.children?.length) flattenDeptTree(node.children, result);
    }
    return result;
  }

  async function loadDeptOptions() {
    try {
      const res = await getAllDepartments();
      // const tree = (Array.isArray(res) ? res : res?.children) ?? [];
      const resWithChildren = res as (DeptTree[] | { children?: DeptTree[] });
      const tree = (Array.isArray(resWithChildren) ? resWithChildren : resWithChildren?.children) ?? [];
      const list = tree.length && tree[0]?.children ? tree[0].children : tree;
      deptOptions.value = flattenDeptTree(list as DeptTree[]);
    } catch (e) {
      console.error('加载部门列表失败:', e);
    }
  }

  async function onApproverDeptChange(deptId: number | null) {
    approverForm.approverId = null;
    approverOptions.value = [];
    if (!deptId) return;
    try {
      const res = await getUserList({
        pageNumber: 1,
        pageSize: 500,
        queryParam: { deptId },
      });
      approverOptions.value = res?.records ?? [];
    } catch (e) {
      console.error('加载部门审核人失败:', e);
    }
  }

  function resetApproverForm() {
    approverForm.deptId = null;
    approverForm.approverId = null;
    approverOptions.value = [];
  }

  /** 点击底部「提交」：先校验表单，再弹出选择审核人 */
  async function openApproverDialog() {
    if (!form.approvalTemplateId) {
      ElMessage.warning('请选择审批模板');
      return;
    }
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;
    if (!form.itemList.length || form.itemList.every((it) => !it.ppeName && !it.equipmentName)) {
      ElMessage.warning('请至少填写一条劳防用品明细');
      return;
    }
    // showApproverDialog.value = true;
    const payload = buildSubmitPayload({
      templateId: form.approvalTemplateId,
    });
    await saveThePurchaseRequest(payload).then((res) => {
      ElMessage.success('提交成功');
      if(isCreateMode.value){
        planId.value = res || undefined;
      }
    });

    await getApprovalNode(form.approvalTemplateId);
    basicDialogRef.value.openDialog();
    if (!deptOptions.value.length) await loadDeptOptions();
  }

  /** 弹窗内点击「保存」：校验审核人后带审批信息提交 */
  async function handleApproverSave() {
    const valid = await approverFormRef.value?.validate().catch(() => false);
    if (!valid) return;
    const approvalInfoList: ApprovalInfoItem[] = [
      { approvalOrder: 1, approverIdList: String(approverForm.approverId) },
    ];
    const payload = buildSubmitPayload({
      approvalInfoList,
      approvalDescription: '',
      templateId: form.approvalTemplateId,
    });
    await doSubmit(payload);
    showApproverDialog.value = false;
    resetApproverForm();
  }

  /** 实际提交请求（新增/编辑） */
  async function doSubmit(payload: SavePpePurchaseApplyReq) {
    submitting.value = true;
    try {
      if (isCreateMode.value) {
        await savePurchaseApply(payload);
        ElMessage.success('提交成功');
      } else {
        await updatePurchaseApply(payload);
        ElMessage.success('保存成功');
        await getApprovalNode(form.approvalTemplateId);
        basicDialogRef.value.openDialog();
        return;
      }
      router.back();
    } catch (e) {
      console.error('保存失败:', e);
      ElMessage.error('保存失败，请重试');
    } finally {
      submitting.value = false;
    }
  }

  /** 底部主按钮：新增时弹出选择审核人，编辑时直接保存 */
  async function onPrimaryClick() {
    if (isCreateMode.value) {
      await openApproverDialog();
    } else {
      const valid = await formRef.value?.validate().catch(() => false);
      if (!valid) return;
      if (!form.itemList.length || form.itemList.every((it) => !it.ppeName && !it.equipmentName)) {
        ElMessage.warning('请至少填写一条劳防用品明细');
        return;
      }
      await doSubmit(buildSubmitPayload());
    }
  }

  async function handleAuditPass() {
    if (!currentId.value) return;
    auditSubmitting.value = true;
    try {
      await auditPurchaseApply({ id: currentId.value, status: 2, approvalOrder: Number(approvalOrder.value),templateId: form.approvalTemplateId });
      ElMessage.success('审核通过');
      router.back();
    } catch (e) {
      console.error('审核失败:', e);
      ElMessage.error('审核失败，请重试');
    } finally {
      auditSubmitting.value = false;
    }
  }

  async function handleAuditReject() {
    if (!rejectReason.value?.trim()) {
      ElMessage.warning('请输入审核不通过原因');
      return;
    }
    if (!currentId.value) return;
    auditSubmitting.value = true;
    try {
      await auditPurchaseApply({ id: currentId.value, status: 3, rejectReason: rejectReason.value.trim(), approvalOrder: Number(approvalOrder.value),templateId: form.approvalTemplateId });
      ElMessage.success('已提交审核不通过');
      showRejectDialog.value = false;
      router.back();
    } catch (e) {
      console.error('审核失败:', e);
      ElMessage.error('审核失败，请重试');
    } finally {
      auditSubmitting.value = false;
    }
  }

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

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

  const getApprovalNode = async (id: number) => {
    const res = await getApprovalNodeInstanceList(id);
    approvalNodeList.value = res.approvalNodeInfoList || [];
  };

  const handleSubmitApproval = () => {
    approvalFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        // 构造后端需要的数据格式
        const approvalData = {
          id: planId.value!,
          templateId: form.approvalTemplateId,
          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();
      }
    });
  };

  onMounted(() => {
    loadPpeOptions();
    getApprovalList();
    if (form.approvalTemplateId) {
      form.approvalTemplateId = Number(form.approvalTemplateId);
    }
    if (isEditMode.value || isViewMode.value || isAuditMode.value) {
      getDetail();
    } else {
      form.itemList = [defaultItem()];
    }
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;

  .safety-platform-container__header {
    flex-direction: row !important;
    justify-content: flex-start !important;
    gap: 8px !important;
  }
  .purchase-apply-form {
    max-width: 100%;
  }
  .apply-no-input {
    max-width: 320px;
  }
  .apply-no-text {
    color: var(--el-text-color-regular);
  }
  .table-section {
    margin-top: 16px;
  }
  .items-table {
    width: 100%;
  }
  .select-box-ao{
    display: flex;
    gap: 20px;
  }
  .select-box--item_new{
    display: flex;
    align-items: center;
  }
  .select-box--item__select{
    width: 320px;
  }
  .detail-reject-alert{
    margin-bottom: 20px;
  }
</style>
