<template>
  <el-drawer
    v-model="visible"
    size="90%"
    title="编辑客户"
    direction="rtl"
    @close="handleBack"
    destroy-on-close
    class="form-drawer custom-edit-drawer"
  >
    <template #header>
      <div class="drawer-header-custom">
        <div class="header-left">
           <el-button link icon="ArrowLeft" @click="handleBack">返回</el-button>
           <span class="header-divider">|</span>
           <span class="header-title">基本信息 / <span class="customer-no">客户编号：{{ form.customerNo }}</span></span>
        </div>
        <div class="header-ops">
          <el-button type="primary" icon="Check" @click="handleSubmit" class="submit-btn" :loading="submitting">提交</el-button>
        </div>
      </div>
    </template>

    <div class="add-customer-container" v-loading="loading">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="custom-form" label-position="right" label-suffix="：">
        <div class="form-title">基本信息</div>
        <div class="form-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="所属公司" prop="belongCompanyId">
                <el-select v-model="form.belongCompanyId" placeholder="请选择" class="w100">
                  <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="客户名称" prop="customerName">
                <el-input v-model="form.customerName" placeholder="请输入客户名称" maxlength="100" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工商名称" prop="businessCustomerName">
                <el-input v-model="form.businessCustomerName" placeholder="请输入工商名称" maxlength="100" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户来源" prop="customerSourceId">
                <el-select v-model="form.customerSourceId" placeholder="请选择" class="w100">
                  <el-option v-for="item in sourceOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业类型" prop="enterpriseTypeId">
                <el-select v-model="form.enterpriseTypeId" placeholder="请选择" class="w100">
                  <el-option v-for="item in corpTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </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="w100" clearable>
                   <el-option v-for="item in scaleOptions" :key="String(item.id)" :label="item.enterpriseScaleName || item.enterpriseScale || item.label || item.name" :value="String(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="w100">
                    <el-option v-for="item in categoryOptions" :key="String(item.id)" :label="item.customerTypeName || item.customerCategoryName || item.typeName || item.name" :value="String(item.id)" />
                  </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="w100">
                  <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="客户等级" prop="customerLevelId">
                <el-select v-model="form.customerLevelId" placeholder="请选择" class="w100" clearable>
                  <el-option v-for="item in levelOptions" :key="String(item.id)" :label="item.levelName || item.customerLevelName || item.label || item.name" :value="String(item.id)" />
                </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="请输入固定电话" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="传真" prop="fax">
                <el-input v-model="form.fax" placeholder="请输入传真" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="网址" prop="url">
                <el-input v-model="form.url" placeholder="请输入网址" maxlength="100" />
              </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="请输入邮政编码" maxlength="6" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="详细地址" prop="areaArray">
                 <div style="display: flex; gap: 10px; width: 100%;">
                    <el-cascader
                      v-model="form.areaArray"
                      :options="areaOptions"
                      :props="{ label: 'areaName', value: 'id', children: 'children' }"
                      placeholder="请选择省/市/县"
                      style="flex: 1"
                      clearable
                      @change="handleAreaChange"
                    />
                    <el-input v-model="form.address" placeholder="请输入详细地址" style="flex: 1.5" maxlength="200" show-word-limit />
                 </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-title">工商信息</div>
        <div class="form-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="企业工商名称" prop="customerBusinessBo.businessCustomerName">
                <el-input v-model="form.customerBusinessBo.businessCustomerName" maxlength="100" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="社会信用代码" prop="customerBusinessBo.socialCreditCode">
                <el-input v-model="form.customerBusinessBo.socialCreditCode" maxlength="18" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="法人姓名" prop="customerBusinessBo.legalPersonName">
                <el-input v-model="form.customerBusinessBo.legalPersonName" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="注册资本" prop="customerBusinessBo.registeredCapital">
                <el-input v-model="form.customerBusinessBo.registeredCapital" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="登记机关" prop="customerBusinessBo.registrationAuthority">
                <el-input v-model="form.customerBusinessBo.registrationAuthority" maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成立日期">
                <el-date-picker v-model="form.customerBusinessBo.establishmentDate" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="吊销日期">
                <el-date-picker v-model="form.customerBusinessBo.revocationDate" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="登记状态" prop="customerBusinessBo.registrationStatus">
                <el-input v-model="form.customerBusinessBo.registrationStatus" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实缴资本" prop="customerBusinessBo.paidInCapital">
                <el-input v-model="form.customerBusinessBo.paidInCapital" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细地址" prop="customerBusinessBo.businessAddress">
                <el-input v-model="form.customerBusinessBo.businessAddress" placeholder="请输入详细地址" maxlength="200" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="营业执照">
                <image-upload v-model="form.customerBusinessBo.businessLicense" :limit="1" :isShowTip="false" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="正面身份证">
                <image-upload v-model="form.idCardFront" :limit="1" :isShowTip="false" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="反面身份证">
                <image-upload v-model="form.idCardBack" :limit="1" :isShowTip="false" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-title">销售信息</div>
        <div class="form-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="负责人">
                 <el-select v-model="form.salesPersonId" placeholder="请选择" class="w100">
                   <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
                 </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客服支持">
                 <el-select v-model="form.serviceStaffId" placeholder="请选择" class="w100">
                   <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
                 </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="采购规模">
                 <el-input v-model="form.customerSalesInfoBo.procurementScale" placeholder="请输入采购规模">
                   <template #append>万</template>
                 </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="销售目标">
                 <el-input v-model="form.customerSalesInfoBo.salesTarget" placeholder="请输入销售目标">
                   <template #append>万</template>
                 </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
  </el-drawer>
