<template>
  <div class="add-customer-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <div class="left">
        <el-button link icon="Back" @click="handleBack">返回</el-button>
        <el-divider direction="vertical" />
        <span class="breadcrumb">基本信息 / <span class="highlight">新增客户</span></span>
      </div>
      <div class="right">
        <el-button type="primary" icon="Check" class="submit-btn" @click="handleSubmit">提交</el-button>
      </div>
    </div>

    <!-- 表单主体 -->
    <div class="form-body">
      <el-form :model="form" :rules="rules" ref="queryRef" label-width="120px" label-position="right">
        <!-- 基本信息区块 -->
        <div class="section-container">
          <div class="section-content">
            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="所属公司" required prop="belongCompanyId">
                  <el-select v-model="form.belongCompanyId" placeholder="请选择归属公司" style="width: 100%">
                    <el-option
                      v-for="item in companyOptions"
                      :key="item.id"
                      :label="item.companyName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户名称" required prop="customerName">
                  <el-input v-model="form.customerName" placeholder="请输入客户名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="工商名称" prop="bizName">
                  <el-input v-model="form.bizName" placeholder="请输入工商名称" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="客户来源" required prop="customerSourceId">
                  <el-select v-model="form.customerSourceId" placeholder="请选择客户来源" style="width: 100%">
                    <el-option
                      v-for="item in sourceOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="企业类型" required prop="enterpriseTypeId">
                  <el-select v-model="form.enterpriseTypeId" placeholder="请选择企业类型" style="width: 100%">
                    <el-option
                      v-for="item in corpTypeOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="企业规模" required prop="enterpriseScaleId">
                  <el-select v-model="form.enterpriseScaleId" placeholder="请选择企业规模" style="width: 100%">
                    <el-option
                      v-for="item in scaleOptions"
                      :key="item.id"
                      :label="item.enterpriseScaleName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="客户类别" required prop="customerCategoryId">
                  <el-select v-model="form.customerCategoryId" placeholder="请选择客户类别" style="width: 100%">
                    <el-option
                      v-for="item in categoryOptions"
                      :key="item.id"
                      :label="item.typeName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属行业" required prop="industryId">
                  <el-select v-model="form.industryId" placeholder="请选择行业" style="width: 100%">
                    <el-option
                      v-for="item in industryOptions"
                      :key="item.id"
                      :label="item.industryCategoryName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户等级" required prop="customerLevelId">
                    <el-select v-model="form.customerLevelId" placeholder="请选择客户等级" style="width: 100%">
                      <el-option
                        v-for="item in levelOptions"
                        :key="item.id"
                        :label="item.levelName"
                        :value="item.id"
                      />
                    </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="固定电话" prop="phone">
                  <el-input v-model="form.phone" 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="website">
                  <el-input v-model="form.website" placeholder="请输入网址" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="邮政编码" prop="zip">
                  <el-input v-model="form.zip" placeholder="请输入邮政编码" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40">
              <el-col :span="16">
                <el-form-item label="详细地址" prop="address">
                  <div style="display: flex; gap: 10px; width: 100%;">
                    <!-- 省市级联选择器 -->
                    <el-cascader
                      v-model="addressSelection"
                      :options="provinceOptions"
                      :props="cascaderProps"
                      placeholder="请选择"
                      style="width: 340px"
                      clearable
                      filterable
                      @change="handleAddressChange"
                    />
                    <el-input v-model="form.detailAddress" placeholder="请输入详细地址" style="flex: 1" />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 工商信息区块 -->
        <div class="section-container">
          <div class="section-header">工商信息</div>
          <div class="section-content">
            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="企业工商名称" prop="enterpriseName">
                  <el-input v-model="form.enterpriseName" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="社会信用代码" prop="socialCode">
                  <el-input v-model="form.socialCode" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="法人姓名" prop="legalPerson">
                  <el-input v-model="form.legalPerson" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="注册资本" prop="capital">
                  <el-input v-model="form.capital" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="登记机关" prop="org">
                  <el-input v-model="form.org" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="成立日期" prop="foundDate">
                  <el-date-picker
                    v-model="form.foundDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="吊销日期" prop="cancelDate">
                  <el-date-picker
                    v-model="form.cancelDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="登记状态" prop="regStatus">
                  <el-input v-model="form.regStatus" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="实缴资本" prop="paidCapital">
                  <el-input v-model="form.paidCapital" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="40">
              <el-col :span="16">
                <el-form-item label="详细地址" prop="bizAddress">
                  <el-input v-model="form.bizAddress" placeholder="请输入详细地址" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 证照上传（上传到OSS） -->
            <el-row :gutter="40" style="margin-top: 20px;">
              <el-col :span="8">
                <el-form-item label="营业执照">
                  <image-upload v-model="form.businessLicense" :limit="1" :file-size="10" :isShowTip="false" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="正面身份证">
                  <image-upload v-model="form.idCardFront" :limit="1" :file-size="10" :isShowTip="false" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="反面身份证">
                  <image-upload v-model="form.idCardBack" :limit="1" :file-size="10" :isShowTip="false" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 销售信息区块 -->
        <div class="section-container">
          <div class="section-header">销售信息</div>
          <div class="section-content">
            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="负责人" prop="managerId">
                  <el-select v-model="form.managerId" placeholder="请选择负责人" style="width: 100%">
                    <el-option
                      v-for="item in staffOptions"
                      :key="item.staffId"
                      :label="item.staffName"
                      :value="item.staffId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客服支持" prop="supportId">
                  <el-select v-model="form.supportId" placeholder="请选择客服支持" style="width: 100%">
                    <el-option
                      v-for="item in staffOptions"
                      :key="item.staffId"
                      :label="item.staffName"
                      :value="item.staffId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="采购规模" prop="purchaseScale">
                  <el-input v-model="form.purchaseScale"><template #append>万</template></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item label="销售目标" prop="salesTarget">
                  <el-input v-model="form.salesTarget"><template #append>万</template></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 联系人信息区块 -->
        <div class="section-container no-border">
          <div class="section-header flex-header">
            <span>联系人信息</span>
            <el-button type="primary" size="small" icon="Plus" @click="handleAddContact">新增</el-button>
          </div>
          <el-table :data="form.contacts" border class="contact-table">
            <el-table-column label="联系人" align="center" prop="contactName" />
            <el-table-column label="部门" align="center" prop="deptName" />
            <el-table-column label="职位" align="center" prop="roleName" />
            <el-table-column label="手机号码" align="center" prop="phone" />
            <el-table-column label="办公电话" align="center" prop="officePhone" />
            <el-table-column label="操作" align="center" width="100">
               <template #default="scope">
                  <el-button link type="danger" icon="Delete" @click="handleDeleteContact(scope.$index)">删除</el-button>
               </template>
            </el-table-column>
            <template #empty>暂无数据</template>
          </el-table>
        </div>
      </el-form>
    </div>

    <!-- 联系人新增抽屉 -->
    <el-drawer
      v-model="contactVisible"
      title="客户联系人"
      size="70%"
      class="contact-drawer"
    >
      <el-form :model="contactForm" :rules="contactRules" ref="contactRef" label-width="85px" label-position="right">
        <!-- 基本信息 -->
        <div class="drawer-header-section">基本信息</div>
        <div class="drawer-content-body">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="姓名" required prop="contactName">
                <el-input v-model="contactForm.contactName" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人类型" prop="type">
                <el-radio-group v-model="contactForm.type">
                  <el-radio label="1">公司职员</el-radio>
                  <el-radio label="2">关系资源人</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="contactForm.gender">
                  <el-radio label="1">男</el-radio>
                  <el-radio label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="contactForm.age" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="籍贯" prop="nativePlace">
                <el-input v-model="contactForm.nativePlace" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker v-model="contactForm.birthday" type="date" value-format="YYYY-MM-DD" placeholder="2026-04-07" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="描述" prop="remark">
                <el-input v-model="contactForm.remark" type="textarea" :rows="3" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 办公信息 -->
        <div class="drawer-header-section">办公信息</div>
        <div class="drawer-content-body">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="在职状态" prop="jobStatus">
                <el-radio-group v-model="contactForm.jobStatus">
                  <el-radio label="1">在职</el-radio>
                  <el-radio label="2">离职</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码" required prop="phone">
                <el-input v-model="contactForm.phone" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="部门" required prop="deptName">
                <el-input v-model="contactForm.deptName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="职位" prop="roleName">
                <el-input v-model="contactForm.roleName" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="办公座机" prop="officePhone">
                <el-input v-model="contactForm.officePhone" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="办公地址" required prop="officeAddress">
                <div style="display:flex; gap: 10px; width: 100%;">
                  <el-cascader
                    v-model="officeAddressSelection"
                    :options="provinceOptions"
                    :props="cascaderProps"
                    placeholder="请选择"
                    style="width: 200px"
                    clearable
                    filterable
                    @change="handleOfficeAddressChange"
                  />
                  <el-input v-model="contactForm.detailAddress" placeholder="请输入详细地址" style="flex: 1" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="工作内容" prop="jobContent">
                <el-input v-model="contactForm.jobContent" type="textarea" :rows="3" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 家庭信息 -->
        <div class="drawer-header-section">家庭信息</div>
        <div class="drawer-content-body">
          <el-row>
            <el-col :span="24">
              <el-form-item label="家庭住址" prop="homeAddress">
                <div style="display:flex; gap: 10px; width: 100%;">
                  <el-cascader
                    v-model="homeAddressSelection"
                    :options="provinceOptions"
                    :props="cascaderProps"
                    placeholder="请选择"
                    style="width: 200px"
                    clearable
                    filterable
                    @change="handleHomeAddressChange"
                  />
                  <el-input v-model="contactForm.homeAddressDetail" placeholder="请输入详细地址" style="flex: 1" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="家庭情况" prop="familyStatus">
                <el-input v-model="contactForm.familyStatus" placeholder="请输入家庭情况" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="爱好" prop="hobby">
                <el-input v-model="contactForm.hobby" placeholder="请输入爱好" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性格特征" prop="characterTrait">
                <el-input v-model="contactForm.characterTrait" placeholder="请输入性格特征" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="是否抽烟" prop="isSmoke">
                <el-radio-group v-model="contactForm.isSmoke">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否喝酒" prop="isDrink">
                <el-radio-group v-model="contactForm.isDrink">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <div style="display: flex; justify-content: flex-end; gap: 10px; padding: 10px 20px 20px;">
          <el-button color="#9ca3af" style="color: #fff; border: none;" @click="contactVisible = false">取消</el-button>
          <el-button type="primary" style="background: #3b82f6; border-color: #3b82f6;" @click="handleSaveContact">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="AddCustomer">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listEnterpriseScale } from "@/api/customer/enterpriseScale";
