<template>
  <el-drawer
    v-model="visible"
    title="编辑公海客户"
    size="80%"
    append-to-body
    class="customer-form-drawer"
  >
    <div class="form-container" v-loading="loading">
      <div class="form-toolbar">
        <div class="toolbar-left">
          <span class="breadcrumb">基本信息 / <span class="highlight">客户编号: {{ form.customerNo }}</span></span>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" icon="Check" @click="handleSubmit" :loading="submitting">提交</el-button>
          <el-button @click="visible = false">取消</el-button>
        </div>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" label-position="right" label-suffix="：">
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="所属公司" required prop="belongCompanyId">
                <el-select v-model="form.belongCompanyId" placeholder="请选择" class="w100" clearable>
                  <el-option v-for="item in companyOptions" :key="item.id" :label="item.companyName" :value="String(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="请输入客户名称" class="w100" 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="请输入工商名称" class="w100" 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" clearable>
                  <el-option v-for="item in dict.K0001" :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" clearable>
                  <el-option v-for="item in dict.Q0001" :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" clearable>
                  <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" clearable>
                  <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="item.id" :label="item.levelName" :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="请输入固定电话" class="w100" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="传真" prop="fax">
                <el-input v-model="form.fax" placeholder="请输入传真" class="w100" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="网址" prop="url">
                <el-input v-model="form.url" placeholder="请输入网址" class="w100" 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="请输入邮政编码" class="w100" maxlength="6" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" class="w100" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="详细地址" prop="areaArray">
                <div class="address-group">
                  <el-cascader
                    v-model="form.areaArray"
                    :options="areaOptions"
                    :props="{ label: 'areaName', value: 'id', children: 'children' }"
                    placeholder="请选择"
                    class="flex1"
                    @change="handleAreaChange"
                  />
                  <el-input v-model="form.address" placeholder="请输入详细地址" class="flex1" maxlength="200" show-word-limit />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 工商信息 -->
        <div class="form-section">
          <div class="section-title">工商信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="企业工商名称" prop="businessCustomerName">
                <el-input v-model="form.businessCustomerName" class="w100" maxlength="100" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="社会信用代码" prop="socialCreditCode">
                <el-input v-model="form.socialCreditCode" class="w100" maxlength="18" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="法人姓名" prop="legalPersonName">
                <el-input v-model="form.legalPersonName" class="w100" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="注册资本" prop="registeredCapital">
                <el-input v-model="form.registeredCapital" class="w100" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="登记机关" prop="registrationAuthority">
                <el-input v-model="form.registrationAuthority" class="w100" maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成立日期">
                <el-date-picker v-model="form.establishmentDate" type="date" value-format="YYYY-MM-DD" 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.revocationDate" type="date" value-format="YYYY-MM-DD" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="登记状态">
                <el-select v-model="form.registrationStatus" placeholder="请选择" class="w100" clearable>
                  <el-option v-for="item in dict.registration_status" :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="paidInCapital">
                <el-input v-model="form.paidInCapital" class="w100" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细地址" prop="businessAddress">
                <el-input v-model="form.businessAddress" placeholder="请输入详细地址" class="w100" maxlength="200" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="mt-20">
            <el-col :span="8">
              <el-form-item label="营业执照">
                <image-upload v-model="form.businessLicense" :limit="1" :is-show-tip="false" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="正面身份证">
                <image-upload v-model="form.legalPersonCardFront" :limit="1" :is-show-tip="false" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="反面身份证">
                <image-upload v-model="form.legalPersonCardBack" :limit="1" :is-show-tip="false" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

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

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, isRef } from 'vue';
import { getPool as getCustomerInfo, updatePool as updateCustomerInfo, listCompanyOption, listLevelOption } from "@/api/customer/customerPool";
import { listComStaff } from "@/api/system/comStaff/index";
import { listProvinceWithCities } from "@/api/customer/addressArea";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listEnterpriseScale } from "@/api/customer/enterpriseScale";
import { listCustomerTypeOption } from "@/api/customer/customerDict";
import ImageUpload from "@/components/ImageUpload";

const proxy = getCurrentInstance().proxy;
const dict = reactive(proxy.useDict(
  'K0001', 
  'Q0001',
  'registration_status'
));

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