</template>

<script setup name="CustomerValidEdit">
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { listCompanyOption, getCustomerInfo, updateCustomerInfo } from "@/api/customer/customerPool";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listLevel } from "@/api/customer/customerLevel";
import { listComStaff } from "@/api/system/comStaff/index";
import { listCustomerTypeOption } from "@/api/customer/customerDict";
import { listEnterpriseScale } from "@/api/customer/enterpriseScale";
import { listProvinceWithCities } from "@/api/customer/addressArea";
import { deptTreeSelect } from "@/api/system/dept";

const proxy = getCurrentInstance().proxy;
const { K0001: sourceOptions, Q0001: corpTypeOptions } = toRefs(reactive(proxy.useDict("K0001", "Q0001")));
const route = useRoute();
const router = useRouter();

const formRef = ref(null);
const loading = ref(false);
const visible = ref(false);
const submitting = ref(false);

const form = reactive({
  id: undefined,
  customerNo: '',
  belongCompanyId: undefined,
  customerName: '',
  businessCustomerName: '',
  customerSourceId: undefined,
  enterpriseTypeId: undefined,
  enterpriseScaleId: undefined,
  customerTypeId: undefined,
  industryCategoryId: undefined,
  customerLevelId: undefined,
  landline: '',
  fax: '',
  url: '',
  postCode: '',
  email: '',
  regProvincialNo: '',
  regCityNo: '',
  regCountyNo: '',
  areaArray: [],
  provincialCityCounty: '',
  address: '',
  salesPersonId: undefined,
  serviceStaffId: undefined,
  belongingDepartmentId: undefined,
  idCardFront: '',
  idCardBack: '',
  customerBusinessBo: {
    businessCustomerName: '', socialCreditCode: '', legalPersonName: '',
    registeredCapital: '', establishmentDate: '', registrationStatus: '',
    registrationAuthority: '', paidInCapital: '', revocationDate: '',
    businessAddress: '', businessLicense: '', legalPersonCardUrl: ''
  },
  customerSalesInfoBo: { procurementScale: '', salesTarget: '' }
});

