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

    <BasicForm
      ref="basicFormRef"
      :formData="ruleFormData"
      :formRules="isViewMode ? undefined : formRules"
      :formConfig="computedFormConfig"
    >
      <template #approvalTemplateId>
        <el-select
          class="select-box--item__select"
          v-model="ruleFormData.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>
      </template>
      <template #reviewDepartmentId>
        <el-cascader
          v-model="ruleFormData.departmentCode"
          ref="cascaderRef" 
          :options="firstLevelDepts"
          :props="cascaderProp"
          :show-all-levels="false"
          placeholder="部门名称"
          filterable
          :disabled="isViewMode || isAuditMode"
          @change="handleChangeDept"
        />
      </template>

      <template #accidentReport>
        <UploadFiles
          v-if="!isViewMode && !isAuditMode"
          label="上传事故报告"
          :maxCount="1"
          :file-list="accidentCertUrl"
          :disabled="isViewMode || isAuditMode"
          @uploadSuccess="handleAccidentReportUploadSuccess"
        />
        <div class="file-list" v-else>
          <div v-if="accidentCertUrl && accidentCertUrl.length > 0">
            <div class="file-item" v-for="file in accidentCertUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                >
              </div>
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </template>

      <template #powerOfAttorney>
        <UploadFiles
          v-if="!isViewMode && !isAuditMode"
          label="上传委托书"
          :maxCount="1"
          :file-list="powerAttorneyUrl"
          :disabled="isViewMode || isAuditMode"
          @uploadSuccess="handlePowerOfAttorneyUploadSuccess"
        />
        <div class="file-list" v-else>
          <div v-if="powerAttorneyUrl && powerAttorneyUrl.length > 0">
            <div class="file-item" v-for="file in powerAttorneyUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                >
              </div>
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </template>
      <template #addressConfirmation>
        <UploadFiles
          v-if="!isViewMode && !isAuditMode"
          label="上传地址确认书"
          :maxCount="1"
          :file-list="addressConfirmUrl"
          :disabled="isViewMode || isAuditMode"
          @uploadSuccess="handleAddressConfirmationUploadSuccess"
        />
        <div class="file-list" v-else>
          <div v-if="addressConfirmUrl && addressConfirmUrl.length > 0">
            <div class="file-item" v-for="file in addressConfirmUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                >
              </div>
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </template>
      <template #applicationForm>
        <UploadFiles
          v-if="!isViewMode && !isAuditMode"
          label="上传申请表"
          :maxCount="1"
          :file-list="applicationFormUrl"
          :disabled="isViewMode || isAuditMode"
          @uploadSuccess="handleApplicationFormUploadSuccess"
        />
        <div class="file-list" v-else>
          <div v-if="applicationFormUrl && applicationFormUrl.length > 0">
            <div class="file-item" v-for="file in applicationFormUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                >
              </div>
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </template>
      <template #idCard>
        <UploadFiles
          v-if="!isViewMode && !isAuditMode"
          label="上传身份证正反面"
          :maxCount="1"
          :file-list="idCardUrl"
          :disabled="isViewMode || isAuditMode"
          @uploadSuccess="handleIdCardUploadSuccess"
        />
        <div class="file-list" v-else>
          <div v-if="idCardUrl && idCardUrl.length > 0">
            <div class="file-item" v-for="file in idCardUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                >
              </div>
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </template>
      <template #laborContract>
        <UploadFiles
          v-if="!isViewMode && !isAuditMode"
          label="上传劳动合同"
          :maxCount="1"
          :file-list="laborContractUrl"
          :disabled="isViewMode || isAuditMode"
          @uploadSuccess="handleLaborContractUploadSuccess"
        />
        <div class="file-list" v-else>
          <div v-if="laborContractUrl && laborContractUrl.length > 0">
            <div class="file-item" v-for="file in laborContractUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                >
              </div>
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </template>
      <template #initialMedicalCertificate>
        <UploadFiles
          v-if="!isViewMode && !isAuditMode"
          label="上传初次医疗证明"
          :maxCount="1"
          :file-list="initialMedicalCertUrl"
          :disabled="isViewMode || isAuditMode"
          @uploadSuccess="handleInitialMedicalCertificateUploadSuccess"
        />
        <div class="file-list" v-else>
          <div v-if="initialMedicalCertUrl && initialMedicalCertUrl.length > 0">
            <div class="file-item" v-for="file in initialMedicalCertUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                >
              </div>
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </template>
      <template #agentIdCard>
        <UploadFiles
          v-if="!isViewMode && !isAuditMode"
          label="上传被委托人员身份证正反面"
          :maxCount="1"
          :file-list="trusteeIdCardUrl"
          :disabled="isViewMode || isAuditMode"
          @uploadSuccess="handleAgentIdCardUploadSuccess"
        />
        <div class="file-list" v-else>
          <div v-if="trusteeIdCardUrl && trusteeIdCardUrl.length > 0">
            <div class="file-item" v-for="file in trusteeIdCardUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                >
              </div>
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </template>
      <template #status>
        <el-radio-group v-model="ruleFormData.status" :disabled="isViewMode">
          <el-radio label="ENABLE">启用</el-radio>
          <el-radio label="DISABLE">禁用</el-radio>
        </el-radio-group>
      </template>
    </BasicForm>
    <PreviewOnline ref="previewOnlineRef" />
    <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>
    <!-- 审核不通过原因 -->
    <el-dialog
      v-model="showRejectDialog"
      title="审核不通过"
      width="400px"
      destroy-on-close
      @close="rejectReason = ''"
    >
      <el-radio-group v-model="rejectReason" v-if="auditType">
        <el-radio value="1">责任事故</el-radio>
        <el-radio value="2">非责任事故</el-radio>
        <el-radio value="3">交通事故</el-radio>
      </el-radio-group>
      <el-input
      v-else
        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>
  </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="handleSubmit">
        {{ isCreateMode ? '提交' : '保存' }}
      </el-button>
    </template>
    <template v-if="isAuditMode">
      <el-button type="success" :loading="auditSubmitting" @click="showRejectDialog = true;auditType = true">
        审核通过
      </el-button>
      <el-button type="danger" :loading="auditSubmitting" @click="showRejectDialog = true;auditType = false">
        审核不通过
      </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 BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { INVENTORY_FORM_CONFIG, INVENTORY_FORM_DATA, INVENTORY_FORM_RULES } from '../configs/form';
  import { 
    queryWorkInjuryApplyDetail, 
    saveBusinessInformation, 
    updateInventory , 
    submitApprovalProcess, 
    auditPurchaseApply,
    updateWorkInjuryApply,
   } from '@/api/inventory';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import type { FileItem } from '@/components/UploadFiles/types';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { getAllDepartments } from '@/api/auth/dept';
  import BasicDialog from '@/components/BasicDialog.vue';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  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 { useEmergencyHook } from '@/views/emergency/src/hoos';
  import { getApprovalNodeInstanceList } from '@/api/approval/approval';
  import { template } from 'lodash-es';
  import { downloadFile } from '@/views/disaster/utils';


  const router = useRouter();
  const route = useRoute();

  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    // emitPath: false,
    value: 'id',
    label: 'deptName',
  };
  const { approvalList, getApprovalList } = useEmergencyHook()

  const operate = computed(() => (route.query.operate as string) || 'inventory-create');
  const currentId = computed(() => Number(route.query.id));
  const newFormId = ref('');

  const firstLevelDepts = ref<any[]>([]);

  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 === 'inventory-audit');
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const cascaderRef = ref();
  const rejectReason = ref<string>(route.query.rejectReason as string || '');
  const approvalOrder = ref<string>(route.query.approvalOrder as string || '');
  const approvalTemplateId = ref<string>(route.query.approvalTemplateId as string || '');
  const approvalStatus = ref<string>(route.query.approvalStatus as string || '');
  const auditType = ref(true);

  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 submitting = ref(false);
  const auditSubmitting = ref(false);
  const showRejectDialog = ref(false);

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook(INVENTORY_FORM_CONFIG, INVENTORY_FORM_DATA, INVENTORY_FORM_RULES);

  // 查看模式下，所有字段设为只读
  const viewFormConfig = ref(
    INVENTORY_FORM_CONFIG.map((item) => ({
      ...item,
      componentProps: {
        ...item.componentProps,
        disabled: true,
      },
    })),
  );

  const computedFormConfig = computed(() => {
    if (isViewMode.value) {
      return viewFormConfig.value;
    }
    if (isAuditMode.value) {
      return viewFormConfig.value;
    }
    return ruleFormConfig.value;
  });

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const res = await basicFormRef.value.validateForm();
    return res;
  };

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryWorkInjuryApplyDetail(currentId.value);
      if (res) {
        // 映射接口字段到表单字段
        ruleFormData.itemName = res.applicantName || ''; // 申请人姓名
      ruleFormData.applicantCode = res.applicantCode || ''; // 工号
      ruleFormData.warehouseDate = res.injuryTime ? res.injuryTime.split('T')[0] : ''; // 受伤时间
      ruleFormData.status = res.status ? 'ENABLE' : 'DISABLE'; // 状态
      ruleFormData.remarks = res.injuryReason || ''; // 受伤原因
      ruleFormData.accidentCertUrl = res.accidentCertUrl || ''; // 事故报告
      ruleFormData.powerAttorneyUrl = res.powerAttorneyUrl || ''; // 委托书
      ruleFormData.addressConfirmUrl = res.addressConfirmUrl || ''; // 地址确认书
      ruleFormData.applicationFormUrl = res.applicationFormUrl || ''; // 申请表
      ruleFormData.idCardUrl = res.idCardUrl || ''; // 身份证正反面
      ruleFormData.laborContractUrl = res.laborContractUrl || ''; // 劳动合同
      ruleFormData.initialMedicalCertUrl = res.initialMedicalCertUrl || ''; // 初次医疗证明
      ruleFormData.trusteeIdCardUrl = res.trusteeIdCardUrl || ''; // 被委托人员身份证正反面
      ruleFormData.departmentCode = JSON.parse(res.departmentCode || '[]') || ''; // 部门编码
      ruleFormData.departmentName = res.departmentName || ''; // 添加这一行，设置部门名称
      ruleFormData.approvalTemplateId = res.templateId || ''; // 审批模板ID
      }
      cloneRuleFormData();
    } catch (e) {
      console.error('获取物品库存详情失败:', e);
      ElMessage.error('获取详情失败');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      const basePayload = {
        applicantName: ruleFormData.itemName,
        applicantCode: ruleFormData.applicantCode,
        injuryTime: ruleFormData.warehouseDate
          ? new Date(ruleFormData.warehouseDate).toISOString()
          : '',
        status: ruleFormData.status === 'ENABLE',
        injuryReason: ruleFormData.remarks || '',
        accidentCertUrl: ruleFormData.accidentCertUrl,
        powerAttorneyUrl: ruleFormData.powerAttorneyUrl,
        addressConfirmUrl: ruleFormData.addressConfirmUrl,
        applicationFormUrl: ruleFormData.applicationFormUrl,
        idCardUrl: ruleFormData.idCardUrl,
        laborContractUrl: ruleFormData.laborContractUrl,
        initialMedicalCertUrl: ruleFormData.initialMedicalCertUrl,
        trusteeIdCardUrl: ruleFormData.trusteeIdCardUrl,
        departmentName: ruleFormData.departmentName || '',
        departmentCode: ruleFormData.departmentCode || '',
        templateId: Number(ruleFormData.approvalTemplateId),
      };

      if (isCreateMode.value) {
        await saveBusinessInformation(basePayload).then((res)=>{
          newFormId.value = res || '';
        });
        ElMessage.success('创建成功');
        await getApprovalNode(Number(ruleFormData.approvalTemplateId));
        basicDialogRef.value.openDialog();
        return;
      } else if (isEditMode.value && currentId.value) {
        await updateWorkInjuryApply({
          id: currentId.value,
          ...basePayload,
        });
        ElMessage.success('保存成功');
        await getApprovalNode(Number(ruleFormData.approvalTemplateId));
        basicDialogRef.value.openDialog();
        return;
      }
      cloneRuleFormData();
      router.back();
    } catch (e) {
      console.error('保存物品库存失败:', e);
      ElMessage.error('保存失败，请重试');
    }
  };

  const handlePreview = (url: string) => {
    if (url) {
      // 根据文件扩展名判断文件类型
      const extension = url.split('.').pop()?.toLowerCase() || '';
      let fileType: 'pdf' | 'word' | 'excel' | 'ppt' = 'pdf';
      if (extension === 'doc' || extension === 'docx') {
        fileType = 'word';
      } else if (extension === 'xls' || extension === 'xlsx') {
        fileType = 'excel';
      } else if (extension === 'ppt' || extension === 'pptx') {
        fileType = 'ppt';
      }
      previewOnlineRef.value?.open(url, fileType);
    }
  };

   /** 附件 JSON [{file_name, url}] 转 FileItem 列表，供 UploadFiles 使用（新增/编辑/查看/审核统一展示） */
  function convertAttachmentJsonToFileItems(attachmentStr: string): FileItem[] {
    if (!attachmentStr || !String(attachmentStr).trim()) return [];
    try {
      const arr = JSON.parse(attachmentStr);
      if (!Array.isArray(arr)) return [];
      return arr.map((item: any, index: number) => {
        const fileName = item.file_name || item.fileName || `附件${index + 1}`;
        const url = item.url || item.fileUrl || '';
        const ext = (fileName || '').split('.').pop()?.toLowerCase() || '';
        let fileType = 'pdf';
        if (['doc', 'docx'].includes(ext)) fileType = 'word';
        else if (['xls', 'xlsx'].includes(ext)) fileType = 'excel';
        else if (['ppt', 'pptx'].includes(ext)) fileType = 'ppt';
        return { fileId: index + 1, fileName, fileType, fileSize: '0', fileUrl: url };
      });
    } catch {
      return [];
    }
  }

  const accidentCertUrl = computed(() => convertAttachmentJsonToFileItems(ruleFormData.accidentCertUrl || ''));
  const powerAttorneyUrl = computed(() => convertAttachmentJsonToFileItems(ruleFormData.powerAttorneyUrl || ''));
  const addressConfirmUrl = computed(() => convertAttachmentJsonToFileItems(ruleFormData.addressConfirmUrl || ''));
  const applicationFormUrl = computed(() => convertAttachmentJsonToFileItems(ruleFormData.applicationFormUrl || ''));
  const idCardUrl = computed(() => convertAttachmentJsonToFileItems(ruleFormData.idCardUrl || ''));
  const laborContractUrl = computed(() => convertAttachmentJsonToFileItems(ruleFormData.laborContractUrl || ''));
  const initialMedicalCertUrl = computed(() => convertAttachmentJsonToFileItems(ruleFormData.initialMedicalCertUrl || ''));
  const trusteeIdCardUrl = computed(() => convertAttachmentJsonToFileItems(ruleFormData.trusteeIdCardUrl || ''));

  async function handleAccidentReportUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.accidentCertUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || []).map((r) => ({
        fileName: r.fileName,
        fileId: r.fileId || '',
        fileSize: r.fileSize || '',
        fileType: r.fileType || '',
        fileUrl: r.fileUrl || '',
      })).filter((x) => x.fileId);
      ruleFormData.accidentCertUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('事故报告上传失败:', e);
      ElMessage.error(e?.message || e?.data || '事故报告上传失败，请重试');
    }
  }

  async function handlePowerOfAttorneyUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.powerAttorneyUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || []).map((r) => ({
        fileName: r.fileName,
        fileId: r.fileId || '',
        fileSize: r.fileSize || '',
        fileType: r.fileType || '',
        fileUrl: r.fileUrl || '',
      })).filter((x) => x.fileId);
      ruleFormData.powerAttorneyUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('委托书上传失败:', e);
      ElMessage.error(e?.message || e?.data || '委托书上传失败，请重试');
    }
  }

  async function handleAddressConfirmationUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.addressConfirmUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || []).map((r) => ({
        file_name: r.fileName,
        fileId: r.fileId || '',
        fileSize: r.fileSize || '',
        fileType: r.fileType || '',
        fileUrl: r.fileUrl || '',
      })).filter((x) => x.fileId);
      ruleFormData.addressConfirmUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('地址确认书上传失败:', e);
      ElMessage.error(e?.message || e?.data || '地址确认书上传失败，请重试');
    }
  }

  async function handleApplicationFormUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.applicationFormUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || []).map((r) => ({
        file_name: r.fileName,
        fileId: r.fileId || '',
        fileSize: r.fileSize || '',
        fileType: r.fileType || '',
        fileUrl: r.fileUrl || '',
      })).filter((x) => x.fileId);
      ruleFormData.applicationFormUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('申请表上传失败:', e);
      ElMessage.error(e?.message || e?.data || '申请表上传失败，请重试');
    }
  }

  async function handleIdCardUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.idCardUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || []).map((r) => ({
        fileName: r.fileName,
        fileId: r.fileId || '',
        fileSize: r.fileSize || '',
        fileType: r.fileType || '',
        fileUrl: r.fileUrl || '',
      })).filter((x) => x.fileId);
      ruleFormData.idCardUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('身份证正反面上传失败:', e);
      ElMessage.error(e?.message || e?.data || '身份证正反面上传失败，请重试');
    }
  }

  async function handleLaborContractUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.laborContractUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || []).map((r) => ({
        file_name: r.fileName,
        fileId: r.fileId || '',
        fileSize: r.fileSize || '',
        fileType: r.fileType || '',
        fileUrl: r.fileUrl || '',
      })).filter((x) => x.fileId);
      ruleFormData.laborContractUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('劳动合同上传失败:', e);
      ElMessage.error(e?.message || e?.data || '劳动合同上传失败，请重试');
    }
  }

  async function handleInitialMedicalCertificateUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.initialMedicalCertUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || []).map((r) => ({
        file_name: r.fileName,
        fileId: r.fileId || '',
        fileSize: r.fileSize || '',
        fileType: r.fileType || '',
        fileUrl: r.fileUrl || '',
      })).filter((x) => x.fileId);
      ruleFormData.initialMedicalCertUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('初次医疗证明上传失败:', e);
      ElMessage.error(e?.message || e?.data || '初次医疗证明上传失败，请重试');
    }
  }

  async function handleAgentIdCardUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.trusteeIdCardUrl = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || []).map((r) => ({
        file_name: r.fileName,
        fileId: r.fileId || '',
        fileSize: r.fileSize || '',
        fileType: r.fileType || '',
        fileUrl: r.fileUrl || '',
      })).filter((x) => x.fileId);
      ruleFormData.trusteeIdCardUrl = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('被委托人员身份证正反面上传失败:', e);
      ElMessage.error(e?.message || e?.data || '被委托人员身份证正反面上传失败，请重试');
    }
  }

  const getDeptData = () => {
    getAllDepartments().then((res) => {
      firstLevelDepts.value = formatDeptTree(res);
    });
  };

  const handleChangeDept = () => {
    const deptInfo = cascaderRef.value?.getCheckedNodes();
    if (deptInfo?.[0]) {
      ruleFormData.departmentName = deptInfo[0].label;
      ruleFormData.departmentCode = deptInfo[0].pathValues;
    }
  };

  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 = {
          id: currentId.value || newFormId.value || '',
          templateId: ruleFormData.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();
        cloneRuleFormData();
        router.back();
      }
    });
  };

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

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

  const previewOnline = (url: string | undefined, type) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };

  onMounted(() => {
    cloneRuleFormData();
    beforeRouteLeave();
    getDeptData();
    getApprovalList();
    if (isEditMode.value || isViewMode.value || isAuditMode.value) {
      getDetail();
    }
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  .detail-reject-alert{
    margin-bottom: 20px;
  }
</style>