<template>
  <el-drawer v-model="visible" size="90%" class="customer-detail-drawer" :with-header="false" :destroy-on-close="true">
    <div class="detail-container" v-loading="loading">
      <!-- 顶部 Header -->
      <div class="detail-header">
        <div class="header-left">
          <span class="customer-title">{{ customerData.customerName }}</span>
          <span class="customer-type">类型：{{ customerData.customerTypeName || '正式客户' }}</span>
        </div>
        <div class="header-right">
          <el-icon class="close-btn" @click="visible = false"><Close /></el-icon>
        </div>
      </div>

      <div class="detail-main">
        <!-- 左侧主内容区 -->
        <div class="main-content">
          <el-tabs v-model="activeContentTab" class="custom-tabs">
            <el-tab-pane label="客户资料" name="data">
              <div class="tab-scroll-pane">
                <!-- 基本信息 -->
                <div class="info-section">
                  <div class="section-header">
                    <span class="section-title">基本信息</span>
                    <el-button v-if="!isReadOnly" type="primary" class="blue-btn" icon="Edit" @click="handleEdit">编辑</el-button>
                  </div>
                  <el-row :gutter="40" class="info-grid">
                    <el-col :span="8"><div class="info-cell"><span class="label">工商名称</span><span class="value">{{ customerData.businessCustomerName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">归属公司</span><span class="value">{{ customerData.companyName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">客户来源</span><span class="value">{{ customerData.customerSourceName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">客户等级</span><span class="value">{{ customerData.customerLevelName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">企业规模</span><span class="value">{{ customerData.enterpriseScale }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">企业邮箱</span><span class="value">{{ customerData.email }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">办公电话</span><span class="value">{{ customerData.landline }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">行业</span><span class="value">{{ customerData.industryName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">国家</span><span class="value">中国</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">省份</span><span class="value">{{ customerData.regProvincialName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">城市</span><span class="value">{{ customerData.regCityName }}</span></div></el-col>
                    <el-col :span="24"><div class="info-cell"><span class="label">办公地址</span><span class="value">{{ customerData.address }}</span></div></el-col>
                  </el-row>
                </div>

                <div class="info-section">
                  <div class="section-header"><span class="section-title">工商信息</span></div>
                  <el-row :gutter="40" class="info-grid">
                    <el-col :span="8"><div class="info-cell"><span class="label">工商名称</span><span class="value">{{ bizInfo.businessCustomerName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">社会信用代码</span><span class="value">{{ bizInfo.socialCreditCode }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">法定代表人</span><span class="value">{{ bizInfo.legalPersonName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">注册资本</span><span class="value">{{ bizInfo.registeredCapital }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">成立日期</span><span class="value">{{ bizInfo.establishmentDate }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">吊销日期</span><span class="value">{{ bizInfo.revocationDate }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">登记状态</span><span class="value">{{ bizInfo.registrationStatus }}</span></div></el-col>
                    <el-col :span="16"><div class="info-cell"><span class="label">注册地址</span><span class="value">{{ bizInfo.businessAddress }}</span></div></el-col>
                    <el-col :span="8">
                      <div class="info-cell image-cell">
                        <span class="label">营业执照</span>
                        <div class="image-box">
                          <el-image 
                            v-if="bizInfo.businessLicense" 
                            :src="bizInfo.businessLicense" 
                            :preview-src-list="[bizInfo.businessLicense]"
                            fit="cover"
                            class="info-img"
                          />
                          <div v-else class="img-placeholder">暂无图片</div>
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="info-cell image-cell">
                        <span class="label">正面身份证</span>
                        <div class="image-box">
                          <el-image 
                            v-if="getCardImage(0)" 
                            :src="getCardImage(0)" 
                            :preview-src-list="[getCardImage(0)]"
                            fit="cover"
                            class="info-img"
                          />
                          <div v-else class="img-placeholder">暂无图片</div>
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="info-cell image-cell">
                        <span class="label">反面身份证</span>
                        <div class="image-box">
                          <el-image 
                            v-if="getCardImage(1)" 
                            :src="getCardImage(1)" 
                            :preview-src-list="[getCardImage(1)]"
                            fit="cover"
                            class="info-img"
                          />
                          <div v-else class="img-placeholder">暂无图片</div>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </div>

                <div class="info-section no-border">
                  <div class="section-header"><span class="section-title">销售信息</span></div>
                  <el-row :gutter="40" class="info-grid">
                    <el-col :span="8"><div class="info-cell"><span class="label">合作状况</span><span class="value">{{ customerData.cooperationName || '未合作' }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">开票类型</span><span class="value">{{ customerData.invoiceTypeName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">归属部门</span><span class="value">{{ customerData.deptName }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">采购规模(万)</span><span class="value">{{ customerData.annualProcurementScale || 0 }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">销售目标(万)</span><span class="value">{{ customerData.salesTarget || 0 }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">采购方式</span><span class="value">办公采购</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">信用等级</span><span class="value">{{ salesInfo.creditLevel || 'A' }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">授信额度</span><span class="value">{{ salesInfo.creditAmount || 0.00 }}</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">应收账款</span><span class="value">0.00</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">预收账款</span><span class="value">0.00</span></div></el-col>
                    <el-col :span="8"><div class="info-cell"><span class="label">剩余额度</span><span class="value">0.00</span></div></el-col>
                  </el-row>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="客户联系人" name="contact">
              <div class="tab-scroll-pane">
                <div class="contact-toolbar">
                  <el-button v-if="!isReadOnly" type="primary" icon="Plus" class="blue-btn" @click="handleAddContact">新增</el-button>
                </div>
                <el-table :data="customerData.customerContactVoList || []" 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="120">
                    <template #default="scope">
                      <el-button v-if="!isReadOnly" link type="primary" @click="handleEditContact(scope.row)">编辑</el-button>
                      <el-button v-if="!isReadOnly" link type="danger" @click="handleDeleteContact(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                  <template #empty>暂无数据</template>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 右侧侧边栏 (通用业务活动组件) -->
        <div class="sidebar-content">
          <BusinessActivity 
            v-if="customerData.id"
            :business-id="customerData.id" 
            business-type="customer"
            :info-data="{
              ...customerData,
              customerName: customerData.customerName,
              deptName: customerData.deptName || '',
              department: customerData.deptName || '',
              industryName: customerData.industryName || '',
              profession: customerData.industryName || ''
            }"
            @update-readonly="val => isReadOnly = val"
          />
        </div>
      </div>
    </div>

    <!-- 客户联系人抽屉 -->
    <el-drawer v-model="contactDrawerVisible" direction="rtl" size="80%" destroy-on-close :with-header="false" class="contact-form-drawer" append-to-body>
      <div class="drawer-header-compact" style="height: 40px; padding: 0 16px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; background: #fff;">
        <span style="font-size: 15px; font-weight: 600; color: #333;">{{ contactForm.id ? '编辑客户联系人' : '新建客户联系人' }}</span>
        <el-icon @click="contactDrawerVisible = false" style="cursor: pointer; font-size: 18px; color: #94a3b8;"><Close /></el-icon>
      </div>
      <el-form :model="contactForm" :rules="contactRules" ref="contactFormRef" label-width="100px" label-position="right" label-suffix="：">
        <!-- 基本信息 Section -->
        <div class="form-section-header">基本信息</div>
        <div class="form-section-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 value="1">公司职员</el-radio>
                  <el-radio value="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 value="1">男</el-radio>
                  <el-radio value="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="年龄" required 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-05-01" 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>

        <!-- 办公信息 Section -->
        <div class="form-section-header">办公信息</div>
        <div class="form-section-body">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="在职状态" prop="jobStatus">
                <el-radio-group v-model="contactForm.jobStatus">
                  <el-radio value="1">在职</el-radio>
                  <el-radio value="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="deptId">
                <el-tree-select
                  v-model="contactForm.deptId"
                  :data="deptOptions"
                  :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                  value-key="deptId"
                  placeholder="请选择部门"
                  check-strictly
                  style="width: 100%"
                />
              </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="办公座机" required 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="addressDetail">
                <div class="address-group">
                  <el-cascader 
                    v-model="officeAddr" 
                    :options="areaOptions" 
                    :props="{ label: 'areaName', value: 'id', children: 'children' }"
                    placeholder="请选择" 
                    style="width: 200px" 
                  />
                  <el-input v-model="contactForm.addressDetail" 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>

        <!-- 家庭信息 Section -->
        <div class="form-section-header">家庭信息</div>
        <div class="form-section-body">
          <el-row>
            <el-col :span="24">
              <el-form-item label="家庭住址" prop="homeDetailAddress">
                <div class="address-group">
                  <el-cascader 
                    v-model="homeAddr" 
                    :options="areaOptions" 
                    :props="{ label: 'areaName', value: 'id', children: 'children' }"
                    placeholder="请选择" 
                    style="width: 200px" 
                  />
                  <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 value="1">是</el-radio><el-radio value="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 value="1">是</el-radio><el-radio value="0">否</el-radio></el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="drawer-footer">
          <el-button type="primary" @click="handleSaveContact" class="blue-btn">保存</el-button>
          <el-button @click="contactDrawerVisible = false">取消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 客户编辑抽屉组件 -->
    <customer-edit ref="editRef" @success="handleEditSuccess" />
  </el-drawer>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Close, Edit, Plus, Search } from '@element-plus/icons-vue';
import { getPool } from "@/api/customer/customerPool";
import { listProvinceWithCities } from "@/api/customer/addressArea";
import { addContact, updateContact, delContact, getContact } from "@/api/customer/crmContact";
import { listDept } from "@/api/system/dept";
import { listTeamMember } from "@/api/customer/teamMember";
import BusinessActivity from '../../common/businessActivity.vue';
import CustomerEdit from './edit.vue';

const emit = defineEmits(['success']);
const proxy = getCurrentInstance().proxy;
const visible = ref(false);
const isReadOnly = ref(true);
const loading = ref(false);
const customerData = ref({});
const bizInfo = ref({});
const salesInfo = ref({});
const teamMembers = ref([]);
const activeContentTab = ref('data');
const activeSideTab = ref('team');
const editRef = ref(null);

// 获取身份证正反面图片
const getCardImage = (index) => {
  if (!bizInfo.value || !bizInfo.value.legalPersonCardUrl) return '';
  const urls = bizInfo.value.legalPersonCardUrl.split(',');
  return urls[index] || '';
};

// 联系人抽屉相关
const contactDrawerVisible = ref(false);
const contactTitle = ref("");
const contactFormRef = ref(null);
const officeAddr = ref([]);
const homeAddr = ref([]);
const areaOptions = ref([]);
const deptOptions = ref([]);
const contactForm = reactive({
  id: undefined,
  customerId: undefined,
  contactName: '', type: '1', gender: '1', age: '', nativePlace: '', birthday: '', remark: '',
  jobStatus: '1', phone: '', deptId: undefined, deptName: '', roleName: '', officePhone: '', jobContent: '',
  homeProvinceId: undefined, homeCityId: undefined, homeAreaId: undefined,
  addressProvince: undefined, addressCity: undefined, addressCounty: undefined, addressDetail: '',
  familyStatus: '', hobby: '', characterTrait: '', isSmoke: '0', isDrink: '0', homeAddressDetail: ''
});
const contactRules = {
  contactName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
  deptName: [{ required: true, message: "部门不能为空", trigger: "blur" }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的11位手机号码", trigger: "blur" }
  ],
  officePhone: [
    { pattern: /^1[3-9]\d{9}$/, message: "座机号请输入正确的11位手机号码", trigger: "blur" }
  ],
  addressDetail: [{ required: true, message: "请输入办公地址", trigger: "blur" }]
};

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

const loadData = (id) => {
  loading.value = true;
  getPool(id).then(res => {
    customerData.value = res.data;
    bizInfo.value = res.data.customerBusinessInfoVo || {};
    salesInfo.value = res.data.customerSalesInfoVo || {};
    loading.value = false;
  }).catch(() => loading.value = false);
};

// refreshTeamMembers removed since we listen to update-readonly event

const handleAddContact = () => {
  contactTitle.value = "新建客户联系人";
  contactDrawerVisible.value = true;
  officeAddr.value = [];
  homeAddr.value = [];
  Object.assign(contactForm, {
    id: undefined,
    customerId: customerData.value.id,
    customerName: customerData.value.customerName || '',
    customerNo: customerData.value.customerNo || '',
    contactName: '', type: '1', gender: '1', age: '', nativePlace: '', birthday: '', remark: '',
    jobStatus: '1', phone: '', deptId: undefined, deptName: '', roleName: '', officePhone: '', jobContent: '',
    homeProvinceId: undefined, homeCityId: undefined, homeAreaId: undefined,
    addressProvince: undefined, addressCity: undefined, addressCounty: undefined, addressDetail: '',
    familyStatus: '', hobby: '', characterTrait: '', isSmoke: '0', isDrink: '0', homeDetailAddress: ''
  });
  if (contactFormRef.value) contactFormRef.value.resetFields();
};

const handleEditContact = async (row) => {
  contactTitle.value = "编辑客户联系人";
  try {
    loading.value = true;
    const res = await getContact(row.id);
    console.log("联系人详情响应:", res);
    const data = res.data || res; // 兼容处理，防止 request 拦截器已经解包
    
    if (!data || Object.keys(data).length === 0) {
      proxy.$modal.msgError("未能获取到联系人详细信息");
      return;
    }
    
    // 处理性别、类型等 radio 字段的字符串转换，确保选中状态
    if (data.gender) data.gender = String(data.gender);
    if (data.type) data.type = String(data.type);
    if (data.jobStatus) data.jobStatus = String(data.jobStatus);
    if (data.isSmoke) data.isSmoke = String(data.isSmoke);
    if (data.isDrink) data.isDrink = String(data.isDrink);
    
    // 还原表单
    Object.assign(contactForm, data);
    
    // 还原地址级联 (注意：如果后端存储的是字符串，这里需要确保类型匹配)
    officeAddr.value = [data.addressProvince, data.addressCity, data.addressCounty].filter(i => i);
    homeAddr.value = [data.homeProvinceId, data.homeCityId, data.homeAreaId].filter(i => i);
    
    contactDrawerVisible.value = true;
  } catch (err) {
    console.error("获取联系人详情失败:", err);
  } finally {
    loading.value = false;
  }
};

const handleDeleteContact = (row) => {
  proxy.$modal.confirm(`确认要删除联系人「${row.contactName}」吗？`).then(() => {
    return delContact(row.id);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    loadData(customerData.value.id);
  }).catch(() => {});
};

const handleSaveContact = () => {
  contactFormRef.value.validate(async valid => {
    if (valid) {
      // 从部门树中提取部门名称
      if (contactForm.deptId) {
        const findDeptName = (nodes, id) => {
          for (const node of nodes) {
            if (node.deptId === id) return node.deptName;
            if (node.children) {
              const res = findDeptName(node.children, id);
              if (res) return res;
            }
          }
          return '';
        };
        contactForm.deptName = findDeptName(deptOptions.value, contactForm.deptId);
      }

      // 处理地址级联数据 (对应后端 addressProvince, addressCity, addressCounty)
      if (officeAddr.value && officeAddr.value.length > 0) {
        contactForm.addressProvince = officeAddr.value[0];
        contactForm.addressCity = officeAddr.value[1];
        contactForm.addressCounty = officeAddr.value[2];
      }
      // 处理家庭地址级联数据
      if (homeAddr.value && homeAddr.value.length > 0) {
        contactForm.homeProvinceId = homeAddr.value[0];
        contactForm.homeCityId = homeAddr.value[1];
        contactForm.homeAreaId = homeAddr.value[2];
      }

      try {
        loading.value = true;
        if (contactForm.id) {
          await updateContact(contactForm);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          await addContact(contactForm);
          proxy.$modal.msgSuccess("保存成功");
        }
        contactDrawerVisible.value = false;
        loadData(customerData.value.id); // 刷新数据，重新获取联系人列表
      } catch (error) {
        console.error("保存联系人失败:", error);
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleEdit = () => { editRef.value.open(customerData.value.id); };
const handleEditSuccess = () => { loadData(customerData.value.id); proxy.$emit('success'); };

onMounted(() => {
  listProvinceWithCities().then(res => {
    const list = res.rows || [];
    areaOptions.value = handleTree(list, "id", "parentId");
  });
  listDept().then(res => {
    deptOptions.value = proxy.handleTree(res.data, "deptId");
  });
});

/** 构造树型结构数据 */
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;
}

defineExpose({ open });
</script>

<style scoped lang="scss">
.customer-detail-drawer { :deep(.el-drawer__body) { padding: 0; overflow: hidden; } }
.detail-container { 
  display: flex; flex-direction: column; height: 100vh; background-color: #fff;
  font-family: inherit;
}
.detail-header { 
  height: 48px; padding: 0 24px; background: #fff; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #f0f2f5;
  .customer-title { font-size: 16px; color: #333; font-weight: normal; }
  .customer-type { margin-left: 24px; font-size: 14px; color: #86909c; }
  .close-btn { font-size: 20px; color: #94a3b8; cursor: pointer; &:hover { color: #333; } }
}
.detail-main { display: flex; flex: 1; overflow: hidden; }
.main-content { flex: 1; display: flex; flex-direction: column; background: #fff; overflow: hidden; }

.custom-tabs {
  flex: 1; display: flex; flex-direction: column; overflow: hidden;
  :deep(.el-tabs__header) { 
    margin: 0 !important; padding: 0 16px !important; background: #fff !important; height: 48px !important; 
    border-bottom: 1px solid #f0f2f5 !important;
    order: 1;
  }
  :deep(.el-tabs__nav-wrap::after) { display: none !important; }
  :deep(.el-tabs__item) { 
    height: 48px !important; line-height: 48px !important; font-size: 14px; color: #666; 
    &.is-active { color: #409eff; font-weight: 500 !important; } 
  }
  :deep(.el-tabs__active-bar) { 
    background-color: transparent !important;
    height: 3px !important;
    &::after {
      content: '';
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      width: 24px;
      height: 100%;
      background-color: #409eff;
      border-radius: 2px;
    }
    bottom: 0 !important; 
  }
  :deep(.el-tabs__content) { flex: 1; overflow-y: auto; order: 2; padding: 0; }
}

.tab-scroll-pane { padding: 24px; }
.info-section { 
  margin-bottom: 40px;
  .section-header { 
    display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;
    .section-title { font-size: 16px; color: #333; font-weight: 700; }
    .blue-btn { background-color: #409eff; border-color: #409eff; color: #fff; padding: 8px 20px; font-weight: 500; }
  }
}
.info-grid { 
  .info-cell { 
    display: flex; margin-bottom: 24px; font-size: 14px; align-items: flex-start;
    .label { width: 100px; color: #999; flex-shrink: 0; }
    .value { color: #333; word-break: break-all; flex: 1; }
    
    &.image-cell {
      flex-direction: column;
      .label { margin-bottom: 12px; }
      .image-box {
        width: 140px; height: 88px; background-color: #fff; border: 1px solid #eee; border-radius: 4px; display: flex; align-items: center; justify-content: center; overflow: hidden;
        .info-img { width: 100%; height: 100%; }
        .img-placeholder { font-size: 12px; color: #ccc; }
      }
    }
  } 
}
.contact-toolbar { display: flex; justify-content: flex-end; margin-bottom: 20px; }
.table-container-custom { 
  background: #fff; border-radius: 12px; border: 1px solid #f1f5f9; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.02); 
}
.contact-table { 
  :deep(.el-table__header) { 
    th { background-color: #f8fafc; color: #1e293b; font-weight: 600; font-size: 13px; height: 48px; border-bottom: 1px solid #f1f5f9; } 
  }
  :deep(.el-table__row) { 
    td { height: 52px; border-bottom: 1px solid #f8fafc; }
    &:last-child td { border-bottom: none; }
  }
  .name-highlight { color: #1e293b; font-weight: 500; }
  .op-btn { font-weight: 500; font-size: 13px; }
  .empty-wrap { padding: 40px 0; }
}

/* 动画效果 */
.fade-slide-enter-active, .fade-slide-leave-active { transition: all 0.3s ease; }
.fade-slide-enter-from { opacity: 0; transform: translateY(10px); }
.fade-slide-leave-to { opacity: 0; transform: translateY(-10px); }
.sidebar-content { width: 450px; display: flex; flex-direction: column; background: #fff; border-left: 1px solid #f0f2f5; flex-shrink: 0; }
.side-panel { padding: 20px; display: flex; flex-direction: column; flex: 1;
  .panel-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;
    .panel-title { font-size: 14px; color: #1e293b; }
    .add-btn { color: #94a3b8; cursor: pointer; font-size: 18px; &:hover { color: #409eff; } }
  }
  .side-search { margin-bottom: 20px; :deep(.el-input__wrapper) { background: #f8fafc; box-shadow: none; } }
  .member-list { flex: 1; overflow-y: auto; }
  .member-card { display: flex; align-items: center; padding: 12px; border-radius: 6px; margin-bottom: 8px; border: 1px solid #f1f5f9;
    &:hover { background: #f8fafc; }
    .member-avatar { width: 32px; height: 32px; background: #409eff; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; margin-right: 12px; }
    .m-name { font-size: 14px; color: #1e293b; }
    .m-role { font-size: 12px; color: #64748b; margin-top: 2px; }
  } }


</style>

<style lang="scss">
/* 全局样式处理 append-to-body 的抽屉 */
.contact-form-drawer {
  .el-drawer__body { padding: 0; }
  .form-section-header { background: #f8fafc; padding: 10px 20px; color: #409eff; font-size: 14px; margin-bottom: 15px; font-weight: normal !important; }
  .form-section-body { padding: 0 20px 20px; }
  .address-group { display: flex; gap: 10px; width: 100%; }
  .drawer-footer { display: flex; justify-content: flex-end; gap: 10px; padding: 20px; border-top: 1px solid #f1f5f9; }
  
  /* 强制覆盖标签和输入框文字加粗 */
  .el-form-item { margin-bottom: 18px !important; }
  :deep(*) { font-weight: normal !important; }
  .el-form-item__label, .el-radio__label, .el-input__inner, .el-textarea__inner { 
    font-weight: normal !important; 
    color: #64748b; 
    font-size: 14px; 
  }
  .el-input__inner, .el-textarea__inner { color: #1e293b; }
}

/* 全局彻底隐藏滑动条 - 针对所有浏览器 */
html, body, .customer-detail-drawer, .customer-detail-drawer * {
  &::-webkit-scrollbar { width: 0 !important; height: 0 !important; display: none !important; }
  -ms-overflow-style: none !important;
  scrollbar-width: none !important;
}

/* 强制抽屉开启时锁定 body 且不留空隙 */
.el-popup-parent--hidden {
  padding-right: 0 !important;
  overflow: hidden !important;
}
</style>
