<template>
  <div class="p-2">
    <!-- 搜索区域 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="企业登记注册类型" prop="supplierType" label-width="140px">
              <el-select v-model="queryParams.supplierType" placeholder="请选择类型" clearable>
                <el-option label="劳务" value="劳务"></el-option>
                <el-option label="技术服务" value="技术服务"></el-option>
                <el-option label="物资设备" value="物资设备"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业名称" prop="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="请输入企业名称" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 列表及操作区域 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['supplierInput:supplierInput:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport" v-hasPermi="['supplierInput:supplierInput:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['supplierInput:supplierInput:export']"
              >导出模板</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="supplierInputList" @selection-change="handleSelectionChange" border>
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column label="企业登记注册类型" align="center" prop="supplierType" width="140" />
        <el-table-column label="企业名称" align="center" prop="supplierName" width="180" />
        <el-table-column label="法定代表人" align="center" prop="supplierPerson" width="120" />
        <el-table-column label="统一社会信用代码" align="center" prop="supplierCode" width="180" />
        <el-table-column label="负责人" align="center" prop="personName" width="100" />
        <el-table-column label="负责人电话" align="center" prop="personPhone" width="120" />
        <el-table-column label="纳税规模" align="center" prop="taxScale" width="120" />
        <el-table-column label="资质等级" align="center" prop="supplierLivel" width="120" />
        <el-table-column label="流程状态" align="center">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="入库资料" align="center" prop="inputFile" width="120">
          <template #default="scope">
            <el-link v-if="scope.row.inputFile" :href="scope.row.inputFile" target="_blank" :style="{ textDecoration: 'none', color: '#409eff' }">
              查看文件
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="240">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['supplierInput:supplierInput:edit']"
              >修改</el-button
            >
            <el-button link type="primary" icon="edit" @click="handleAudit(scope.row)" v-if="scope.row.state == 'draft' || scope.row.state == 'back'"
              >审核</el-button
            >
            <el-button link type="primary" icon="View" v-if="scope.row.state != '2' && scope.row.state != 'draft'" @click="handleAuditView(scope.row)"
              >查看流程</el-button
            >
            <!-- <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['supplierInput:supplierInput:remove']"
            ></el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 新增/修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="950px" append-to-body>
      <el-form ref="supplierInputFormRef" :model="form" :rules="rules" label-width="200px">
        <!-- 第一行：基础信息（2列布局） -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="企业登记注册类型" prop="supplierType">
              <el-select v-model="form.supplierType" placeholder="请选择供应商类型" @change="handleTypeChange">
                <el-option label="劳务" value="劳务"></el-option>
                <el-option label="技术服务" value="技术服务"></el-option>
                <el-option label="物资设备" value="物资设备"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入企业名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：企业信息 -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="企业法定代表人" prop="supplierPerson">
              <el-input v-model="form.supplierPerson" placeholder="请输入法定代表人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="supplierCode">
              <el-input v-model="form.supplierCode" placeholder="请输入统一社会信用代码" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：地址与联系人 -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="企业注册地址" prop="supplierAddres">
              <el-input v-model="form.supplierAddres" placeholder="请输入注册地址" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人姓名" prop="personName">
              <el-input v-model="form.personName" placeholder="请输入负责人姓名" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：联系电话与纳税规模 -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="负责人联系电话" prop="personPhone">
              <el-input v-model="form.personPhone" placeholder="请输入联系电话" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纳税规模" prop="taxScale">
              <el-select v-model="form.taxScale" placeholder="请选择纳税规模">
                <el-option label="一般纳税人" value="一般纳税人"></el-option>
                <el-option label="小规模纳税人" value="小规模纳税人"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：银行信息 -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="开户行户名" prop="bankPersonName">
              <el-input v-model="form.bankPersonName" placeholder="请输入开户行户名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户银行" prop="bankName">
              <el-input v-model="form.bankName" placeholder="请输入开户银行" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行：银行账号与经营范围 -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="开户行账号" prop="bankAccount">
              <el-input v-model="form.bankAccount" placeholder="请输入开户行账号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经营范围" prop="scope">
              <el-input v-model="form.scope" placeholder="请输入经营范围" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第七行：企业资质 -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="企业资质等级" prop="supplierLivel">
              <el-input v-model="form.supplierLivel" placeholder="请输入资质等级" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发证日期" prop="issueDate">
              <el-date-picker v-model="form.issueDate" type="date" placeholder="请选择发证日期" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第八行：证书有效期与营业额 -->
        <el-row :gutter="20" class="mb-4">
          <el-col :span="12">
            <el-form-item label="证书有效期" prop="certificateValidity">
              <el-date-picker v-model="form.certificateValidity" type="date" placeholder="请选择证书有效期" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="近三年营业额" prop="pastThreeYears">
              <el-input v-model="form.pastThreeYears" placeholder="请输入近三年营业额" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第九行：安全生产许可证（仅劳务类型显示） -->
        <el-row :gutter="20" class="mb-4" v-if="form.supplierType === '劳务'">
          <el-col :span="12">
            <el-form-item label="安全生产许可证编号" prop="safeCode">
              <el-input v-model="form.safeCode" placeholder="请输入许可证编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安全生产许可证发证日期" prop="safeCodeData">
              <el-date-picker v-model="form.safeCodeData" type="date" placeholder="请选择发证日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第十行：安全生产许可证有效期（仅劳务类型显示） -->
        <el-row :gutter="20" class="mb-4" v-if="form.supplierType === '劳务'">
          <el-col :span="12">
            <el-form-item label="安全生产许可证有效期" prop="safeCertificateValidity">
              <el-date-picker v-model="form.safeCertificateValidity" type="date" placeholder="请选择有效期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列占位 -->
          </el-col>
        </el-row>
        <!-- 第十一行：注册人员数量（仅劳务类型显示） -->
        <el-row :gutter="20" class="mb-4" v-if="form.supplierType === '劳务'">
          <el-col :span="12">
            <el-form-item label="一建建造师" prop="firstBuildingNumber">
              <el-input v-model="form.firstBuildingNumber" placeholder="请输入一建建造师数量" clearable />
            </el-form-item>
            <el-form-item label="二建建造师" prop="secondBuildingNumber">
              <el-input v-model="form.secondBuildingNumber" placeholder="请输入二建建造师数量" clearable />
            </el-form-item>
            <el-form-item label="注册造价工程师" prop="registeredEngineerNumber">
              <el-input v-model="form.registeredEngineerNumber" placeholder="请输入注册造价工程师数量" clearable />
            </el-form-item>
            <el-form-item label="其他人员数量" prop="otherBuildingNumber">
              <el-input v-model="form.otherBuildingNumber" placeholder="请输入其他人员数量" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列占位 -->
          </el-col>
        </el-row>
        <!-- 第十二行：职称人员数量（仅劳务类型显示） -->
        <el-row :gutter="20" class="mb-4" v-if="form.supplierType === '劳务'">
          <el-col :span="12">
            <el-form-item label="高级工程师人数" prop="seniorEngineerNumber">
              <el-input v-model="form.seniorEngineerNumber" placeholder="请输高级工程师数量" clearable />
            </el-form-item>
            <el-form-item label="工程师数量" prop="engineerNumber">
              <el-input v-model="form.engineerNumber" placeholder="请输入工程师数量" clearable />
            </el-form-item>
            <el-form-item label="助理工程师数量" prop="assistantEngineerNumber">
              <el-input v-model="form.assistantEngineerNumber" placeholder="请输入助理工程师数量" clearable />
            </el-form-item>
            <el-form-item label="其他人员数量" prop="otherPersonnelNumber">
              <el-input v-model="form.otherPersonnelNumber" placeholder="请输入其他人员数量" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列占位 -->
          </el-col>
        </el-row>
        <!-- 第十四行：入库资料上传 -->
        <el-row class="mb-4">
          <el-col :span="24">
            <el-form-item label="入库资料" prop="inputFile">
              <template #label> <span class="text-red">*</span> 入库资料 </template>
              <file-upload
                v-model="form.fileId"
                :fileType="['doc', 'docx', 'pdf']"
                :autoUpload="false"
                ref="fileUploadRef"
                :method="form.id ? 'put' : 'post'"
                :data="form"
                uploadUrl="/supplierInput/supplierInput"
                :limit="1"
                @handleChange="handleFileChange"
                @handleRemove="handleFileRemove"
                showFileList
              >
                <div><el-button type="primary">上传文件</el-button><br /></div>
              </file-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SupplierInput" lang="ts">
import { ComponentInternalInstance, getCurrentInstance, onMounted, ref, reactive, toRefs, computed } from 'vue';
import { ElFormInstance } from 'element-plus';
import {
  listSupplierInput,
  getSupplierInput,
  delSupplierInput,
  updateSupplierInput,
  leadingIn,
  leadingOut
} from '@/api/supplierInput/supplierInput/index';
import { SupplierInputVO, SupplierInputQuery, SupplierInputForm, PageData, DialogOption } from '@/api/supplierInput/supplierInput/types';
import Pagination from '@/components/Pagination/index.vue';
import RightToolbar from '@/components/RightToolbar/index.vue';
import FileUpload from '@/components/FileUpload/index.vue';
import { useUserStoreHook } from '@/store/modules/user';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status'));
// 组件引用
const fileUploadRef = ref<InstanceType<typeof FileUpload> | null>(null);
const queryFormRef = ref<ElFormInstance>();
const supplierInputFormRef = ref<ElFormInstance>();
// 获取用户 store
const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
// 基础数据
const supplierInputList = ref<SupplierInputVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const fileUrl = ref('');

// 对话框配置
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 初始化表单数据：新增build1-build4、personnelNumber1-personnelNumber4字段（用于拆分拼接字符串）
const initFormData: any = {
  id: undefined,
  supplierType: undefined,
  supplierName: undefined,
  supplierPerson: undefined,
  supplierCode: undefined,
  supplierAddres: undefined,
  personName: undefined,
  personPhone: undefined,
  bankPersonName: undefined,
  bankName: undefined,
  bankAccount: undefined,
  taxScale: undefined,
  scope: undefined,
  supplierLivel: undefined,
  issueDate: undefined,
  certificateValidity: undefined,
  pastThreeYears: undefined,
  safeCode: undefined,
  safeCodeData: undefined,
  safeCertificateValidity: undefined,
  registeredNumber: undefined, // 后端返回的拼接字符串（如“1,2,3,4”）
  personnelNumber: undefined, // 后端返回的拼接字符串（如“5,6,7,8”）
  fileId: undefined,
  inputFile: undefined,
  // state: '0', // 新增默认待审核
  // 新增：用于表单输入的单独字段
  firstBuildingNumber: undefined, // 一建建造师
  secondBuildingNumber: undefined, // 二建建造师
  registeredEngineerNumber: undefined, // 注册造价工程师
  otherBuildingNumber: undefined, // 其他注册人员
  seniorEngineerNumber: undefined, // 高级工程师
  engineerNumber: undefined, // 工程师
  assistantEngineerNumber: undefined, // 助理工程师
  otherPersonnelNumber: undefined // 其他职称人员
};
// 核心数据（表单+查询参数）
const data = reactive<PageData<SupplierInputForm, SupplierInputQuery>>({
  form: { ...initFormData },
  queryParams: {
    projectId: currentProject.value?.id,
    pageNum: 1,
    pageSize: 10,
    supplierType: undefined,
    supplierName: undefined,
    state: undefined,
    inputFile: undefined,
    registeredNumber: undefined,
    personnelNumber: undefined,
    params: {}
  }
});

// 解构响应式数据
const { queryParams, form } = toRefs(data);

// 动态验证规则：仅劳务类型需要校验【安全生产许可证+人员数量】字段
const rules = computed(() => {
  const baseRules = {
    supplierType: [{ required: true, message: '请选择企业登记注册类型', trigger: 'change' }],
    supplierName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
    supplierPerson: [{ required: true, message: '请输入法定代表人', trigger: 'blur' }],
    supplierCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
    personName: [{ required: true, message: '请输入负责人姓名', trigger: 'blur' }],
    personPhone: [
      { required: true, message: '请输入负责人联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    firstBuildingNumber: [{ required: true, message: '请输入一建建造师数量', trigger: 'change' }],
    secondBuildingNumber: [{ required: true, message: '请输入二建建造师数量', trigger: 'change' }],
    registeredEngineerNumber: [{ required: true, message: '请输入注册造价工程师数量', trigger: 'change' }],
    otherBuildingNumber: [{ required: true, message: '请输入其他数量', trigger: 'change' }],
    seniorEngineerNumber: [{ required: true, message: '请输入高级工程师数量', trigger: 'change' }],
    engineerNumber: [{ required: true, message: '请输入工程师数量', trigger: 'change' }],
    assistantEngineerNumber: [{ required: true, message: '请输入助理工程师数量', trigger: 'change' }],
    otherPersonnelNumber: [{ required: true, message: '请输入其他数量', trigger: 'change' }]
  };

  // 仅当类型为"劳务"时，添加安全生产许可证+人员数量校验
  if (form.value.supplierType === '劳务') {
    return {
      ...baseRules,
      // 安全生产许可证相关校验
      safeCode: [{ required: true, message: '请输入安全生产许可证编号', trigger: 'blur' }],
      safeCodeData: [{ required: true, message: '请选择安全生产许可证发证日期', trigger: 'change' }],
      safeCertificateValidity: [{ required: true, message: '请选择安全生产许可证有效期', trigger: 'change' }],
      // 注册人员数量校验
      firstBuildingNumber: [{ required: true, message: '请输入一建建造师数量', trigger: 'blur' }],
      secondBuildingNumber: [{ required: true, message: '请输入二建建造师数量', trigger: 'blur' }],
      registeredEngineerNumber: [{ required: true, message: '请输入注册造价工程师数量', trigger: 'blur' }],
      otherBuildingNumber: [{ required: true, message: '请输入其他注册人员数量', trigger: 'blur' }],
      // 职称人员数量校验
      seniorEngineerNumber: [{ required: true, message: '请输入高级工程师数量', trigger: 'blur' }],
      engineerNumber: [{ required: true, message: '请输入工程师数量', trigger: 'blur' }],
      assistantEngineerNumber: [{ required: true, message: '请输入助理工程师数量', trigger: 'blur' }],
      otherPersonnelNumber: [{ required: true, message: '请输入其他职称人员数量', trigger: 'blur' }]
    };
  }

  return baseRules;
});

/** 企业类型变更时的处理：清空隐藏字段数据+重置校验 */
const handleTypeChange = () => {
  // 非劳务类型：清空安全生产许可证+人员数量字段
  if (form.value.supplierType !== '劳务') {
    form.value.safeCode = undefined;
    form.value.safeCodeData = undefined;
    form.value.safeCertificateValidity = undefined;
    form.value.registeredNumber = undefined;
    form.value.personnelNumber = undefined;
    // 清空表单单独字段
    form.value.firstBuildingNumber =
      form.value.secondBuildingNumber =
      form.value.registeredEngineerNumber =
      form.value.otherBuildingNumber =
        undefined;
    form.value.seniorEngineerNumber = form.value.engineerNumber = form.value.assistantEngineerNumber = form.value.otherPersonnelNumber = undefined;
  }
  // 重置隐藏字段的校验状态，避免错误提示残留
  supplierInputFormRef.value?.clearValidate([
    'safeCode',
    'safeCodeData',
    'safeCertificateValidity',
    'firstBuildingNumber',
    'secondBuildingNumber',
    'registeredEngineerNumber',
    'otherBuildingNumber',
    'seniorEngineerNumber',
    'engineerNumber',
    'assistantEngineerNumber',
    'otherPersonnelNumber'
  ]);
};

/** 查询供应商入库列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listSupplierInput(queryParams.value);
    supplierInputList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    proxy?.$modal.msgError('查询失败，请重试');
  } finally {
    loading.value = false;
  }
};

/** 取消操作 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置：清空所有字段 */
const reset = () => {
  form.value = { ...initFormData, projectId: currentProject.value?.id };
  fileUrl.value = '';
  form.value.inputFile = '';
  supplierInputFormRef.value?.resetFields();
};

/** 搜索操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置搜索 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const splitBackEndStrToForm = (resData: any) => {
  if (resData.registeredNumber) {
    const registeredArr = resData.registeredNumber.split(',');
    form.value.firstBuildingNumber = registeredArr[0] || undefined; // 一建建造师
    form.value.secondBuildingNumber = registeredArr[1] || undefined; // 二建建造师
    form.value.registeredEngineerNumber = registeredArr[2] || undefined; // 注册造价工程师
    form.value.otherBuildingNumber = registeredArr[3] || undefined; // 其他注册人员
  }

  if (resData.personnelNumber) {
    const personnelArr = resData.personnelNumber.split(',');
    form.value.seniorEngineerNumber = personnelArr[0] || undefined; // 高级工程师
    form.value.engineerNumber = personnelArr[1] || undefined; // 工程师
    form.value.assistantEngineerNumber = personnelArr[2] || undefined; // 助理工程师
    form.value.otherPersonnelNumber = personnelArr[3] || undefined; // 其他职称人员
  }
};
/** 审核过程按钮操作 */
const handleAudit = async (row) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/approval/supplierInput/indexEdit`,
    query: {
      id: row.id,
      type: 'update'
    }
  });
};
/** 查看按钮操作 */
const handleAuditView = async (row) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/approval/supplierInput/indexEdit`,
    query: {
      id: row.id,
      type: 'view'
    }
  });
};
/** 文件选择变更 */
const change = () => {
  fileUrl.value = '';
};