import { listDictByType, listCommonDict, listCustomerTypeOption } from "@/api/customer/customerDict";
import { listLevel } from "@/api/customer/customerLevel";
import { listUser } from "@/api/system/user";
import { addPool } from "@/api/customer/customerPool";
import { listProvinceWithCities } from "@/api/customer/addressArea";
import { listDept } from "@/api/system/dept";
import { selectStaffOptionList } from "@/api/customer/crmStaff";
import { listCompanyOption } from "@/api/customer/customerInfo";

const { proxy } = getCurrentInstance();
const router = useRouter();

// 移除所有系统字典依赖，全部走业务表
const industryOptions = ref([]);
const scaleOptions = ref([]);
const sourceOptions = ref([]);
const categoryOptions = ref([]);
const levelOptions = ref([]);
const corpTypeOptions = ref([]);
const staffOptions = ref([]);
const companyOptions = ref([]);
const loading = ref(false);
const queryRef = ref(null);

// 省市级联选择器数据
const provinceOptions = ref([]);  // 省级列表（含children=市级）
const addressSelection = ref([]);  // 级联选中值 [provinceId, cityId]

// 级联选择器配置（checkStrictly=true 允许只选省不选市）
const cascaderProps = {
  value: 'id',
  label: 'areaName',
  children: 'children',
  checkStrictly: true,
  emitPath: true
};