const rules = reactive({
  belongCompanyId: [{ required: true, message: "所属公司不能为空", trigger: "change" }],
  customerName: [
    { required: true, message: "客户名称不能为空", trigger: "blur" },
    { max: 100, message: "客户名称不能超过100个字符", trigger: "blur" }
  ],
  businessCustomerName: [
    { required: true, message: "工商名称不能为空", trigger: "blur" },
    { max: 100, message: "工商名称不能超过100个字符", trigger: "blur" }
  ],
  customerSourceId: [{ required: true, message: "客户来源不能为空", trigger: "change" }],
  enterpriseTypeId: [{ 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" }],
  landline: [
    { required: true, message: "固定电话不能为空", trigger: "blur" },
    { pattern: /^([0-9-]{7,20})$/, message: "请输入正确的电话号码", trigger: "blur" }
  ],
  fax: [
    { pattern: /^([0-9-]{7,20})$/, message: "请输入正确的传真号码", trigger: "blur" }
  ],
  url: [
    { pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/, message: "请输入正确的网址", trigger: "blur" }
  ],
  postCode: [
    { pattern: /^\d{6}$/, message: "请输入正确的6位邮政编码", trigger: "blur" }
  ],
  email: [
    { pattern: /^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/, message: "请输入正确的邮箱地址", trigger: "blur" }
  ],
  areaArray: [{ required: true, message: "详细地区不能为空", trigger: "change", type: 'array' }],
  'customerBusinessBo.businessCustomerName': [{ max: 100, message: "企业工商名称不能超过100个字符", trigger: "blur" }],
  'customerBusinessBo.socialCreditCode': [
    { pattern: /^[A-Za-z0-9]{18}$/, message: "请输入正确的18位统一社会信用代码", trigger: "blur" }
  ],
  'customerBusinessBo.legalPersonName': [{ max: 50, message: "法人姓名不能超过50个字符", trigger: "blur" }],
  'customerBusinessBo.registeredCapital': [{ max: 50, message: "注册资本不能超过50个字符", trigger: "blur" }],
  'customerBusinessBo.registrationAuthority': [{ max: 100, message: "登记机关不能超过100个字符", trigger: "blur" }],
  'customerBusinessBo.registrationStatus': [{ max: 50, message: "登记状态不能超过50个字符", trigger: "blur" }],
  'customerBusinessBo.paidInCapital': [{ max: 50, message: "实缴资本不能超过50个字符", trigger: "blur" }],
  'customerBusinessBo.businessAddress': [{ max: 200, message: "详细地址不能超过200个字符", trigger: "blur" }]
});

const companyOptions = ref([]);
const industryOptions = ref([]);
const levelOptions = ref([]);
const staffOptions = ref([]);
const scaleOptions = ref([]);
const categoryOptions = ref([]);
const areaOptions = ref([]);
const deptOptions = ref([]);

const initOptions = async () => {
  listCompanyOption().then(res => companyOptions.value = res.data || []).catch(e => console.error("公司选项接口404或出错", e));
  listIndustryCategory().then(res => industryOptions.value = res.data || res.rows || []).catch(e => console.error("行业类别接口404或出错", e));
  listLevel().then(res => levelOptions.value = res.rows || []).catch(e => console.error("客户等级接口404或出错", e));
  listComStaff({ pageSize: 1000 }).then(res => staffOptions.value = res.rows || res.data || []).catch(e => console.error("员工选项接口404或出错", e));
  listEnterpriseScale().then(res => scaleOptions.value = res.data || res.rows || []).catch(e => console.error("企业规模接口404或出错", e));
  listCustomerTypeOption().then(res => {
    categoryOptions.value = res.data || res.rows || [];
  }).catch(e => {
    console.error("客户类别接口加载失败:", e);
  });
  listProvinceWithCities().then(res => {
    const list = res.rows || [];
    areaOptions.value = handleTree(list, "id", "parentId");
  }).catch(e => console.error("省市联动接口出错", e));
  deptTreeSelect().then(res => {
    const data = res.data || res.rows || [];
    deptOptions.value = proxy.handleTree(data, "deptId");
  }).catch(e => console.error("部门树接口404或出错", e));
};

const loadData = (id) => {
  loading.value = true;
  getCustomerInfo(id).then(res => {
    const data = res.data;
    if (!data) return;
    Object.assign(form, data);
    
    const biz = data.customerBusinessVo || data.customerBusinessInfoVo || {};
    form.customerBusinessBo = {
      customerId: data.id,
      businessCustomerName: biz.businessCustomerName || data.businessCustomerName,
      socialCreditCode: biz.socialCreditCode,
      legalPersonName: biz.legalPersonName,
      registeredCapital: biz.registeredCapital,
      registrationAuthority: biz.registrationAuthority,
      establishmentDate: biz.establishmentDate,
      revocationDate: biz.revocationDate,
      registrationStatus: biz.registrationStatus,
      paidInCapital: biz.paidInCapital,
      businessAddress: biz.businessAddress || data.address,
      businessLicense: biz.businessLicense,
      legalPersonCardUrl: biz.legalPersonCardUrl
    };

    const sales = data.customerSalesInfoVo || data.customerSalesVo || {};
    form.customerSalesInfoBo = {
      id: sales.id,
      customerId: data.id,
      procurementScale: sales.procurementScale || data.annualProcurementScale,
      salesTarget: sales.salesTarget || data.salesTarget
    };

    // 解析身份证回显
    const cardUrls = biz.legalPersonCardUrl ? biz.legalPersonCardUrl.split(',') : [];
    form.idCardFront = cardUrls[0] || '';
    form.idCardBack = cardUrls[1] || '';

    // 显式处理字典项回显和类型转换
    const sourceVal = data.customerSourceId || sales.customerSource || sales.customerSourceId;
    form.customerSourceId = sourceVal ? String(sourceVal).split(',')[0] : undefined;
    
    const typeVal = data.enterpriseTypeId || data.enterpriseType;
    form.enterpriseTypeId = typeVal ? String(typeVal) : undefined;

    const scaleVal = data.enterpriseScaleId || data.enterpriseScale || data.scaleId;
    form.enterpriseScaleId = scaleVal ? String(scaleVal) : undefined;

    form.customerTypeId = data.customerTypeId ? String(data.customerTypeId) : undefined;

    const industryVal = data.industryCategoryId || data.industryId;
    form.industryCategoryId = industryVal ? Number(industryVal) : undefined;

    const levelVal = data.customerLevelId || data.levelId || data.customerLevel;
    form.customerLevelId = levelVal ? String(levelVal) : undefined;
    
    // 地区回显处理
    if (data.regProvincialNo && data.regCityNo && data.regCountyNo) {
      form.areaArray = [Number(data.regProvincialNo), Number(data.regCityNo), Number(data.regCountyNo)];
    } else {
      form.areaArray = [];
    }

    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

const handleAreaChange = (val) => {
  if (val && val.length === 3) {
    form.regProvincialNo = val[0];
    form.regCityNo = val[1];
    form.regCountyNo = val[2];
    // 同步到 provincialCityCounty 以防后端其他地方用到
    form.provincialCityCounty = val.join(',');
  } else {
    form.regProvincialNo = '';
    form.regCityNo = '';
    form.regCountyNo = '';
    form.provincialCityCounty = '';
  }
};

const handleBack = () => { 
  visible.value = false;
  setTimeout(() => {
    router.push('/customer/valid');
  }, 300);
};

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      submitting.value = true;
      // 提交前合并身份证地址
      const cards = [];
      if (form.idCardFront) cards.push(form.idCardFront);
      if (form.idCardBack) cards.push(form.idCardBack);
      form.customerBusinessBo.legalPersonCardUrl = cards.join(',');

      updateCustomerInfo(form).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        handleBack();
      }).finally(() => {
        submitting.value = false;
      });
    }
  });
};

