<template>
  <div class="p-4">
    <!-- 企业基本信息 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-medium"
            >企业基本信息 / <span style="color: #ff0033">客户编号：{{ customerNumber }}</span></span
          >
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="所属公司" prop="belongCompanyId">
              <el-select v-model="form.belongCompanyId" placeholder="请选择所属公司" class="w-full" filterable>
                <el-option v-for="item in companyList" :key="item.id" :label="`${item.companyCode} , ${item.companyName}`" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工商名称" prop="businessCustomerName">
              <el-input v-model="form.businessCustomerName" placeholder="请输入工商名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="企业简称" prop="shortName">
              <el-input v-model="form.shortName" placeholder="请输入企业简称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票类型" prop="invoiceTypeId">
              <el-select v-model="form.invoiceTypeId" placeholder="请选择开票类型" class="w-full">
                <el-option v-for="item in invoiceTypeList" :key="item.id" :label="item.invoiceTypeName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业规模" prop="enterpriseScaleId">
              <el-select v-model="form.enterpriseScaleId" placeholder="请选择企业规模" class="w-full" filterable>
                <el-option v-for="item in enterpriseScaleList" :key="item.id" :label="item.enterpriseScaleName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户类别" prop="customerTypeId">
              <el-select v-model="form.customerTypeId" placeholder="请选择客户类别" class="w-full">
                <el-option v-for="dict in customer_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行业类别" prop="industryCategoryId">
              <el-select v-model="form.industryCategoryId" placeholder="请选择行业类别" class="w-full" filterable>
                <el-option v-for="item in industryCategoryList" :key="item.id" :label="item.industryCategoryName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户等级" prop="customerLevelId">
              <el-select v-model="form.customerLevelId" placeholder="请选择客户等级" class="w-full">
                <el-option v-for="dict in customer_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="固定电话" prop="landline">
              <el-input v-model="form.landline" placeholder="请输入固定电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="传真" prop="fax">
              <el-input v-model="form.fax" placeholder="请输入传真" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网址" prop="url">
              <el-input v-model="form.url" placeholder="请输入网址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="邮政编码" prop="postCode">
              <el-input v-model="form.postCode" placeholder="请输入邮政编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="validityFromDate">
              <el-date-picker
                v-model="form.validityFromDate"
                type="date"
                placeholder="请选择开始时间"
                class="w-full"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="validityToDate">
              <el-date-picker
                v-model="form.validityToDate"
                type="date"
                placeholder="请选择结束时间"
                class="w-full"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="(time) => form.validityFromDate && time.getTime() < new Date(form.validityFromDate).getTime()"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="发票抬头" prop="invoiceTop">
              <el-input v-model="form.invoiceTop" placeholder="请输入发票抬头" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="办公地址">
              <el-cascader v-model="codeArr" :options="regionData" placeholder="请选择" @change="handleChange" style="width: 100%"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 工商信息 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-medium">工商信息</span>
          <el-button type="primary" @click="handleUpdate">更新</el-button>
        </div>
      </template>

      <el-form :model="businessInfo" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="企业工商名称">
              <el-input v-model="businessInfo.businessCustomerName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="社会信用代码">
              <el-input v-model="businessInfo.socialCreditCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人姓名">
              <el-input v-model="businessInfo.legalPersonName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="注册资本">
              <el-input v-model="businessInfo.registeredCapital" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登记机关">
              <el-input v-model="businessInfo.registrationAuthority" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成立日期">
              <el-input v-model="businessInfo.establishmentDate" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="吊销日期">
              <el-input v-model="businessInfo.revocationDate" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登记状态">
              <el-input v-model="businessInfo.registrationStatus" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实缴资本">
              <el-input v-model="businessInfo.paidInCapital" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="详细地址">
              <el-input v-model="businessInfo.businessAddress" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="营业执照">
              <div
                v-if="!businessInfo.businessLicense"
                class="upload-box"
                @click="businessLicenseSelectorVisible = true"
                style="
                  width: 360px;
                  height: 200px;
                  border: 2px dashed #d9d9d9;
                  border-radius: 4px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  cursor: pointer;
                  transition: all 0.3s;
                "
                @mouseenter="(e) => (e.currentTarget.style.borderColor = '#409eff')"
                @mouseleave="(e) => (e.currentTarget.style.borderColor = '#d9d9d9')"
              >
                <div style="text-align: center; color: #8c939d">
                  <el-icon :size="40" style="margin-bottom: 8px">
                    <Plus />
                  </el-icon>
                  <div style="font-size: 14px">点击上传</div>
                </div>
              </div>
              <div v-else style="position: relative; display: inline-block">
                <el-image
                  :src="businessInfo.businessLicense"
                  style="width: 360px; height: 200px"
                  fit="contain"
                  :preview-src-list="[businessInfo.businessLicense]"
                />
                <el-button
                  type="danger"
                  :icon="Delete"
                  circle
                  size="small"
                  style="position: absolute; top: 5px; right: 5px"
                  @click="businessInfo.businessLicense = ''"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 销售信息 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-medium">销售信息</span>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
      <el-form :model="salesForm" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="业务人员" prop="salesPersonId">
              <el-select v-model="salesForm.salesPersonId" placeholder="请选择业务人员" class="w-full" filterable>
                <el-option label="张三" value="1" />
                <el-option label="李四" value="2" />
                <el-option label="王五" value="3" />
                <el-option label="赵六" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客服人员" prop="serviceStaffId">
              <el-select v-model="salesForm.serviceStaffId" placeholder="请选择客服人员" class="w-full" filterable>
                <el-option label="客服A" value="1" />
                <el-option label="客服B" value="2" />
                <el-option label="客服C" value="3" />
                <el-option label="客服D" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属部门" prop="belongingDepartmentId">
              <el-select v-model="salesForm.belongingDepartmentId" placeholder="请选择所属部门" class="w-full" filterable disabled>
                <el-option label="销售部" value="1" />
                <el-option label="市场部" value="2" />
                <el-option label="客服部" value="3" />
                <el-option label="技术部" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="信用等级" prop="creditManagement">
              <el-select v-model="salesForm.creditManagement" placeholder="请选择信用等级" class="w-full">
                <el-option label="A级" value="A" />
                <el-option label="B级" value="B" />
                <el-option label="C级" value="C" />
                <el-option label="D级" value="D" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="信用额度" prop="creditAmount">
              <el-input v-model="salesForm.creditAmount" :controls="false" class="w-full" placeholder="请输入信用额度" style="width: 100%" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="可用额度" prop="remainingQuota">
              <el-input
                v-model="salesForm.remainingQuota"
                :controls="false"
                class="w-full"
                placeholder="请输入可用额度"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单审核" prop="orderAudit">
              <el-select v-model="salesForm.orderAudit" placeholder="请选择" class="w-full" filterable>
                <el-option v-for="dict in order_check_way" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付密码" prop="creditPaymentPassword">
              <el-input v-model="salesForm.creditPaymentPassword" type="password" placeholder="请输入支付密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收款条件" prop="accountPeriod">
              <el-input v-model="salesForm.accountPeriod" placeholder="请输入收款条件" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="结算方式" prop="payDays">
              <el-select v-model="salesForm.creditManagement" placeholder="请选择结算方式" class="w-full"> </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 公司开票信息 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-medium">企业开票信息</span>
          <el-button type="primary" @click="handleAddInvoice">新增</el-button>
        </div>
      </template>
      <el-table :data="invoiceList" border>
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column label="是否主账号" align="center" prop="isPrimaryAccount" min-width="120">
          <template #default="{ row }">
            <span>{{ row.isPrimaryAccount === '0' ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开户行名称" align="center" prop="bankName" min-width="180" />
        <el-table-column label="银行账户" align="center" prop="bankAccount" min-width="180" />
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="{ row, $index }">
            <el-button link type="primary" @click="handleEditInvoice(row, $index)">编辑</el-button>
            <el-button link type="danger" @click="removeInvoice($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑开票信息对话框 -->
    <add-invoice-dialog v-model="invoiceDialogVisible" :edit-data="currentInvoice" @confirm="handleInvoiceConfirm" />

    <!-- 营业执照选择器对话框 -->
    <FileSelector
      v-model="businessLicenseSelectorVisible"
      title="选择营业执照"
      :allowed-types="[1]"
      :multiple="false"
      :allow-upload="true"
      @confirm="handleBusinessLicenseSelected"
    />
  </div>
</template>

<script setup lang="ts" name="BaseInfo">
import { getCustomerInfo, updateCustomerInfo } from '@/api/customer/customerFile/customerInfo';
import type { CustomerInfoForm } from '@/api/customer/customerFile/customerInfo/types';
import type { BusinessInfoForm } from '@/api/customer/customerFile/businessInfo/types';
import type { SalesInfoForm } from '@/api/customer/customerFile/salesInfo/types';
import type { InvoiceInfoForm } from '@/api/customer/customerFile/invoiceInfo/types';
import AddInvoiceDialog from '../components/addInvoiceDialog.vue';
import { regionData } from 'element-china-area-data';
import { listEnterpriseScale } from '@/api/customer/customerCategory/enterpriseScale';
import { listIndustryCategory } from '@/api/customer/customerCategory/industryCategory';
import { listInvoiceType } from '@/api/customer/invoiceType';
import type { EnterpriseScaleVO } from '@/api/customer/customerCategory/enterpriseScale/types';
import type { IndustryCategoryVO } from '@/api/customer/customerCategory/industryCategory/types';
import type { InvoiceTypeVO } from '@/api/customer/invoiceType/types';
import { listSysCompany } from '@/api/company/sysCompany';
import type { SysCompanyVO } from '@/api/company/sysCompany/types';
import FileSelector from '@/components/FileSelector/index.vue';
import { Plus, Delete } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_check_way, customer_type, customer_level } = toRefs<any>(proxy?.useDict('order_check_way', 'customer_type', 'customer_level'));
// 接收父组件传递的props
const props = defineProps<{
  customerId?: string | number;
  customerNo?: string;
}>();

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

const formRef = ref<any>(null);
const submitLoading = ref(false);
const customerId = ref<string | number>('');
const customerNumber = ref('');
const codeArr = ref([]);

// 下拉框数据列表
const enterpriseScaleList = ref<EnterpriseScaleVO[]>([]);
const industryCategoryList = ref<IndustryCategoryVO[]>([]);
const invoiceTypeList = ref<InvoiceTypeVO[]>([]);
const companyList = ref<SysCompanyVO[]>([]);

// 企业基本信息（用于显示）
const customerInfo = reactive<any>({
  customerNo: '',
  belongCompanyName: '',
  companyName: '',
  businessCustomerName: '',
  shortName: '',
  invoiceTypeName: '',
  enterpriseScale: '',
  customerTypeName: '',
  industryCategory: '',
  customerLevelName: '',
  landline: '',
  fax: '',
  url: '',
  postCode: '',
  validityFromDate: '',
  validityToDate: '',
  invoiceTop: '',
  provincialCityCounty: '',
  address: ''
});

// 企业基本信息表单（用于编辑）
const form = reactive<CustomerInfoForm>({
  id: undefined,
  customerNo: '',
  belongCompanyId: undefined,
  companyName: '',
  businessCustomerName: '',
  shortName: '',
  invoiceTypeId: undefined,
  enterpriseScaleId: undefined,
  customerTypeId: undefined,
  industryCategoryId: undefined,
  customerLevelId: undefined,
  landline: '',
  fax: '',
  url: '',
  postCode: '',
  validityFromDate: undefined,
  validityToDate: undefined,
  invoiceTop: '',
  address: '',
  regProvincialNo: '',
  regCityNo: '',
  regCountyNo: '',
  provincialCityCounty: '',
  status: '0',
  remark: ''
});

// 工商信息（只读）
const businessInfo = reactive<BusinessInfoForm>({
  businessCustomerName: '',
  socialCreditCode: '',
  legalPersonName: '',
  registeredCapital: '',
  registrationAuthority: '',
  establishmentDate: '',
  revocationDate: '',
  registrationStatus: '',
  paidInCapital: undefined,
  businessAddress: '',
  businessLicense: '',
  status: '0'
});

// 销售信息
const salesForm = reactive<SalesInfoForm>({
  salesPersonId: undefined,
  serviceStaffId: undefined,
  belongingDepartmentId: undefined,
  creditManagement: undefined,
  creditAmount: undefined,
  remainingQuota: undefined,
  orderAudit: undefined,
  creditPaymentPassword: '',
  accountPeriod: '',
  payDays: undefined,
  status: '0'
});

// 开票信息列表
const invoiceList = ref<InvoiceInfoForm[]>([]);
const invoiceDialogVisible = ref(false);
const currentInvoice = ref<InvoiceInfoForm | undefined>(undefined);
const currentInvoiceIndex = ref<number>(-1);

// 营业执照上传相关
const uploadRef = ref();
const uploadLoading = ref(false);
const businessLicenseSelectorVisible = ref(false);
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/common/upload';
const uploadHeaders = ref({
  Authorization: 'Bearer ' + localStorage.getItem('token')
});

// 表单验证规则
const rules = {
  belongCompanyId: [{ required: true, message: '请选择所属公司', trigger: 'change' }],
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  businessCustomerName: [{ required: true, message: '请输入工商名称', trigger: 'blur' }],
  shortName: [{ required: true, message: '请输入企业简称', trigger: 'blur' }],
  invoiceTypeId: [{ required: true, message: '请选择开票类型', trigger: 'change' }],
  enterpriseScaleId: [{ required: true, message: '请选择企业规模', trigger: 'change' }],
  customerTypeId: [{ required: true, message: '请选择客户类别', trigger: 'change' }],
  industryCategoryId: [{ required: true, message: '请选择行业类别', trigger: 'change' }],
  customerLevelId: [{ required: true, message: '请选择客户等级', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
};

// 初始化
onMounted(async () => {
  // 加载下拉框数据
  await loadEnterpriseScaleList();
  await loadIndustryCategoryList();
  await loadInvoiceTypeList();
  await loadCompanyList();

  // 优先使用props传递的customerId，否则从路由获取
  const id = props.customerId || route.query.id;
  if (id) {
    customerId.value = id as string;
    await loadCustomerData(id as string);
  }
});

// 监听props变化
watch(
  () => props.customerId,
  (newId) => {
    if (newId) {
      customerId.value = newId;
      loadCustomerData(newId);
    }
  }
);

// 加载企业规模列表
const loadEnterpriseScaleList = async () => {
  try {
    const res = await listEnterpriseScale();
    enterpriseScaleList.value = res.rows || [];
  } catch (error) {
    console.error('加载企业规模列表失败:', error);
  }
};

// 加载行业类别列表
const loadIndustryCategoryList = async () => {
  try {
    const res = await listIndustryCategory();
    industryCategoryList.value = res.rows || [];
  } catch (error) {
    console.error('加载行业类别列表失败:', error);
  }
};

// 加载开票类型列表
const loadInvoiceTypeList = async () => {
  try {
    const res = await listInvoiceType();
    invoiceTypeList.value = res.rows || [];
  } catch (error) {
    console.error('加载开票类型列表失败:', error);
  }
};

// 加载公司列表
const loadCompanyList = async () => {
  try {
    const res = await listSysCompany();
    companyList.value = res.rows || [];
  } catch (error) {
    console.error('加载公司列表失败:', error);
  }
};

// 加载客户数据
const loadCustomerData = async (id: string) => {
  try {
    const res = await getCustomerInfo(id);
    const data = res.data;

    // 填充基本信息
    customerInfo.customerNo = data.customerNo || '';
    customerInfo.belongCompanyName = getCompanyName(data.belongCompanyId);
    customerInfo.companyName = data.companyName || '';
    customerInfo.businessCustomerName = data.businessCustomerName || '';
    customerInfo.shortName = data.shortName || '';
    customerInfo.invoiceTypeName = getInvoiceTypeName(data.invoiceTypeId);
    customerInfo.enterpriseScale = data.enterpriseScale || '';
    customerInfo.customerTypeName = getCustomerTypeName(data.customerTypeId);
    customerInfo.industryCategory = data.industryCategory || '';
    customerInfo.customerLevelName = getCustomerLevelName(data.customerLevelId);
    customerInfo.landline = data.landline || '';
    customerInfo.fax = data.fax || '';
    customerInfo.url = data.url || '';
    customerInfo.postCode = data.postCode || '';
    customerInfo.validityFromDate = data.validityFromDate || '';
    customerInfo.validityToDate = data.validityToDate || '';
    customerInfo.invoiceTop = data.invoiceTop || '';
    customerInfo.provincialCityCounty = data.provincialCityCounty || '';
    customerInfo.address = data.address || '';

    // 填充工商信息
    if (data.customerBusinessInfoVo) {
      Object.assign(businessInfo, data.customerBusinessInfoVo);
    }

    // 填充表单数据（用于编辑）
    Object.assign(form, data);
    customerNumber.value = data.customerNo || '';

    // 如果有省市区编码，回显到级联选择器
    if (data.regProvincialNo && data.regCityNo && data.regCountyNo) {
      codeArr.value = [data.regProvincialNo, data.regCityNo, data.regCountyNo] as any;
    }

    // 填充销售信息
    if (data.customerSalesInfoVo) {
      Object.assign(salesForm, data.customerSalesInfoVo);
    }

    // 填充开票信息列表
    if (data.customerInvoiceInfoVoList) {
      invoiceList.value = data.customerInvoiceInfoVoList;
    }
  } catch (error) {
    console.error('加载客户数据失败:', error);
    ElMessage.error('加载客户数据失败');
  }
};

// 格式化方法
const getCompanyName = (id: string | number | undefined) => {
  const map: Record<string, string> = { '1': '公司A', '2': '公司B', '3': '公司C' };
  return map[String(id)] || '-';
};

const getInvoiceTypeName = (id: string | number | undefined) => {
  const map: Record<string, string> = {
    '1': '增值税专用发票',
    '2': '增值税普通发票',
    '3': '电子发票'
  };
  return map[String(id)] || '-';
};

const getCustomerTypeName = (id: string | number | undefined) => {
  const map: Record<string, string> = {
    '1': '重点客户',
    '2': '普通客户',
    '3': '潜在客户'
  };
  return map[String(id)] || '-';
};

const getCustomerLevelName = (id: string | number | undefined) => {
  const map: Record<string, string> = { '1': 'A级', '2': 'B级', '3': 'C级', '4': 'D级' };
  return map[String(id)] || '-';
};

const getSalesPersonName = (id: string | number | undefined) => {
  const map: Record<string, string> = { '1': '张三', '2': '李四', '3': '王五', '4': '赵六' };
  return map[String(id)] || '-';
};

const getServiceStaffName = (id: string | number | undefined) => {
  const map: Record<string, string> = { '1': '客服A', '2': '客服B', '3': '客服C', '4': '客服D' };
  return map[String(id)] || '-';
};

const getDepartmentName = (id: string | number | undefined) => {
  const map: Record<string, string> = { '1': '销售部', '2': '市场部', '3': '客服部', '4': '技术部' };
  return map[String(id)] || '-';
};

// 处理区域选择变化
const handleChange = (val: string[]) => {
  // 保存编码
  form.regProvincialNo = val[0];
  form.regCityNo = val[1];
  form.regCountyNo = val[2];

  // 根据编码获取名称
  const names: string[] = [];
  if (val[0]) {
    const province = regionData.find((item: any) => item.value === val[0]);
    if (province) {
      names.push(province.label);

      if (val[1] && province.children) {
        const city = province.children.find((item: any) => item.value === val[1]);
        if (city) {
          names.push(city.label);

          if (val[2] && city.children) {
            const county = city.children.find((item: any) => item.value === val[2]);
            if (county) {
              names.push(county.label);
            }
          }
        }
      }
    }
  }

  // 将省市区名称用斜杠连接
  form.provincialCityCounty = names.join('/');
};

// 打开添加开票信息对话框
const handleAddInvoice = () => {
  currentInvoice.value = undefined;
  currentInvoiceIndex.value = -1;
  invoiceDialogVisible.value = true;
};

//更新工商信息
const handleUpdate = () => {
  // 触发上传
  uploadRef.value?.$el.querySelector('input[type="file"]')?.click();
};

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isPDF = file.type === 'application/pdf';
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isImage && !isPDF) {
    ElMessage.error('只能上传图片或PDF文件！');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB！');
    return false;
  }
  uploadLoading.value = true;
  return true;
};

// 上传成功回调
const handleUploadSuccess = (response: any) => {
  uploadLoading.value = false;
  if (response.code === 200) {
    businessInfo.businessLicense = response.data.url || response.data.fileName;
    ElMessage.success('上传成功');

    // TODO: 这里可以调用OCR识别接口，自动填充工商信息
    // 如果后端提供了OCR识别接口，可以在这里调用
    // recognizeBusinessLicense(response.data.url);
  } else {
    ElMessage.error(response.msg || '上传失败');
  }
};

// 上传失败回调
const handleUploadError = () => {
  uploadLoading.value = false;
  ElMessage.error('上传失败，请重试');
};

// 预览营业执照
const previewLicense = () => {
  if (businessInfo.businessLicense) {
    window.open(businessInfo.businessLicense, '_blank');
  }
};

// 营业执照选择处理
const handleBusinessLicenseSelected = (files: any[]) => {
  if (files && files.length > 0) {
    const file = files[0]; // 取第一个文件
    if (file && (file.url || file.path)) {
      businessInfo.businessLicense = file.url || file.path;
      ElMessage.success('营业执照选择成功');
    } else {
      ElMessage.error('请选择有效的图片文件');
    }
  } else {
    ElMessage.error('请选择有效的图片文件');
  }
};

// 编辑开票信息
const handleEditInvoice = (row: InvoiceInfoForm, index: number) => {
  currentInvoice.value = { ...row };
  currentInvoiceIndex.value = index;
  invoiceDialogVisible.value = true;
};

// 确认添加/编辑开票信息
const handleInvoiceConfirm = (data: InvoiceInfoForm) => {
  if (currentInvoiceIndex.value >= 0) {
    // 编辑
    invoiceList.value[currentInvoiceIndex.value] = data;
  } else {
    // 新增
    invoiceList.value.push(data);
  }
};

// 删除开票信息
const removeInvoice = (index: number) => {
  ElMessageBox.confirm('确定要删除该开票信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      invoiceList.value.splice(index, 1);
      ElMessage.success('删除成功');
    })
    .catch(() => {});
};

// 保存按钮
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    submitLoading.value = true;

    // 组装提交数据
    const submitData: CustomerInfoForm = {
      ...form,
      customerBusinessBo: businessInfo,
      customerSalesInfoBo: salesForm,
      customerInvoiceInfoBoList: invoiceList.value
    };

    await updateCustomerInfo(submitData);
    ElMessage.success('保存成功');

    // 重新加载数据
    await loadCustomerData(customerId.value);
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请重试');
  } finally {
    submitLoading.value = false;
  }
};
</script>