/** 省市选择变化回调，更新 form 中的 provinceId / cityId */
const handleAddressChange = (val) => {
  if (val && val.length >= 1) {
    form.provinceId = val[0];
    form.cityId = val.length >= 2 ? val[1] : undefined;
  } else {
    form.provinceId = undefined;
    form.cityId = undefined;
  }
};

const form = reactive({
  belongCompanyId: undefined,
  customerName: '',
  bizName: '',
  enterpriseName: '',
  customerSourceId: undefined,
  enterpriseTypeId: undefined,
  enterpriseScaleId: undefined,
  customerCategoryId: undefined,
  industryId: undefined,
  customerLevelId: undefined,
  phone: '',
  fax: '',
  website: '',
  zip: '',
  email: '',
  provinceId: undefined,
  cityId: undefined,
  districtId: undefined,
  detailAddress: '',
  socialCode: '',
  legalPerson: '',
  capital: '',
  org: '',
  foundDate: '',
  cancelDate: '',
  regStatus: '',
  paidCapital: '',
  bizAddress: '',
  businessLicense: '',   // 营业执照 ossId
  idCardFront: '',       // 正面身份证 ossId
  idCardBack: '',        // 反面身份证 ossId
  managerId: undefined,
  supportId: undefined,
  purchaseScale: '',
  creditAmount: 0, // 信用额度
  temporaryQuota: 0, // 临时额度
  salesTarget: '',
  remark: '',
  contacts: []
});