/** 表格多选回调 */
const handleSelectionChange = (selection: SupplierInputVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

/** 新增操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加供应商入库';
};

const editFileId = ref('');
const handleUpdate = async (row?: SupplierInputVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  if (!_id) return proxy?.$modal.msgWarning('请选择需要修改的数据');

  try {
    const res = await getSupplierInput(_id);
    const resData: any = res.data || {};
    editFileId.value = resData.fileId;
    // 1. 基础字段回显
    form.value = { ...form.value, ...resData, inputFile: '' };
    // 2. 核心修复：拆分后端拼接字符串到表单单独字段
    splitBackEndStrToForm(resData);
    // 3. 文件地址回显
    fileUrl.value = resData.inputFile || '';
    // 4. 打开对话框
    dialog.visible = true;
    dialog.title = '修改供应商入库';
  } catch (error) {
    proxy?.$modal.msgError('获取数据失败，请重试');
  }
};

const fileStatus = ref(false);
const updateFileStatus = ref(true);
const isUpdateFile = ref(false); //记录是否在修改页面时是否有新上传的文件
const handleFileChange = (file, fileList) => {
  if (form.value.id) {
    updateFileStatus.value = true;
    isUpdateFile.value = true; //记录是否在修改页面时是否有新上传的文件
  }
  fileStatus.value = true;
};

const handleFileRemove = (file, fileList) => {
  if (form.value.id) {
    updateFileStatus.value = false;
    isUpdateFile.value = false; //记录是否在修改页面时是否有新上传的文件
  }

  fileStatus.value = false;
};
/** 提交表单 */
const submitForm = () => {
  supplierInputFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    if (form.value.supplierType === '劳务') {
      form.value.registeredNumber = [
        form.value.firstBuildingNumber,
        form.value.secondBuildingNumber,
        form.value.registeredEngineerNumber,
        form.value.otherBuildingNumber
      ].join(',');
      form.value.personnelNumber = [
        form.value.seniorEngineerNumber,
        form.value.engineerNumber,
        form.value.assistantEngineerNumber,
        form.value.otherPersonnelNumber
      ].join(',');
    }
    buttonLoading.value = true;
    try {
      if (fileUploadRef.value) {
        if (form.value.fileId === editFileId.value && !isUpdateFile.value) {
          console.log(1111111111);

          editFormData();
        } else {
          fileUploadRef.value.submitUpload().then((res) => {
            if (res == 'noFile') {
              proxy?.$modal.msgError('请上传文件');
              return;
            }
            proxy?.$modal.msgSuccess('操作成功');
            dialog.visible = false;
            getList();
          });
        }
      }
    } catch (error) {
      proxy?.$modal.msgError('提交失败，请重试');
    } finally {
      buttonLoading.value = false;
    }
  });
};
const editFormData = async () => {
  const res = await updateSupplierInput(form.value);
  if ((res.code = 200)) {
    proxy?.$modal.msgSuccess('操作成功');
    dialog.visible = false;
    getList();
  }
};
/** 删除操作 */
const handleDelete = async (row?: SupplierInputVO) => {
  const _ids = row?.id || ids.value;
  if (!_ids || (Array.isArray(_ids) && _ids.length === 0)) {
    return proxy?.$modal.msgWarning('请选择需要删除的数据');
  }

  try {
    await proxy?.$modal.confirm(`是否确认删除供应商入库编号为"${_ids}"的数据项？`);
    await delSupplierInput(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    getList();
  } catch (error) {
    proxy?.$modal.msgError('删除失败，请重试');
  }
};

/** 导出操作 */
const handleExport = () => {
  try {
    // 创建a标签并直接下载public目录下的静态文件
    const link = document.createElement('a');
    link.href = '/xx.xlsx';
    link.download = '供应商导入模板.xlsx';
    document.body.appendChild(link);
    link.click();
    // 清理DOM元素
    setTimeout(() => {
      document.body.removeChild(link);
    }, 100);
  } catch (error) {
    proxy?.$modal.msgError('模板下载失败，请重试');
  }
};

/** 导入操作 */
const handleImport = () => {
  // 创建一个隐藏的input[type=file]元素
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xlsx,.xls'; // 限定只能导入excel文件
  input.style.display = 'none';

  // 监听文件选择事件
  input.onchange = async (e: Event) => {
    const target = e.target as HTMLInputElement;
    const file = target.files?.[0];

    if (file) {
      // 检查文件类型是否为Excel
      const isValidType = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
      if (!isValidType) {
        proxy?.$modal.msgError('请选择Excel文件(.xlsx或.xls)');
        return;
      }

      // 创建FormData并添加文件
      const formData = new FormData();
      formData.append('file', file);

      try {
        // 显示加载状态
        loading.value = true;
        // 调用导入接口
        const res = await leadingIn(formData, queryParams.value.projectId);
        console.log('111111111111', queryParams.value.projectId);

        if (res.code === 200) {
          proxy?.$modal.msgSuccess('导入成功');
          // 刷新列表
          getList();
        } else {
          proxy?.$modal.msgError(res.msg || '导入失败');
        }
      } catch (error) {
        proxy?.$modal.msgError('导入失败，请重试');
      } finally {
        loading.value = false;
      }
    }

    // 清除input元素
    input.remove();
  };

  // 触发文件选择对话框
  document.body.appendChild(input);
  input.click();
};
//调用projectId并获取列表
onMounted(() => {
  // 若需要依赖项目ID，可先判断项目是否已选中，再调用接口
  if (currentProject.value?.id) {
    queryParams.value.projectId = currentProject.value.id;
    form.value.projectId = currentProject.value.id;
    getList(); // 首次进入自动调取listSupplierInput接口
  } else {
    // 若项目未选中，可提示或后续监听项目变化时再加载（已有监听逻辑）
    getList();
  }
});
// 监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid, oid) => {
    queryParams.value.projectId = nid;
    form.value.projectId = nid;
    getList();
  }
);
onUnmounted(() => {
  listeningProject();
});
</script>

<style scoped lang="scss">
/* 文件上传样式 */
.upload-file-list {
  margin: 0;
  .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 0;
    position: relative;
  }
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

/* PDF预览样式（若有） */
.pdf {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 6px;
  position: relative;
  width: 100%;
  img {
    width: 40%;
  }
  &:hover {
    .Shadow {
      opacity: 1;
    }
  }
  > span {
    width: 100%;
  }
}

.Shadow {
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  cursor: default;
  display: inline-flex;
  font-size: 20px;
  height: 100%;
  justify-content: center;
  left: 0;
  opacity: 0;
  position: absolute;
  top: 0;
  transition: opacity 0.3s;
  width: 100%;
  z-index: 1;
}

/* 头像上传样式（备用） */
.el-icon.avatar-uploader-icon {
  border: 1px dashed #cdd0d6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.3s;
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 178px;
  text-align: center;
  &:hover {
    border-color: #409eff;
  }
}

/* 表格操作列样式 */
.small-padding {
  padding: 0 5px;
}

.fixed-width {
  width: 120px;
}

/* 行间距调整 */
.mb8 {
  margin-bottom: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>