const emit = defineEmits(['success']);

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: [], 
  address: '',
  // 工商信息
  socialCreditCode: '',
  legalPersonName: '',
  registeredCapital: '',
  paidInCapital: '',
  establishmentDate: '',
  revocationDate: '',
  registrationStatus: '',
  registrationAuthority: '',
  businessAddress: '',
  businessLicense: undefined,
  legalPersonCardUrl: undefined,
  legalPersonCardFront: undefined,
  legalPersonCardBack: undefined,
  // 销售信息
  salesPersonId: undefined,
  serviceStaffId: undefined,
  annualProcurementScale: undefined,
  salesTarget: undefined,
  contacts: []
});

const rules = {
  customerName: [
    { required: true, message: "客户名称不能为空", trigger: "blur" },
    { max: 100, message: "客户名称不能超过100个字符", trigger: "blur" }
  ],
  belongCompanyId: [{ required: true, message: "所属公司不能为空", trigger: "change" }],
  businessCustomerName: [{ max: 100, message: "工商名称不能超过100个字符", trigger: "blur" }],
  landline: [
    { 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" }
  ],
  socialCreditCode: [
    { pattern: /^[A-Za-z0-9]{18}$/, message: "请输入正确的18位统一社会信用代码", trigger: "blur" }
  ],
  legalPersonName: [{ max: 50, message: "法人姓名不能超过50个字符", trigger: "blur" }],
  registeredCapital: [{ max: 50, message: "注册资本不能超过50个字符", trigger: "blur" }],
  registrationAuthority: [{ max: 100, message: "登记机关不能超过100个字符", trigger: "blur" }],
  paidInCapital: [{ max: 50, message: "实缴资本不能超过50个字符", trigger: "blur" }],
  businessAddress: [{ max: 200, message: "详细地址不能超过200个字符", trigger: "blur" }]
};

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

const open = (id) => {
  if (!id) return;
  visible.value = true;
  reset();
  loadData(id);
};

const reset = () => {
  Object.assign(form, {
    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: [], address: '',
    socialCreditCode: '', legalPersonName: '', registeredCapital: '', paidInCapital: '',
    establishmentDate: '', revocationDate: '', registrationStatus: '', registrationAuthority: '',
    businessAddress: '', businessLicense: '', legalPersonCardUrl: '',
    salesPersonId: undefined, serviceStaffId: undefined, annualProcurementScale: undefined, salesTarget: undefined,
    contacts: []
  });
  if (formRef.value) formRef.value.resetFields();
};

const loadData = (id) => {
  loading.value = true;
  getCustomerInfo(id).then(res => {
    const data = res.data;
    const biz = data.customerBusinessInfoVo || {};
    const sales = data.customerSalesInfoVo || {};

    // 基本信息回显 (统一转为 String 处理 ID 类型)
    form.id = data.id;
    form.customerNo = data.customerNo;
    form.customerName = data.customerName;
    form.businessCustomerName = data.businessCustomerName;
    // 关联项回显 (仅在有名称字段时回显，防止显示数字 ID；禁止模拟数据)
    form.belongCompanyId = data.companyName ? String(data.belongCompanyId) : undefined;
    form.customerLevelId = data.customerLevelName ? String(data.customerLevelId) : undefined;
    form.salesPersonId = data.salesPersonName ? String(sales.salesPersonId) : undefined;
    form.serviceStaffId = data.serviceStaffName ? String(sales.serviceStaffId) : undefined;

    // 字典项回显 (仅在通过名称匹配成功时回显，禁止 ID 兜底)
    const getDictValue = (dictList, label) => {
      const list = isRef(dictList) ? dictList.value : dictList;
      return (list || []).find(i => i.label === label)?.value;
    };

    form.enterpriseTypeId = getDictValue(dict.Q0001, data.enterpriseTypeName);
    form.customerTypeId = data.customerTypeId ? String(data.customerTypeId) : undefined;

    // 基础字典项 (这些通常已有 code 映射)
    form.customerSourceId = sales.customerSource ? String(sales.customerSource).split(',')[0] : undefined;
    form.enterpriseScaleId = (data.enterpriseScaleId || data.enterpriseScale) ? String(data.enterpriseScaleId || data.enterpriseScale) : undefined;
    form.industryCategoryId = (data.industryCategoryId || data.industryCategory) ? Number(data.industryCategoryId || data.industryCategory) : undefined;
    form.registrationStatus = biz.registrationStatus;
    
    form.landline = data.landline;
    form.fax = data.fax;
    form.url = data.url;
    form.postCode = data.postCode;
    form.email = data.email;
    form.address = data.address;
    
    // 地区回显
    form.regProvincialNo = data.regProvincialNo;
    form.regCityNo = data.regCityNo;
    form.regCountyNo = data.regCountyNo;
    if (data.regProvincialNo && data.regCityNo && data.regCountyNo) {
      form.areaArray = [Number(data.regProvincialNo), Number(data.regCityNo), Number(data.regCountyNo)];
    }

    // 工商信息回显
    form.socialCreditCode = biz.socialCreditCode;
    form.legalPersonName = biz.legalPersonName;
    form.registeredCapital = biz.registeredCapital;
    form.paidInCapital = biz.paidInCapital;
    form.establishmentDate = biz.establishmentDate;
    form.revocationDate = biz.revocationDate;
    form.registrationAuthority = biz.registrationAuthority;
    form.businessLicense = biz.businessLicense;
    
    // 拆分身份证正反面
    if (biz.legalPersonCardUrl) {
      const cards = biz.legalPersonCardUrl.split(',');
      form.legalPersonCardFront = cards[0] || undefined;
      form.legalPersonCardBack = cards[1] || undefined;
    } else {
      form.legalPersonCardFront = undefined;
      form.legalPersonCardBack = undefined;
    }
    form.legalPersonCardUrl = biz.legalPersonCardUrl;

    form.annualProcurementScale = data.annualProcurementScale;
    form.salesTarget = data.salesTarget;

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

const handleAreaChange = (val) => {
  if (val && val.length === 3) {
    form.regProvincialNo = String(val[0]);
    form.regCityNo = String(val[1]);
    form.regCountyNo = String(val[2]);
  } else {
    form.regProvincialNo = '';
    form.regCityNo = '';
    form.regCountyNo = '';
  }
};

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      submitting.value = true;
      // 提交前组装数据，保持后端要求的结构
      const postData = {
        ...form,
        customerBusinessInfoVo: {
          socialCreditCode: form.socialCreditCode,
          legalPersonName: form.legalPersonName,
          registeredCapital: form.registeredCapital,
          paidInCapital: form.paidInCapital,
          establishmentDate: form.establishmentDate,
          revocationDate: form.revocationDate,
          registrationStatus: form.registrationStatus,
          registrationAuthority: form.registrationAuthority,
          businessAddress: form.businessAddress,
          businessLicense: form.businessLicense,
          legalPersonCardUrl: [form.legalPersonCardFront, form.legalPersonCardBack].filter(Boolean).join(',')
        },
        customerSalesInfoVo: {
          salesPersonId: form.salesPersonId,
          serviceStaffId: form.serviceStaffId
        }
      };
      updateCustomerInfo(postData).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        visible.value = false;
        emit('success');
      }).finally(() => submitting.value = false);
    }
  });
};