// 表单校验规则（全量汉化提示）
const rules = reactive({
  belongCompanyId: [{ required: true, message: "所属公司不能为空", trigger: "change" }],
  customerName: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
  customerSourceId: [{ required: true, message: "客户来源不能为空", trigger: "change" }],
  enterpriseTypeId: [{ required: true, message: "企业类型不能为空", trigger: "change" }],
  enterpriseScaleId: [{ required: true, message: "企业规模不能为空", trigger: "change" }],
  customerCategoryId: [{ required: true, message: "客户类别不能为空", trigger: "change" }],
  industryId: [{ required: true, message: "所属行业不能为空", trigger: "change" }],
  customerLevelId: [{ required: true, message: "客户等级不能为空", trigger: "change" }]
});

/** 查询具体选项集合 */
const getAllOptions = async () => {
  try {
    industryOptions.value = (await listIndustryCategory()).data || [];
  } catch (e) {
    console.error('获取行业分类失败:', e);
  }
  
  try {
    scaleOptions.value = (await listEnterpriseScale()).data || [];
  } catch (e) {
    console.error('获取企业规模失败:', e);
  }
  
  try {
    levelOptions.value = (await listLevel()).rows || [];
  } catch (e) {
    console.error('获取客户等级失败:', e);
  }
  
  try {
    // 字典项查询 - 客户来源从通用字典 K0001 查询
    sourceOptions.value = (await listCommonDict("K0001")).data || [];
  } catch (e) {
    console.error('获取客户来源失败:', e);
  }
  
  try {
    // 客户类别从 com_customer_type 表查询
    categoryOptions.value = (await listCustomerTypeOption()).data || [];
  } catch (e) {
    console.error('获取客户类别失败:', e);
  }
  
  try {
    corpTypeOptions.value = (await listDictByType("enterprise_type")).data || [];
  } catch (e) {
    console.error('获取企业类型失败:', e);
  }
  
  try {
    // 人员与公司
    staffOptions.value = (await selectStaffOptionList()).data || [];
  } catch (e) {
    console.error('获取人员列表失败:', e);
  }
  
  try {
    companyOptions.value = (await listCompanyOption()).data || [];
  } catch (e) {
    console.error('获取公司列表失败:', e);
  }
  
  try {
    // 地址
    provinceOptions.value = (await listProvinceWithCities()).data || [];
  } catch (e) {
    console.error('获取省市数据失败:', e);
  }
};

onMounted(() => {
  getAllOptions();
});

const handleBack = () => {
  router.back();
};