const open = (id) => {
  visible.value = true;
  loadData(id);
};

onMounted(() => {
  initOptions();
  const id = route.query.id;
  if (id) {
    loadData(id);
  }
});

defineExpose({ open });

/** 构造树型结构数据 */
function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let pId = d[config.parentId];
    if (childrenListMap[pId] == null) {
      childrenListMap[pId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[pId].push(d);
  }

  for (let d of data) {
    let pId = d[config.parentId];
    if (nodeIds[pId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}
</script>

<style lang="scss">
.el-overlay {
  .custom-edit-drawer {
    width: 90% !important;
    .el-drawer__header { margin-bottom: 0; padding: 0; }
    .el-drawer__body { padding: 24px; }

    .el-form-item__label {
      font-size: 13px;
      color: #606266;
      font-weight: normal !important;
      white-space: nowrap !important;
      overflow: visible !important;
      display: inline-block !important;
    }

    .form-title {
      font-weight: normal !important;
    }

    /* 隐藏上传组件提示语 */
    .el-upload__tip {
      display: none !important;
    }
  }
}

.drawer-header-custom {
  height: 64px; display: flex; justify-content: space-between; align-items: center;
  padding: 0 24px; border-bottom: 1px solid #f1f5f9; background-color: #fff; width: 100%;
  .header-left {
    display: flex; align-items: center; gap: 12px;
    .header-divider { color: #e2e8f0; }
  }
  .header-title { font-size: 14px; color: #1e293b; }
}

.form-title { 
  font-size: 13px; 
  color: #64748b; 
  margin: 32px 0 16px; 
  padding-bottom: 8px;
  border-bottom: 1px solid #f1f5f9;
}
.form-section { 
  padding: 8px 0; 
}

/* 统一输入组件宽度 */
.custom-form {
  .el-input, .el-select, .el-date-editor, .el-cascader, .el-tree-select {
    width: 100% !important;
  }
}
.upload-item { 
  display: flex; 
  flex-direction: column; 
  gap: 8px; 
}
.w100 { width: 100%; }
</style>
