<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" label-width="100px">
            <el-form-item label="供应商编号" prop="supplierNo">
              <el-input v-model="queryParams.supplierNo" placeholder="供应商编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商名称" prop="enterpriseName">
              <el-input v-model="queryParams.enterpriseName" placeholder="供应商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商类型" prop="supplierType">
              <el-select v-model="queryParams.supplierType" placeholder="请选择供应商类型" clearable>
                <el-option v-for="item in supplierTypeList" :key="item.id" :label="item.supplierTypeName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="供应品牌" prop="operatingBrand">
              <el-input v-model="queryParams.operatingBrand" placeholder="供应品牌" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应类别" prop="operatingCategory">
              <el-select v-model="queryParams.operatingCategory" placeholder="请选择供应类别" clearable>
                <el-option v-for="item in productCategoryList" :key="item.id" :label="item.categoryName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="供应区域" prop="province">
              <el-input v-model="queryParams.province" placeholder="供应区域（省）" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应区域" prop="city">
              <el-input v-model="queryParams.city" placeholder="供应区域（市）" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品经理" prop="productManager">
              <el-select v-model="queryParams.productManager" placeholder="请选择产品经理" clearable>
                <el-option v-for="item in comStaffList" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
              </el-select>
            </el-form-item>
            <el-form-item label="采购人员" prop="buyer">
              <el-select v-model="queryParams.buyer" placeholder="请选择采购人员" clearable>
                <el-option v-for="item in comStaffList" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
              </el-select>
            </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-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="infoList" class="no-resize-table" @selection-change="handleSelectionChange">
        <el-table-column label="编号" align="center" prop="supplierNo" width="150" fixed="left" />
        <el-table-column label="名称" align="left" prop="enterpriseName" fixed="left" />
        <el-table-column label="注册时间" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="企业规模" align="center" prop="enterpriseScaleName"> </el-table-column>
        <el-table-column label="采销经理" align="center" prop="productManager" />
        <el-table-column label="产品专员" align="center" prop="buyer" />
        <el-table-column label="类型" align="center" prop="buyer" />
        <!-- 类型:新增/更新 -->

        <!-- <el-table-column label="经营类目" align="center" prop="operatingCategory" width="150" />
        <el-table-column label="供应品牌" align="center" prop="brandName" width="200" />
        <el-table-column label="供应区域（省）" align="left" prop="province" width="250">
          <template #default="scope">
            <el-tooltip
              :content="scope.row.province"
              placement="top"
              :disabled="!scope.row.province || scope.row.province.split(',').filter((p) => p.trim()).length <= 3"
            >
              <span>{{ formatProvinceDisplay(scope.row.province) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="供应区域（市）" align="left" prop="city" width="300">
          <template #default="scope">
            <el-tooltip
              :content="scope.row.city"
              placement="top"
              :disabled="!scope.row.city || scope.row.city.split(',').filter((c) => c.trim()).length <= 10"
            >
              <span>{{ formatCityDisplay(scope.row.city) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="合同到期时间" align="center" prop="contractEndTime" width="180" />

        <el-table-column label="合作情况" align="center" prop="cooperative" width="120">
          <template #default="scope">
            <span>{{ getCooperationStatusDisplayName(scope.row.cooperative) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="审核状态" align="center" prop="supplyStatus" width="180">
          <template #default="scope">
            <span>{{ getStatusDisplayName(scope.row.supplyStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
          <template #default="scope">
            <!-- 状态 0、3、4：待审核、审核未通过、待修改审核 -->
            <template
              v-if="
                scope.row.supplyStatus === '0' ||
                scope.row.supplyStatus === 0 ||
                scope.row.supplyStatus === '4' ||
                scope.row.supplyStatus === 4
              "
            >
              <el-button link type="primary" @click="handleView(scope.row)" v-hasPermi="['customer:info:query']">查看</el-button>
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['customer:info:edit']">编辑</el-button>
              <el-button link type="primary" @click="handleApprove(scope.row)" v-hasPermi="['customer:info:edit']">审核通过</el-button>
              <el-button link type="danger" @click="handleReject(scope.row)" v-hasPermi="['customer:info:edit']">驳回</el-button>
            </template>

            <!-- 状态 1：正式供应商 -->
            <template v-else-if="scope.row.supplyStatus === '1' || scope.row.supplyStatus === 1">
              <el-button link type="primary" @click="handleView(scope.row)" v-hasPermi="['customer:info:query']">查看</el-button>
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['customer:info:edit']">编辑</el-button>
              <el-button link type="primary" @click="handleStopCooperation(scope.row)" v-hasPermi="['customer:info:edit']">停止合作</el-button>
            </template>

            <!-- 状态 2：停用 -->
            <template v-else-if="scope.row.supplyStatus === '2' || scope.row.supplyStatus === 2">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['customer:info:edit']">编辑</el-button>
              <el-button link type="primary" @click="handleResumeCooperation(scope.row)" v-hasPermi="['customer:info:edit']">恢复合作</el-button>
            </template>
            <!-- 状态 未通过 -->
            <template v-else-if="scope.row.supplyStatus === '3' || scope.row.supplyStatus === 3">
              <el-button link type="primary" @click="handleView(scope.row)" v-hasPermi="['customer:info:query']">查看</el-button>
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['customer:info:edit']">编辑</el-button>
            </template>
          </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="500px" append-to-body>
      <el-form ref="infoFormRef" :model="form" :rules="rules" label-width="80px" :disabled="dialog.readonly">
        <el-form-item label="供应商编号" prop="supplierNo">
          <el-input v-model="form.supplierNo" placeholder="请输入供应商编号" />
        </el-form-item>
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="人员规模" prop="membershipSize">
          <el-input v-model="form.membershipSize" placeholder="请输入人员规模" />
        </el-form-item>
        <el-form-item label="固定电话" prop="fixedPhone">
          <el-input v-model="form.fixedPhone" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="传真" prop="fax">
          <el-input v-model="form.fax" placeholder="请输入传真" />
        </el-form-item>
        <el-form-item label="网址" prop="url">
          <el-input v-model="form.url" placeholder="请输入网址" />
        </el-form-item>
        <el-form-item label="邮政编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入邮政编码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="mailbox">
          <el-input v-model="form.mailbox" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="办公地址-省" prop="officeProvince">
          <el-input v-model="form.officeProvince" placeholder="请输入办公地址-省" />
        </el-form-item>
        <el-form-item label="办公地址-市" prop="officeCity">
          <el-input v-model="form.officeCity" placeholder="请输入办公地址-市" />
        </el-form-item>
        <el-form-item label="办公地址-区/县" prop="officeCounty">
          <el-input v-model="form.officeCounty" placeholder="请输入办公地址-区/县" />
        </el-form-item>
        <el-form-item label="办公详细地址" prop="officeAddress">
          <el-input v-model="form.officeAddress" placeholder="请输入办公详细地址" />
        </el-form-item>
        <el-form-item label="营业执照名称" prop="businessName">
          <el-input v-model="form.businessName" placeholder="请输入营业执照名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="socialCreditCode">
          <el-input v-model="form.socialCreditCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="法人姓名" prop="legalPersonName">
          <el-input v-model="form.legalPersonName" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item label="法人身份证号" prop="legalPersonId">
          <el-input v-model="form.legalPersonId" placeholder="请输入法人身份证号" />
        </el-form-item>
        <el-form-item label="注册资本" prop="registeredCapital">
          <el-input v-model="form.registeredCapital" placeholder="请输入注册资本" />
        </el-form-item>
        <el-form-item label="注册地址-省" prop="businessProvince">
          <el-input v-model="form.businessProvince" placeholder="请输入注册地址-省" />
        </el-form-item>
        <el-form-item label="注册地址-市" prop="businessCity">
          <el-input v-model="form.businessCity" placeholder="请输入注册地址-市" />
        </el-form-item>
        <el-form-item label="注册地址-区/县" prop="businessCounty">
          <el-input v-model="form.businessCounty" placeholder="请输入注册地址-区/县" />
        </el-form-item>
        <el-form-item label="注册详细地址" prop="businessAddress">
          <el-input v-model="form.businessAddress" placeholder="请输入注册详细地址" />
        </el-form-item>
        <el-form-item label="营业执照图片路径" prop="businessLicense">
          <el-input v-model="form.businessLicense" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="发票抬头" prop="invoiceHeader">
          <el-input v-model="form.invoiceHeader" placeholder="请输入发票抬头" />
        </el-form-item>
        <el-form-item label="纳税人识别号" prop="taxpayerIdentifier">
          <el-input v-model="form.taxpayerIdentifier" placeholder="请输入纳税人识别号" />
        </el-form-item>
        <el-form-item label="开户银行" prop="depositaryBank">
          <el-input v-model="form.depositaryBank" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item label="行号" prop="rowNum">
          <el-input v-model="form.rowNum" placeholder="请输入行号" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccounts">
          <el-input v-model="form.bankAccounts" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="发票地址" prop="invoiceAddress">
          <el-input v-model="form.invoiceAddress" placeholder="请输入发票地址" />
        </el-form-item>
        <el-form-item label="发票电话" prop="invoiceLandline">
          <el-input v-model="form.invoiceLandline" placeholder="请输入发票电话" />
        </el-form-item>
        <el-form-item label="供货范围" prop="scopeSupply">
          <el-input v-model="form.scopeSupply" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="合作方式" prop="cooperateWay">
          <el-input v-model="form.cooperateWay" placeholder="请输入合作方式" />
        </el-form-item>
        <el-form-item label="合作等级" prop="cooperateLevel">
          <el-input v-model="form.cooperateLevel" placeholder="请输入合作等级" />
        </el-form-item>
        <el-form-item label="合同到期时间" prop="contractEndTime">
          <el-date-picker
            clearable
            v-model="form.contractEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择合同到期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应评分" prop="supplyScore">
          <el-input v-model="form.supplyScore" placeholder="请输入供应评分" />
        </el-form-item>
        <el-form-item label="年销售额" prop="yearSales">
          <el-input v-model="form.yearSales" placeholder="请输入年销售额" />
        </el-form-item>
        <el-form-item label="供应商联系人姓名" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商联系人姓名" />
        </el-form-item>
        <el-form-item label="供应商联系人电话" prop="supplierPhone">
          <el-input v-model="form.supplierPhone" placeholder="请输入供应商联系人电话" />
        </el-form-item>
        <el-form-item label="供应商登录密码" prop="supplierPassword">
          <el-input v-model="form.supplierPassword" placeholder="请输入供应商登录密码" />
        </el-form-item>
        <el-form-item label="经营品类" prop="operatingCategory">
          <el-input v-model="form.operatingCategory" placeholder="请输入经营品类" />
        </el-form-item>
        <el-form-item label="经营品牌" prop="operatingBrand">
          <el-input v-model="form.operatingBrand" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="其他客户" prop="otherCustomers">
          <el-input v-model="form.otherCustomers" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="简称" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入简称" />
        </el-form-item>
        <el-form-item label="所属行业" prop="industrCategory">
          <el-input v-model="form.industrCategory" placeholder="请输入所属行业" />
        </el-form-item>
        <el-form-item label="所属公司" prop="ownedCompany">
          <el-input v-model="form.ownedCompany" placeholder="请输入所属公司" />
        </el-form-item>
        <el-form-item label="创建时间" prop="created">
          <el-date-picker clearable v-model="form.created" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改时间" prop="modify">
          <el-date-picker clearable v-model="form.modify" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择修改时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期开始时间" prop="validityFromDate">
          <el-date-picker
            clearable
            v-model="form.validityFromDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期结束时间" prop="validityToDate">
          <el-date-picker
            clearable
            v-model="form.validityToDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="行号" prop="rowNo">
          <el-input v-model="form.rowNo" placeholder="请输入行号" />
        </el-form-item>
        <el-form-item label="法人身份证图片路径" prop="personImage">
          <image-upload v-model="form.personImage" />
        </el-form-item>
        <el-form-item label="对接次数" prop="abutmentNo">
          <el-input v-model="form.abutmentNo" placeholder="请输入对接次数" />
        </el-form-item>
        <el-form-item label="是否合作" prop="cooperative">
          <el-input v-model="form.cooperative" placeholder="请输入是否合作" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!dialog.readonly" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">{{ dialog.readonly ? '关 闭' : '取 消' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Info" lang="ts">
import { useRoute } from 'vue-router';
import {
  getApproveList,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
  getComSupTyList,
  getProductCategoryList,
  getComStaffList,
  getDictData
} from '@/api/customer/info';
import { InfoVO, InfoQuery, InfoForm } from '@/api/customer/info/types';
import { listType } from '@/api/system/type';
import { TypeVO } from '@/api/system/type/types';
import { getSupplierStatusOptions, getSupplierStatusDisplayName } from '@/enums/supplierStatus';
import { getSupplierCooperationStatusDisplayName } from '@/enums/supplierCooperationStatus';

// 测试枚举函数
console.log('测试枚举 - 使用原始名称:', getSupplierStatusOptions(true));
console.log('测试枚举 - 使用展示名称:', getSupplierStatusOptions(false));

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();

const infoList = ref<InfoVO[]>([]);
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 supplierTypeList = ref<TypeVO[]>([]);
const productCategoryList = ref<{ categoryNo: string; categoryName: string; id?: number }[]>([]);
const comStaffList = ref<{ staffId: string; staffName: string }[]>([]);
const membershipSizeDict = ref<any[]>([]); // 企业规模字典
// 使用枚举获取供应商状态选项，搜索框显示原始名称
const supplierStatusOptions = getSupplierStatusOptions(true);
console.log('供应商状态选项:', supplierStatusOptions);

const queryFormRef = ref<ElFormInstance>();
const infoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption & { readonly?: boolean }>({
  visible: false,
  title: '',
  readonly: false
});

const initFormData: InfoForm = {
  id: undefined,
  supplierNo: undefined,
  enterpriseName: undefined,
  membershipSize: undefined,
  supplierType: undefined,
  cooperationType: undefined,
  fixedPhone: undefined,
  fax: undefined,
  url: undefined,
  postCode: undefined,
  mailbox: undefined,
  officeProvince: undefined,
  officeCity: undefined,
  officeCounty: undefined,
  officeAddress: undefined,
  businessName: undefined,
  socialCreditCode: undefined,
  legalPersonName: undefined,
  legalPersonId: undefined,
  registeredCapital: undefined,
  businessProvince: undefined,
  businessCity: undefined,
  businessCounty: undefined,
  businessAddress: undefined,
  businessLicense: undefined,
  invoiceType: undefined,
  invoiceHeader: undefined,
  taxpayerIdentifier: undefined,
  depositaryBank: undefined,
  rowNum: undefined,
  bankAccounts: undefined,
  invoiceAddress: undefined,
  invoiceLandline: undefined,
  scopeSupply: undefined,
  cooperateWay: undefined,
  cooperateLevel: undefined,
  contractEndTime: undefined,
  supplyStatus: undefined,
  supplyScore: undefined,
  yearSales: undefined,
  supplierName: undefined,
  supplierPhone: undefined,
  supplierPassword: undefined,
  operatingCategory: undefined,
  operatingBrand: undefined,
  otherCustomers: undefined,
  shortName: undefined,
  industrCategory: undefined,
  type: undefined,
  ownedCompany: undefined,
  pushStatus: undefined,
  created: undefined,
  modify: undefined,
  validityFromDate: undefined,
  validityToDate: undefined,
  rowNo: undefined,
  personImage: undefined,
  abutmentNo: undefined,
  cooperative: undefined
};
const data = reactive<PageData<InfoForm, InfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierNo: undefined,
    enterpriseName: undefined,
    membershipSize: undefined,
    supplierType: undefined,
    cooperationType: undefined,
    fixedPhone: undefined,
    fax: undefined,
    url: undefined,
    postCode: undefined,
    mailbox: undefined,
    officeProvince: undefined,
    officeCity: undefined,
    officeCounty: undefined,
    officeAddress: undefined,
    businessName: undefined,
    socialCreditCode: undefined,
    legalPersonName: undefined,
    legalPersonId: undefined,
    registeredCapital: undefined,
    businessProvince: undefined,
    businessCity: undefined,
    businessCounty: undefined,
    businessAddress: undefined,
    businessLicense: undefined,
    invoiceType: undefined,
    invoiceHeader: undefined,
    taxpayerIdentifier: undefined,
    depositaryBank: undefined,
    rowNum: undefined,
    bankAccounts: undefined,
    invoiceAddress: undefined,
    invoiceLandline: undefined,
    scopeSupply: undefined,
    cooperateWay: undefined,
    cooperateLevel: undefined,
    contractEndTime: undefined,
    supplyStatus: undefined,
    supplyScore: undefined,
    yearSales: undefined,
    supplierName: undefined,
    supplierPhone: undefined,
    supplierPassword: undefined,
    operatingCategory: undefined,
    operatingBrand: undefined,
    otherCustomers: undefined,
    shortName: undefined,
    industrCategory: undefined,
    type: undefined,
    ownedCompany: undefined,
    pushStatus: undefined,
    created: undefined,
    modify: undefined,
    validityFromDate: undefined,
    validityToDate: undefined,
    rowNo: undefined,
    personImage: undefined,
    abutmentNo: undefined,
    cooperative: undefined,
    productManager: undefined,
    buyer: undefined,
    province: undefined,
    city: undefined,
    params: {}
  },
  rules: {
    supplierNo: [{ required: true, message: '供应商编号不能为空', trigger: 'blur' }],
    enterpriseName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
    membershipSize: [{ required: true, message: '人员规模不能为空', trigger: 'blur' }],
    supplierType: [{ required: true, message: '供应商类型不能为空', trigger: 'change' }],
    cooperationType: [{ required: true, message: '合作类型不能为空', trigger: 'change' }],
    fixedPhone: [{ required: true, message: '固定电话不能为空', trigger: 'blur' }],
    fax: [{ required: true, message: '传真不能为空', trigger: 'blur' }],
    url: [{ required: true, message: '网址不能为空', trigger: 'blur' }],
    postCode: [{ required: true, message: '邮政编码不能为空', trigger: 'blur' }],
    mailbox: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }],
    officeProvince: [{ required: true, message: '办公地址-省不能为空', trigger: 'blur' }],
    officeCity: [{ required: true, message: '办公地址-市不能为空', trigger: 'blur' }],
    officeCounty: [{ required: true, message: '办公地址-区/县不能为空', trigger: 'blur' }],
    officeAddress: [{ required: true, message: '办公详细地址不能为空', trigger: 'blur' }],
    businessName: [{ required: true, message: '营业执照名称不能为空', trigger: 'blur' }],
    socialCreditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: 'blur' }],
    legalPersonName: [{ required: true, message: '法人姓名不能为空', trigger: 'blur' }],
    legalPersonId: [{ required: true, message: '法人身份证号不能为空', trigger: 'blur' }],
    registeredCapital: [{ required: true, message: '注册资本不能为空', trigger: 'blur' }],
    businessProvince: [{ required: true, message: '注册地址-省不能为空', trigger: 'blur' }],
    businessCity: [{ required: true, message: '注册地址-市不能为空', trigger: 'blur' }],
    businessCounty: [{ required: true, message: '注册地址-区/县不能为空', trigger: 'blur' }],
    businessAddress: [{ required: true, message: '注册详细地址不能为空', trigger: 'blur' }],
    businessLicense: [{ required: true, message: '营业执照图片路径不能为空', trigger: 'blur' }],
    invoiceType: [{ required: true, message: '发票类型不能为空', trigger: 'change' }],
    invoiceHeader: [{ required: true, message: '发票抬头不能为空', trigger: 'blur' }],
    taxpayerIdentifier: [{ required: true, message: '纳税人识别号不能为空', trigger: 'blur' }],
    depositaryBank: [{ required: true, message: '开户银行不能为空', trigger: 'blur' }],
    rowNum: [{ required: true, message: '行号不能为空', trigger: 'blur' }],
    bankAccounts: [{ required: true, message: '银行账号不能为空', trigger: 'blur' }],
    invoiceAddress: [{ required: true, message: '发票地址不能为空', trigger: 'blur' }],
    invoiceLandline: [{ required: true, message: '发票电话不能为空', trigger: 'blur' }],
    scopeSupply: [{ required: true, message: '供货范围不能为空', trigger: 'blur' }],
    cooperateWay: [{ required: true, message: '合作方式不能为空', trigger: 'blur' }],
    contractEndTime: [{ required: true, message: '合同到期时间不能为空', trigger: 'blur' }],
    yearSales: [{ required: true, message: '年销售额不能为空', trigger: 'blur' }],
    supplierName: [{ required: true, message: '供应商联系人姓名不能为空', trigger: 'blur' }],
    supplierPhone: [{ required: true, message: '供应商联系人电话不能为空', trigger: 'blur' }],
    supplierPassword: [{ required: true, message: '供应商登录密码不能为空', trigger: 'blur' }],
    operatingCategory: [{ required: true, message: '经营品类不能为空', trigger: 'blur' }],
    operatingBrand: [{ required: true, message: '经营品牌不能为空', trigger: 'blur' }],
    otherCustomers: [{ required: true, message: '其他客户不能为空', trigger: 'blur' }],
    shortName: [{ required: true, message: '简称不能为空', trigger: 'blur' }],
    industrCategory: [{ required: true, message: '所属行业不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
    ownedCompany: [{ required: true, message: '所属公司不能为空', trigger: 'blur' }],
    modify: [{ required: true, message: '修改时间不能为空', trigger: 'blur' }],
    validityFromDate: [{ required: true, message: '有效期开始时间不能为空', trigger: 'blur' }],
    validityToDate: [{ required: true, message: '有效期结束时间不能为空', trigger: 'blur' }],
    rowNo: [{ required: true, message: '行号不能为空', trigger: 'blur' }],
    personImage: [{ required: true, message: '法人身份证图片路径不能为空', trigger: 'blur' }],
    cooperative: [{ required: true, message: '是否合作不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询供应商信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await getApproveList(queryParams.value);
  infoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 获取企业规模字典 */
const getMembershipSizeDict = async () => {
  try {
    const res = await getDictData('membership_size');
    membershipSizeDict.value = res.data || [];
    console.log('企业规模字典:', membershipSizeDict.value);
  } catch (e) {
    console.error('获取企业规模字典失败:', e);
  }
};

/** 根据字典值获取字典标签 */
const getMembershipSizeLabel = (dictValue: string) => {
  const dict = membershipSizeDict.value.find((item) => item.dictValue === dictValue);
  return dict ? dict.dictLabel : dictValue;
};

/** 格式化日期，只显示日期部分 */
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  return dateStr.split(' ')[0]; // 只取空格前的日期部分
};

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

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  infoFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: InfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加供应商信息';
  dialog.readonly = false;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: InfoVO) => {
  // 跳转到详情页（编辑模式）
  const router = proxy?.$router;
  const _id = row?.id || ids.value[0];
  router?.push({
    path: '/customer/info/detail',
    query: {
      id: _id,
      mode: 'edit'
    }
  });
};

/** 提交按钮 */
const submitForm = () => {
  infoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: InfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除供应商信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 查看按钮操作 */
const handleView = (row: InfoVO) => {
  // 使用router.push跳转到详情页
  const router = proxy?.$router;
  router?.push({
    path: '/customer/info/detail',
    query: {
      id: row.id
    }
  });
};

/** 审核通过按钮操作 */
const handleApprove = async (row: InfoVO) => {
  await proxy?.$modal.confirm('是否确认审核通过供应商"' + row.enterpriseName + '"？');
  try {
    // 只传id和supplyStatus，避免将后端返回的名字字段传回去
    await updateInfo({
      id: row.id,
      supplyStatus: '1'
    });
    proxy?.$modal.msgSuccess('审核通过成功');
    await getList();
  } catch (e) {
    console.error('审核通过失败:', e);
  }
};

/** 驳回按钮操作 */
const handleReject = async (row: InfoVO) => {
  await proxy?.$modal.confirm('是否确认驳回供应商"' + row.enterpriseName + '"？');
  try {
    // 只传id和supplyStatus
    await updateInfo({
      id: row.id,
      supplyStatus: '3'
    });
    proxy?.$modal.msgSuccess('驳回成功');
    await getList();
  } catch (e) {
    console.error('驳回失败:', e);
  }
};

/** 停止合作按钮操作 */
const handleStopCooperation = async (row: InfoVO) => {
  await proxy?.$modal.confirm('是否确认停止与供应商"' + row.enterpriseName + '"的合作？');
  // 只传id和supplyStatus
  const updateData = {
    id: row.id,
    supplyStatus: '2'
  };
  await updateInfo(updateData);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

/** 恢复合作按钮操作 */
const handleResumeCooperation = async (row: InfoVO) => {
  await proxy?.$modal.confirm('是否确认恢复与供应商"' + row.enterpriseName + '"的合作？');
  // 只传id和supplyStatus
  const updateData = {
    id: row.id,
    supplyStatus: '1'
  };
  await updateInfo(updateData);
  proxy?.$modal.msgSuccess('已恢复合作');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/info/export',
    {
      ...queryParams.value
    },
    `info_${new Date().getTime()}.xlsx`
  );
};

/** 获取供应商类型列表 */
const getSupplierTypeList = async () => {
  try {
    const res = await listType({
      pageNum: 1,
      pageSize: 1000
    } as any);
    supplierTypeList.value = res.rows || [];
  } catch (e) {
    console.error('获取供应商类型失败', e);
  }
};

/** 获取产品分类列表 */
const getProductCategoryData = async () => {
  try {
    const res = await getProductCategoryList();
    // 接口返回格式：{ code: 200, data: [...] }
    productCategoryList.value = res.data;
    console.log('产品分类数据:', productCategoryList.value);
  } catch (e) {
    console.error('获取产品分类失败', e);
  }
};

/** 获取人员信息列表 */
const getComStaffData = async () => {
  try {
    const res = await getComStaffList({ pageNum: 1, pageSize: 100000 });
    // 接口返回格式：{ code: 200, data: { total: 7, rows: [...] } }
    comStaffList.value = res.data?.rows || [];
    console.log('人员信息数据:', comStaffList.value);
    console.log('完整响应:', res);
  } catch (e) {
    console.error('获取人员信息失败', e);
  }
};

/** 根据供应商类型名称获取显示名称 */
const getSupplierTypeName = (typeName: string) => {
  const item = supplierTypeList.value.find((t) => t.supplierTypeName === typeName);
  return item ? item.supplierTypeName : typeName;
};

/** 根据categoryNo获取categoryName */
const getCategoryName = (categoryNo: string) => {
  const item = productCategoryList.value.find((c) => c.categoryNo === categoryNo);
  return item ? item.categoryName : categoryNo;
};

/** 根据staffId获取staffName */
const getStaffName = (staffId: string) => {
  const item = comStaffList.value.find((s) => s.staffId === staffId);
  return item ? item.staffName : staffId;
};

/** 根据状态码获取状态显示名称 */
const getStatusDisplayName = (statusCode: number) => {
  return getSupplierStatusDisplayName(statusCode);
};

/** 根据合作状态码获取合作状态显示名称 */
const getCooperationStatusDisplayName = (statusCode: number) => {
  return getSupplierCooperationStatusDisplayName(statusCode);
};

/** 格式化省份显示：只显示第一个省份，其余用...表示 */
const formatProvinceDisplay = (province: string) => {
  if (!province) return '';
  const provinces = province.split(',').filter((p) => p.trim());
  if (provinces.length === 0) return '';
  if (provinces.length === 1) return provinces[0];
  return `${provinces[0]}...`;
};

/** 格式化城市显示：显示前10个城市，其余用...表示 */
const formatCityDisplay = (city: string) => {
  if (!city) return '';
  const cities = city.split(',').filter((c) => c.trim());
  if (cities.length === 0) return '';
  if (cities.length <= 10) return cities.join(',');
  return `${cities.slice(0, 10).join(',')}...`;
};

onMounted(async () => {
  getSupplierTypeList();
  getProductCategoryData();
  getMembershipSizeDict(); // 获取企业规模字典

  // 直接调用人员接口测试
  try {
    console.log('开始获取人员数据...');
    const staffRes = await getComStaffList({ pageNum: 1, pageSize: 100000 });
    console.log('人员接口响应:', staffRes);
    // 根据你提供的数据结构，直接从 staffRes.rows 获取
    comStaffList.value = staffRes.rows || [];
    console.log('人员列表:', comStaffList.value);
    console.log('人员列表长度:', comStaffList.value.length);
  } catch (e) {
    console.error('人员接口调用失败:', e);
  }

  // 从路由query中获取supplyStatus并传给后端
  if (route.query.supplyStatus) {
    queryParams.value.supplyStatus = route.query.supplyStatus as string;
  }
  getList();

  // 禁用表格列宽调整
  nextTick(() => {
    const table = document.querySelector('.no-resize-table');
    if (table) {
      table.addEventListener(
        'mousedown',
        (e: any) => {
          const target = e.target as HTMLElement;
          // 阻止在表头边界处的鼠标按下事件
          if (target.classList.contains('el-table__column-resize-proxy') || target.closest('.el-table__column-resize-proxy')) {
            e.preventDefault();
            e.stopPropagation();
            return false;
          }
        },
        true
      );
    }
  });
});
</script>

<style scoped>
:deep(.el-form-item__label) {
  text-align: left !important;
}

:deep(.el-form-item) {
  margin-right: 30px;
  margin-bottom: 20px;
}

/* 禁用表格列宽拖动 */
.no-resize-table :deep(th.el-table__cell) {
  user-select: none !important;
  resize: none !important;
  cursor: default !important;
}

.no-resize-table :deep(.el-table__header-wrapper th) {
  cursor: default !important;
}

.no-resize-table :deep(.el-table__header-wrapper .el-table__cell:hover) {
  cursor: default !important;
}

.no-resize-table :deep(.el-table__header-wrapper) {
  cursor: default !important;
}

/* 隐藏列宽调整的分隔线悬停效果 */
.no-resize-table :deep(th.el-table__cell:hover) {
  cursor: default !important;
}

.no-resize-table :deep(.el-table__header th.el-table__cell) {
  border-right: 1px solid #ebeef5;
}

/* 禁用拖动事件 */
.no-resize-table :deep(.el-table__header-wrapper) {
  pointer-events: auto;
}

.no-resize-table :deep(.el-table__header th) {
  pointer-events: auto;
}

.no-resize-table :deep(.el-table__header .cell) {
  pointer-events: auto;
}

:deep(.el-input__wrapper) {
  font-size: 15px;
}

:deep(.el-input__inner) {
  font-size: 15px;
}

:deep(.el-select) {
  font-size: 15px;
}

:deep(.el-select .el-input__inner) {
  font-size: 15px;
}
</style>