/** 保存逻辑 */
const handleSubmit = () => {
  queryRef.value.validate(valid => {
    if (valid) {
      loading.value = true;

      // 构建后端期望的结构 - 基本客户信息
      const submitData = {
        belongCompanyId: form.belongCompanyId,
        customerName: form.customerName,
        businessCustomerName: form.enterpriseName, // 企业名称 -> 工商名称
        shortName: form.bizName, // 企业别称
        customerSourceId: form.customerSourceId,
        enterpriseTypeId: form.enterpriseTypeId,
        enterpriseScaleId: form.enterpriseScaleId,
        customerTypeId: form.customerCategoryId, // 客户类别 -> 客户类型ID
        industryCategoryId: form.industryId, // 所属行业
        customerLevelId: form.customerLevelId,
        landline: form.phone, // 电话 -> 固定电话
        fax: form.fax,
        url: form.website, // 网址
        postCode: form.zip, // 邮政编码
        email: form.email,
        regProvincialNo: form.provinceId,
        regCityNo: form.cityId,
        regCountyNo: form.districtId,
        address: form.detailAddress, // 详细地址 -> 注册地址
        annualProcurementScale: form.purchaseScale, // 采购规模
        salesTarget: form.salesTarget,
        remark: form.remark,
        
        // 营业执照 ossId（同时存入客户主表和工商信息子表）
        businessLicense: form.businessLicense || undefined,
        // 法人证件（正面+反面身份证 ossId 合并，逗号分隔）
        legalPersonCardUrl: [form.idCardFront, form.idCardBack].filter(Boolean).join(',') || undefined,
        
        // 工商信息子对象
        customerBusinessBo: {
          businessCustomerName: form.enterpriseName,
          socialCreditCode: form.socialCode,
          legalPersonName: form.legalPerson,
          registeredCapital: form.capital,
          paidInCapital: form.paidCapital,
          establishmentDate: form.foundDate,
          revocationDate: form.cancelDate,
          registrationStatus: form.regStatus,
          registrationAuthority: form.org,
          businessAddress: form.bizAddress,
          businessLicense: form.businessLicense || undefined,
          legalPersonCardUrl: [form.idCardFront, form.idCardBack].filter(Boolean).join(',') || undefined
        },
        
        // 销售信息子对象
        customerSalesInfoBo: {
          salesPersonId: form.managerId,
          serviceStaffId: form.supportId,
          creditAmount: form.creditAmount || 0,
          temporaryQuota: form.temporaryQuota || 0
        },
        
        // 联系人列表
        customerContactBoList: form.contacts
      };

      addPool(submitData).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        router.back();
      }).catch(error => {
        proxy.$modal.msgError(error.message || "新增失败，请重试");
      }).finally(() => {
        loading.value = false;
      });
    } else {
      proxy.$modal.msgError("表单校验失败，请检查输入项");
    }
  });
};

// 联系人抽屉相关逻辑
const contactVisible = ref(false);
const contactRef = ref(null);
const contactForm = reactive({
  contactName: '',
  type: '1',
  gender: '1',
  age: '',
  nativePlace: '',
  birthday: '',
  remark: '',
  jobStatus: '1',
  phone: '',
  deptName: '',
  roleName: '',
  officePhone: '',
  provinceId: undefined,
  cityId: undefined,
  detailAddress: '',
  jobContent: '',
  homeProvinceId: undefined,
  homeCityId: undefined,
  homeAddressDetail: '',
  familyStatus: '',
  hobby: '',
  characterTrait: '',
  isSmoke: '0',
  isDrink: '0'
});

// 联系人级联选择选中值
const officeAddressSelection = ref([]);
const homeAddressSelection = ref([]);

/** 联系人办公地址变化 */
const handleOfficeAddressChange = (val) => {
  if (val && val.length >= 1) {
    contactForm.provinceId = val[0];
    contactForm.cityId = val.length >= 2 ? val[1] : undefined;
  } else {
    contactForm.provinceId = undefined;
    contactForm.cityId = undefined;
  }
};

