<template>
  <el-drawer v-model="visible" size="90%" class="customer-info-drawer" :with-header="false">
    <div class="info-container" v-loading="loading">
      <template v-if="customerData">
      <!-- 头部布局 -->
      <div class="info-header">
        <div class="header-left">
          <span class="company-name">{{ customerData.customerName }}</span>

          <span class="customer-type-tag">类型：{{ customerData.customerCategoryName || '' }}</span>
        </div>
        <div class="header-right">
          <el-icon class="close-icon" @click="handleClose"><Close /></el-icon>
        </div>
      </div>

      <!-- 主体内容 -->
      <div class="info-body">
        <!-- 左侧详情 -->
        <div class="info-main">
          <!-- 导航栏 Tab -->
          <div class="main-tabs">
            <div 
              v-for="tab in mainTabs" 
              :key="tab.key" 
              :class="['tab-item', { active: activeMainTab === tab.key }]"
              @click="activeMainTab = tab.key"
            >
              {{ tab.label }}
            </div>
          </div>
          
          <div class="scroll-content">
            <!-- 客户资料模块 -->
            <div v-show="activeMainTab === 'profile'" class="profile-section">
              <div class="section-actions">
                <el-button type="primary" icon="Edit" class="edit-btn">编辑</el-button>
              </div>

              <!-- 基本信息 -->
              <div class="detail-section">
                <div class="section-title">基本信息</div>
                <div class="info-grid">
                  <!-- 第一行 -->
                  <div class="info-item col-span-3">
                    <span class="label">工商名称</span>
                    <span class="value">{{ customerData.businessCustomerName || customerData.businessName || '' }}</span>
                  </div>
                  <!-- 第二行 -->
                  <div class="info-item">
                    <span class="label">归属公司</span>
                    <span class="value">{{ customerData.companyName || customerData.belongCompanyId || '' }}</span>
                  </div>
                  <div class="info-item">
                     <span class="label">客户来源</span>
                     <span class="value">{{ customerData.customerSourceName || customerData.sourceName || getLabel(sourceOptions, customerData.customerSourceId, 'dictValue', 'dictLabel') }}</span>
                  </div>
                  <div class="info-item">
                     <span class="label">企业类型</span>
                     <span class="value">{{ customerData.enterpriseTypeName || getLabel(corpTypeOptions, customerData.enterpriseTypeId || customerData.EnterpriseType, 'dictValue', 'dictLabel') }}</span>
                  </div>
                  <!-- 第三行 -->
                  <div class="info-item">
                    <span class="label">客户等级</span>
                    <span class="value">{{ customerData.customerLevelName || getLabel(levelOptions, customerData.customerLevelId, 'id', 'levelName') }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">企业规模</span>
                    <span class="value">{{ customerData.enterpriseScaleName || getLabel(scaleOptions, customerData.enterpriseScaleId || customerData.enterpriseScale, 'id', 'enterpriseScaleName') }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">企业邮箱</span>
                    <span class="value">{{ customerData.email || customerData.mailbox || '' }}</span>
                  </div>
                  <!-- 第四行 -->
                  <div class="info-item">
                    <span class="label">办公电话</span>
                    <span class="value">{{ customerData.landline || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">行业</span>
                    <span class="value">{{ customerData.industryCategoryName || customerData.industryName || getLabel(industryOptions, customerData.industryCategoryId, 'id', 'industryCategoryName') }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">国家</span>
                    <span class="value">{{ customerData.countryName || '中国' }}</span>
                  </div>
                  <!-- 第五行 -->
                  <div class="info-item">
                    <span class="label">省份</span>
                    <span class="value">{{ provinceDisplay }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">城市</span>
                    <span class="value">{{ cityDisplay }}</span>
                  </div>
                  <div class="info-item"></div> <!-- 占位占满一行 -->
                  <!-- 第六行 -->
                  <div class="info-item col-span-3">
                    <span class="label">办公地址</span>
                    <span class="value">{{ customerData.address || '' }}</span>
                  </div>
                </div>
              </div>

              <!-- 工商信息 -->
              <div class="detail-section">
                <div class="section-title">工商信息</div>
                <div class="info-grid">
                  <!-- 行1 -->
                  <div class="info-item col-span-3">
                    <span class="label">工商名称</span>
                    <span class="value">{{ customerData.businessName || customerData.businessCustomerName || '' }}</span>
                  </div>
                  <!-- 行2 -->
                  <div class="info-item">
                    <span class="label">社会信用代码</span>
                    <span class="value">{{ customerData.customerBusinessVo?.socialCreditCode || customerData.customerBusinessInfoVo?.socialCreditCode || customerData.social_credit_code || customerData.creditCode || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">法人姓名</span>
                    <span class="value">{{ customerData.customerBusinessVo?.legalPersonName || customerData.customerBusinessInfoVo?.legalPersonName || customerData.legalPerson || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">注册资本</span>
                    <span class="value">{{ customerData.customerBusinessVo?.registeredCapital || customerData.customerBusinessInfoVo?.registeredCapital || customerData.registeredCapital || '' }}</span>
                  </div>
                  <!-- 行3 -->
                  <div class="info-item">
                     <span class="label">登记机关</span>
                     <span class="value">{{ customerData.customerBusinessVo?.registrationAuthority || customerData.customerBusinessInfoVo?.registrationAuthority || customerData.registrationAuthority || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">成立日期</span>
                    <span class="value">{{ customerData.customerBusinessVo?.establishmentDate || customerData.customerBusinessInfoVo?.establishmentDate || customerData.establishedDate || '' }}</span>
                  </div>
                   <div class="info-item">
                    <span class="label">吊销日期</span>
                    <span class="value">{{ customerData.customerBusinessVo?.revocationDate || customerData.customerBusinessInfoVo?.revocationDate || customerData.revocationDate || '' }}</span>
                  </div>
                  <!-- 行4 -->
                  <div class="info-item">
                    <span class="label">登记状态</span>
                    <span class="value">{{ customerData.customerBusinessVo?.registrationStatus || customerData.customerBusinessInfoVo?.registrationStatus || customerData.registrationStatus || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">实缴资本</span>
                    <span class="value">{{ customerData.customerBusinessVo?.paidInCapital || customerData.customerBusinessInfoVo?.paidInCapital || customerData.paidInCapital || '' }}</span>
                  </div>
                  <div class="info-item"></div>
                  <!-- 行5 -->
                  <div class="info-item col-span-3">
                    <span class="label">注册地址</span>
                    <span class="value">{{ customerData.customerBusinessVo?.businessAddress || customerData.customerBusinessInfoVo?.businessAddress || customerData.businessAddress || customerData.address || '' }}</span>
                  </div>
                  <!-- 行6 -->
                  <div class="info-item">
                    <span class="label">营业执照</span>
                    <el-image 
                      v-if="businessLicenseUrl"
                      style="width: 60px; height: 60px; border-radius: 4px; cursor: pointer;"
                      :src="businessLicenseUrl"
                      :preview-src-list="[businessLicenseUrl]"
                      fit="cover"
                    />
                    <span class="value" v-else>未上传</span>
                  </div>
                  <div class="info-item">
                    <span class="label">正面身份证</span>
                    <el-image 
                      v-if="idCardFrontUrl"
                      style="width: 60px; height: 60px; border-radius: 4px; cursor: pointer;"
                      :src="idCardFrontUrl"
                      :preview-src-list="[idCardFrontUrl]"
                      fit="cover"
                    />
                    <span class="value" v-else>未上传</span>
                  </div>
                  <div class="info-item">
                    <span class="label">反面身份证</span>
                    <el-image 
                      v-if="idCardBackUrl"
                      style="width: 60px; height: 60px; border-radius: 4px; cursor: pointer;"
                      :src="idCardBackUrl"
                      :preview-src-list="[idCardBackUrl]"
                      fit="cover"
                    />
                    <span class="value" v-else>未上传</span>
                  </div>
                </div>
              </div>

              <!-- 销售信息 -->
              <div class="detail-section">
                <div class="section-title">销售信息</div>
                <div class="info-grid">
                  <!-- 行1 -->
                  <div class="info-item">
                    <span class="label">合作状况</span>
                    <span class="value">{{ customerData.cooperationName || getLabel(cooperationOptions, customerData.cooperation || customerData.Cooperation, 'dictValue', 'dictLabel') }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">开票类型</span>
                    <span class="value">{{ customerData.invoiceTypeName || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">归属部门</span>
                    <span class="value">{{ customerData.deptName || customerData.belongingDepartmentId || '' }}</span>
                  </div>
                  <!-- 行2 -->
                  <div class="info-item">
                    <span class="label">采购规模(万)</span>
                    <span class="value">{{ customerData.annualProcurementScale || customerData.customerSalesInfoVo?.procurementScale || customerData.procurementScale || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">销售目标(万)</span>
                    <span class="value">{{ customerData.SalesTarget || customerData.customerSalesInfoVo?.salesTarget || customerData.salesTarget || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">采购方式</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.purchaseWayName || customerData.purchaseWayName || getLabel(purchaseWayOptions, customerData.customerSalesInfoVo?.purchaseWay || customerData.purchaseWay || customerData.ProcurementType, 'dictValue', 'dictLabel') }}</span>
                  </div>
                  <!-- 行3 -->
                  <div class="info-item">
                    <span class="label">信用等级</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.creditLevelName || customerData.customerSalesVo?.creditLevelName || customerData.creditLevelName || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">授信额度</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.creditAmount || customerData.customerSalesVo?.creditAmount || customerData.creditAmount || '0.00' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">应收账款</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.accountsReceivable || customerData.customerSalesVo?.accountsReceivable || customerData.customerSalesInfoVo?.receivableAmount || customerData.receivableAmount || '0.00' }}</span>
                  </div>
                  <!-- 行4 -->
                  <div class="info-item">
                    <span class="label">预收账款</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.prepaidAmount || customerData.customerSalesVo?.prepaidAmount || customerData.prepaidAmount || '0' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">剩余额度</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.remainingQuota || customerData.customerSalesVo?.remainingQuota || customerData.customerSalesInfoVo?.remainingAmount || customerData.remainingAmount || '0.00' }}</span>
                  </div>
                  <div class="info-item"></div>
                </div>
              </div>
            </div>

            <!-- 项目商机 Tab -->
            <div v-show="activeMainTab === 'opportunity'" class="tab-table-wrapper">
               <el-table :data="opportunityList" border class="custom-tab-table">
                  <el-table-column label="登记日期" align="center" prop="createTime" width="160">
                    <template #default="scope">{{ proxy.parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</template>
                  </el-table-column>
                  <el-table-column label="项目商机名称" align="center" prop="leadsName" :show-overflow-tooltip="true" />
                  <el-table-column label="项目类型" align="center" prop="projectType" width="120" />
                  <el-table-column label="项目预算(万)" align="center" prop="budget" width="120" />
                  <el-table-column label="最终成交金额" align="center" prop="dealAmount" width="120" />
                  <el-table-column label="成交结果" align="center" prop="dealResult" width="100" />
                  <el-table-column label="操作" align="center" width="100">
                    <template #default="scope"><el-button link type="primary">详情</el-button></template>
                  </el-table-column>
               </el-table>
            </div>

            <!-- 客户联系人 Tab -->
            <div v-show="activeMainTab === 'contacts'" class="contacts-wrapper">
              <div class="tab-actions">
                <el-button type="primary" icon="Plus" class="add-btn">新增</el-button>
              </div>
              <el-table :data="customerData.customerContactVoList || []" border class="custom-tab-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="150">
                  <template #default="scope">
                    <el-button link type="primary">详情</el-button>
                    <el-button link type="primary">编辑</el-button>
                    <el-button link type="danger">删除</el-button>
                  </template>
                </el-table-column>
                <template #empty>暂无数据</template>
              </el-table>
            </div>
            
            <!-- 年度入圃 Tab -->
            <div v-show="activeMainTab === 'admission'" class="tab-table-wrapper">
               <el-table :data="admissionList" border class="custom-tab-table">
                  <el-table-column label="登记日期" align="center" prop="createTime" width="160">
                    <template #default="scope">{{ scope.row.createTime || '' }}</template>
                  </el-table-column>
                  <el-table-column label="年度入围名称" align="center" prop="admissionName" :show-overflow-tooltip="true" />
                  <el-table-column label="项目等级" align="center" prop="level" width="120" />
                  <el-table-column label="金额(万)" align="center" prop="amount" width="120" />
                  <el-table-column label="标期(年)" align="center" prop="period" width="120" />
                  <el-table-column label="投标截止时间" align="center" prop="deadline" width="160" />
                  <el-table-column label="操作" align="center" width="100">
                    <template #default="scope"><el-button link type="primary">详情</el-button></template>
                  </el-table-column>
                  <template #empty>暂无数据</template>
               </el-table>
            </div>
            
            <!-- 客户关怀 Tab -->
            <div v-show="activeMainTab === 'care'" class="contacts-wrapper">
              <div class="tab-actions">
                <el-button type="primary" icon="Plus" class="add-btn">新增</el-button>
              </div>
              <el-table :data="careList" border class="custom-tab-table">
                <el-table-column label="单据编号" align="center" prop="careNo" />
                <el-table-column label="登记日期" align="center" prop="createTime" width="160" />
                <el-table-column label="联系人" align="center" prop="contactName" />
                <el-table-column label="关怀类型" align="center" prop="careType" />
                <el-table-column label="金额" align="center" prop="amount" />
                <el-table-column label="操作" align="center" width="100">
                  <template #default="scope"><el-button link type="primary">详情</el-button></template>
                </el-table-column>
                <template #empty>暂无数据</template>
              </el-table>
            </div>
            
            <!-- 附件 Tab -->
            <div v-show="activeMainTab === 'attachment'" class="contacts-wrapper">
              <div class="tab-actions">
                <el-button type="primary" icon="Upload" class="add-btn" @click="handleUpload">上传附件</el-button>
              </div>
              <el-table :data="attachmentList" border class="custom-tab-table">
                <el-table-column label="文件名称" align="center" prop="fileName" :show-overflow-tooltip="true" />
                <el-table-column label="文件类型" align="center" prop="fileType" width="120" />
                <el-table-column label="上传时间" align="center" prop="createTime" width="180" />
                <el-table-column label="操作" align="center" width="150" fixed="right">
                  <template #default="scope">
                    <el-button link type="primary" @click="handleDownload(scope.row)">下载</el-button>
                    <el-button link type="danger" @click="handleDeleteAttachment(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
                <template #empty>暂无数据</template>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 右侧侧边栏 -->
        <div class="info-sidebar">
          <div class="sidebar-tabs">
            <div 
              v-for="tab in sidebarTabs" 
              :key="tab.key" 
              :class="['sidebar-tab-item', { active: activeSidebarTab === tab.key }]"
              @click="activeSidebarTab = tab.key"
            >
              {{ tab.label }}
            </div>
          </div>
          <div class="sidebar-content">
            <!-- 团队成员 -->
            <div v-if="activeSidebarTab === 'team'" class="team-section">
              <div class="team-header">
                <span class="title">团队成员 ({{ teamMembers.length }})</span>
                <el-icon class="add-icon"><Plus /></el-icon>
              </div>
              <div class="search-box">
                <el-input placeholder="请输入成员" prefix-icon="Search" v-model="memberSearch" clearable />
              </div>
              <div class="member-list" v-if="teamMembers.length > 0">
                <div v-for="member in teamMembers" :key="member.id" class="member-item">
                  <el-avatar :size="32" icon="UserFilled" class="avatar" />
                  <div class="member-info">
                    <div class="name-row">
                      <span class="name">{{ member.staffName }}</span>
                      <span class="role-tag" v-if="member.isLeader === '1'">负责人</span>
                    </div>
                    <div class="perm-row">
                      <span class="role">{{ member.roleName || '业务负责人' }}</span>
                      <span class="perm">修改权限</span>
                    </div>
                  </div>
                  <div class="member-ops">
                    <span class="op-edit">编辑</span>
                    <span class="op-delete">删除</span>
                  </div>
                </div>
              </div>
              <div v-else class="empty-placeholder">暂无成员</div>
            </div>
            <div v-else class="empty-placeholder"> 暂无记录 </div>
          </div>
        </div>
      </div>
      </template>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, getCurrentInstance } from 'vue';
import { Close, Plus, Search, UserFilled } from '@element-plus/icons-vue';
import { getCustomerInfo } from "@/api/customer/customerInfo";
import { listOpportunity } from "@/api/saleManage/opportunity";
import { listTeamMember } from "@/api/customer/teamMember";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listLevel } from "@/api/customer/customerLevel";
import { listDictByType, listCommonDict } from "@/api/customer/customerDict";
import { listEnterpriseScale } from "@/api/customer/enterpriseScale";
import { listByIds } from "@/api/system/oss";

const { proxy } = getCurrentInstance();
const visible = ref(false);
const loading = ref(false);
const customerData = ref(null);
const businessLicenseUrl = ref('');
const idCardFrontUrl = ref('');
const idCardBackUrl = ref('');
const opportunityList = ref([]);
const admissionList = ref([]);
const careList = ref([]);
const attachmentList = ref([]);
const teamMembers = ref([]);
const memberSearch = ref('');
const activeMainTab = ref('profile'); // 默认选中客户资料
const activeSidebarTab = ref('team');

// 映射表数据
const industryOptions = ref([]);
const levelOptions = ref([]);
const sourceOptions = ref([]);
const corpTypeOptions = ref([]);
const scaleOptions = ref([]);
const cooperationOptions = ref([]);
const invoiceTypeOptions = ref([]);
const purchaseWayOptions = ref([]);

// 计算属性处理省市区展示 (适配 provincialCityCounty 格式: 省/市/区)
const provinceDisplay = computed(() => {
  if (customerData.value?.provinceName) return customerData.value.provinceName;
  if (customerData.value?.provincialCityCounty) {
    const parts = customerData.value.provincialCityCounty.split('/');
    return parts[0] || '';
  }
  return '';
});

const cityDisplay = computed(() => {
  if (customerData.value?.cityName) return customerData.value.cityName;
  if (customerData.value?.provincialCityCounty) {
    const parts = customerData.value.provincialCityCounty.split('/');
    return parts[1] || '';
  }
  return '';
});

// 计算属性处理身份证预览
const idCardFront = computed(() => {
  const url = customerData.value?.legalPersonCardUrl || customerData.value?.customerBusinessVo?.legalPersonCardUrl || customerData.value?.customerBusinessInfoVo?.legalPersonCardUrl || customerData.value?.legal_person_card_url;
  if (!url) return '';
  return url.split(',')[0];
});

const idCardBack = computed(() => {
  const url = customerData.value?.legalPersonCardUrl || customerData.value?.customerBusinessVo?.legalPersonCardUrl || customerData.value?.customerBusinessInfoVo?.legalPersonCardUrl || customerData.value?.legal_person_card_url;
  if (!url) return '';
  const parts = url.split(',');
  return parts.length > 1 ? parts[1] : '';
});

// 附件相关操作
const handleUpload = () => {
  proxy.$modal.msgInfo("上传附件功能正在开发中...");
};

const handleDownload = (row) => {
  proxy.$modal.msgInfo("正在下载项目: " + row.fileName);
};

const handleDeleteAttachment = (row) => {
  proxy.$modal.confirm(`是否确认删除附件 "${row.fileName}"？`).then(() => {
    proxy.$modal.msgSuccess("删除成功");
  });
};

const mainTabs = [
  { key: 'profile', label: '客户资料' },
  { key: 'contacts', label: '客户联系人' },
  { key: 'opportunity', label: '项目商机' },
  { key: 'admission', label: '年度入圃' },
  { key: 'care', label: '客户关怀' },
  { key: 'attachment', label: '附件' }
];

const sidebarTabs = [
  { key: 'team', label: '团队成员' },
  { key: 'follow', label: '跟进记录' },
  { key: 'log', label: '操作日志' },
  { key: 'admin', label: '管理信息' }
];

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

const loadData = async (id) => {
  if (!id) return;
  loading.value = true;
  // 先加载配置和字典
  await initOptions();
  
  getCustomerInfo(id).then(res => {
    customerData.value = res.data;
    refreshOpportunities();
    refreshTeamMembers();
    refreshOssUrls();
  }).catch(() => {
    proxy.$modal.msgError("获取客户详情失败");
  }).finally(() => {
    loading.value = false;
  });
};

/** 刷新 OSS 图片 URL */
const refreshOssUrls = () => {
  // 重置 URL
  businessLicenseUrl.value = '';
  idCardFrontUrl.value = '';
  idCardBackUrl.value = '';

  const biz = customerData.value?.customerBusinessVo || customerData.value?.customerBusinessInfoVo;
  const licenseId = customerData.value?.businessLicense || biz?.businessLicense;
  const cardIdsStr = customerData.value?.legalPersonCardUrl || biz?.legalPersonCardUrl || customerData.value?.legal_person_card_url;
  
  const allIds = [];
  if (licenseId) allIds.push(licenseId);
  if (cardIdsStr) {
    cardIdsStr.split(',').forEach(id => {
      if (id && id.trim()) allIds.push(id.trim());
    });
  }

  if (allIds.length === 0) return;

  listByIds(allIds.join(',')).then(res => {
    const ossList = res.data || [];
    const getUrl = (id) => ossList.find(o => String(o.ossId) === String(id))?.url;

    if (licenseId) businessLicenseUrl.value = getUrl(licenseId);
    if (cardIdsStr) {
      const ids = cardIdsStr.split(',').map(i => i.trim());
      if (ids[0]) idCardFrontUrl.value = getUrl(ids[0]);
      if (ids[1]) idCardBackUrl.value = getUrl(ids[1]);
    }
  });
};

const initOptions = async () => {
  // 行业
  listIndustryCategory().then(res => industryOptions.value = res.data || []);
  // 等级
  listLevel().then(res => levelOptions.value = res.rows || []);
  // 来源 (K0001 是常见编码)
  listCommonDict("K0001").then(res => sourceOptions.value = res.data || []);
  // 企业类型 (尝试多种可能的编码)
  listDictByType("crm_enterprise_type").then(res => {
     if (res.data && res.data.length > 0) {
       corpTypeOptions.value = res.data;
     } else {
       listDictByType("enterprise_type").then(res2 => corpTypeOptions.value = res2.data || []);
     }
  });
  // 企业规模
  listEnterpriseScale().then(res => scaleOptions.value = res.data || []);
  // 合作状态
  listDictByType("crm_cooperation_status").then(res => cooperationOptions.value = res.data || []);
  // 采购方式
  listDictByType("crm_purchase_way").then(res => purchaseWayOptions.value = res.data || []);
};

// 翻译辅助函数
const getLabel = (options, value, valueKey = 'id', labelKey = 'label') => {
  if (!value && value !== 0) return '';
  const item = options.find(i => String(i[valueKey]) === String(value));
  return item ? item[labelKey] : value;
};

const refreshOpportunities = () => {
  if (!customerData.value?.id) return;
  listOpportunity({ customerId: customerData.value.id }).then(res => {
    opportunityList.value = res.rows || res.data || [];
  });
};

const refreshTeamMembers = () => {
  if (!customerData.value?.customerNo) return;
  listTeamMember(customerData.value.customerNo).then(res => {
    teamMembers.value = res.data || [];
  });
};

const handleClose = () => {
  visible.value = false;
};

defineExpose({ open });
</script>

<style scoped lang="scss">
.customer-info-drawer {
  :deep(.el-drawer__body) { padding: 0; overflow: hidden !important; height: 100%; }
}

.info-container { display: flex; flex-direction: column; height: 100vh; background-color: #fff; }

.info-header {
  height: 60px; display: flex; justify-content: space-between; align-items: center;
  padding: 0 24px; border-bottom: 1px solid #f1f5f9;
  
  .header-left {
    display: flex; align-items: center; gap: 12px;
    .company-name { font-size: 18px; font-weight: bold; color: #1e293b; }
    .customer-type-tag { font-size: 13px; color: #475569; margin-left: 10px; }
  }
  .close-icon { font-size: 20px; color: #94a3b8; cursor: pointer; &:hover { color: #64748b; } }
}

.info-body { display: flex; flex: 1; overflow: hidden; }

.info-main { flex: 1; display: flex; flex-direction: column; border-right: 1px solid #f1f5f9; min-height: 0; }

.main-tabs {
  display: flex; padding: 0 20px; border-bottom: 1px solid #f1f5f9;
  .tab-item {
    padding: 16px 15px; font-size: 14px; color: #64748b; cursor: pointer; position: relative;
    &.active {
      color: #ea5413; font-weight: bold;
      &::after { content: ''; position: absolute; bottom: 0px; left: 15px; right: 15px; height: 2px; background-color: #ea5413; }
    }
  }
}

.scroll-content { flex: 1; overflow-y: auto; padding: 0 24px 40px; }

.section-actions, .tab-actions { display: flex; justify-content: flex-end; padding: 15px 0; }
.edit-btn, .add-btn { background-color: #3b82f6; border-color: #3b82f6; }

.detail-section {
  margin-bottom: 35px;
  .section-title { font-size: 16px; font-weight: bold; color: #1e293b; margin-bottom: 20px; }
}

.info-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
.info-item {
  display: flex; align-items: flex-start; line-height: 1.6;
  .label { width: 100px; font-size: 13px; color: #94a3b8; flex-shrink: 0; }
  .value { font-size: 13px; color: #334155; word-break: break-all; }
  .value-link { font-size: 13px; color: #3b82f6; cursor: pointer; }
}
.col-span-2 { grid-column: span 2; }
.col-span-3 { grid-column: span 3; }

/* 右侧侧边栏 */
.info-sidebar { width: 420px; background-color: #fff; display: flex; flex-direction: column; }
.sidebar-tabs {
  display: flex; padding: 0 16px; border-bottom: 1px solid #f1f5f9; gap: 10px;
  .sidebar-tab-item {
    padding: 16px 8px; font-size: 14px; color: #64748b; cursor: pointer;
    &.active { color: #ea5413; font-weight: bold; position: relative; }
  }
}

.sidebar-content { flex: 1; padding: 20px; overflow-y: auto; }

.team-section {
  .team-header {
    display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;
    .title { font-size: 14px; font-weight: bold; color: #334155; }
    .add-icon { cursor: pointer; color: #94a3b8; &:hover { color: #3b82f6; } }
  }
  .search-box { margin-bottom: 20px; }
  .member-item {
    display: flex; align-items: center; padding: 12px 0; border-bottom: 1px solid #f8fafc;
    .avatar { background-color: #e2e8f0; color: #94a3b8; margin-right: 12px; flex-shrink: 0; }
    .member-info {
       flex: 1;
       .name-row {
         display: flex; align-items: center; gap: 8px; margin-bottom: 4px;
         .name { font-size: 14px; color: #334155; }
         .role-tag { font-size: 11px; padding: 1px 6px; background-color: #f0fdf4; color: #22c55e; border: 1px solid #dcfce7; border-radius: 2px; }
       }
       .perm-row {
         font-size: 12px; color: #94a3b8; display: flex; gap: 12px;
         .perm { color: #cbd5e1; }
       }
    }
    .member-ops {
      font-size: 12px; display: flex; gap: 12px;
      .op-edit { color: #fb923c; cursor: pointer; }
      .op-delete { color: #64748b; cursor: pointer; }
    }
  }
}

.empty-placeholder { padding: 60px 0; text-align: center; color: #cbd5e1; font-size: 13px; }
</style>