onMounted(() => {
  listCompanyOption().then(res => companyOptions.value = res.data || []);
  listLevelOption().then(res => levelOptions.value = res.data || []);
  listComStaff({ pageSize: 1000 }).then(res => staffOptions.value = res.rows || res.data || []);
  listProvinceWithCities().then(res => {
    const list = res.rows || [];
    areaOptions.value = handleTree(list, "id", "parentId");
  });
  listIndustryCategory().then(res => industryOptions.value = res.data || res.rows || []);
  listEnterpriseScale().then(res => scaleOptions.value = res.data || res.rows || []);
  listCustomerTypeOption().then(res => categoryOptions.value = res.data || res.rows || []);
});

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 scoped lang="scss">
.customer-form-drawer { 
  :deep(.el-drawer__header) { margin-bottom: 15px; padding: 20px; border-bottom: 1px solid #f1f5f9; }
  :deep(.el-drawer__body) { padding: 0; } 
}
.form-container { 
  padding: 24px; background-color: #fff; min-height: 100%;
  &::-webkit-scrollbar { width: 0; display: none; }
  scrollbar-width: none;
}
.form-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #f1f5f9; 
  .breadcrumb { font-size: 14px; color: #64748b; .highlight { color: #f43f5e; font-weight: bold; } }
}
.form-section { margin-bottom: 30px; }
.section-title { font-size: 16px; font-weight: bold; color: #409eff; margin-bottom: 15px; }
.w100 { width: 100% !important; }
.flex1 { flex: 1; }
.address-group { display: flex; gap: 10px; width: 100%; }
.mt-20 { margin-top: 20px; }
.mt-10 { margin-top: 10px; }
:deep(.el-form-item__label) { font-weight: normal; color: #64748b; white-space: nowrap; }
:deep(.el-form-item) { margin-bottom: 22px; }
</style>