/** 联系人家庭住址变化 */
const handleHomeAddressChange = (val) => {
  if (val && val.length >= 1) {
    contactForm.homeProvinceId = val[0];
    contactForm.homeCityId = val.length >= 2 ? val[1] : undefined;
  } else {
    contactForm.homeProvinceId = undefined;
    contactForm.homeCityId = undefined;
  }
};

const contactRules = reactive({
  contactName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  phone: [{ required: true, message: "手机号码不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "部门不能为空", trigger: "blur" }],
  officeAddress: [{ 
    required: true, 
    validator: (rule, value, callback) => {
      if (!contactForm.provinceId) {
        callback(new Error("办公地址省份不能为空"));
      } else if (!contactForm.detailAddress) {
        callback(new Error("办公详细地址不能为空"));
      } else {
        callback();
      }
    }, 
    trigger: "change" 
  }]
});

/** 新增联系人按钮 */
const handleAddContact = () => {
  // 重置表单
  Object.assign(contactForm, {
    contactName: '', type: '1', gender: '1', age: '', nativePlace: '', 
    birthday: '', remark: '', jobStatus: '1', phone: '', deptName: '', 
    roleName: '', officePhone: '', provinceId: undefined, cityId: undefined, detailAddress: '', 
    jobContent: '', homeProvinceId: undefined, homeCityId: undefined, homeAddressDetail: '', 
    familyStatus: '', hobby: '', characterTrait: '', isSmoke: '0', isDrink: '0'
  });
  officeAddressSelection.value = [];
  homeAddressSelection.value = [];
  contactVisible.value = true;
};

/** 保存联系人到列表 */
const handleSaveContact = () => {
  contactRef.value.validate(valid => {
    if (valid) {
      form.contacts.push({ ...contactForm });
      contactVisible.value = false;
      proxy.$modal.msgSuccess("联系人已添加到列表");
    }
  });
};

/** 删除联系人 */
const handleDeleteContact = (index) => {
  form.contacts.splice(index, 1);
};

onMounted(() => {
  getAllOptions();
});
</script>

<style scoped lang="scss">
.add-customer-container {
  background-color: #fff;
  min-height: 100vh;
}

.drawer-header-section {
  background-color: #f0f7ff;
  color: #3b82f6;
  padding: 8px 15px;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.drawer-row {
  margin-bottom: 5px;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #f1f5f9;
  position: sticky;
  top: 0;
  z-index: 10;
  background: #fff;

  .left {
    display: flex;
    align-items: center;
    .breadcrumb {
      font-size: 14px;
      color: #64748b;
      .highlight {
        color: #ef4444; // 图片中的客户编号是红色的
        font-weight: 500;
      }
    }
  }

  .submit-btn {
    background-color: #3b82f6;
    border-color: #3b82f6;
  }
}

.form-body {
  padding: 20px 30px;
}

.section-container {
  margin-bottom: 30px;
  border-bottom: 1px solid #f1f5f9;
  padding-bottom: 20px;
  &.no-border {
    border-bottom: none;
  }

  .section-header {
    font-size: 15px;
    font-weight: bold;
    color: #1e293b;
    margin-bottom: 20px;
    &.flex-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

// 核心：响应用户要求的“边框调大”
:deep(.el-input__wrapper), :deep(.el-select__wrapper) {
  background-color: #f8fafc !important; // 匹配图片中的浅灰色背景
  box-shadow: 0 0 0 1px #cbd5e1 inset !important; // 加深边框颜色（原本是很淡的 e2e8f0，调至 cbd5e1）
  border-radius: 4px;
  transition: all 0.2s;
  
  &:hover, &.is-focus {
    box-shadow: 0 0 0 1px #3b82f6 inset !important; // 聚焦时改为蓝色
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #334155;
  &::before {
    margin-right: 4px;
  }
}

.upload-square {
  width: 120px;
  height: 120px;
  border: 1px dashed #cbd5e1;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-color: #f8fafc;
  font-size: 24px;
  color: #94a3b8;
  &:hover {
    border-color: #3b82f6;
    color: #3b82f6;
  }
}

.contact-table {
  :deep(th.el-table__cell) {
    background-color: #f8fafc !important;
  }
}
</style>
