<template>
  <el-drawer v-model="visible" title="客户详情" size="80%" class="customer-info-drawer" :with-header="false">
    <div class="info-container" v-if="customerData">
      <!-- 头部布局 -->
      <div class="info-header">
        <div class="header-left">
          <span class="company-name">{{ customerData.customerName }}</span>
          <!-- 头部展示：显示合作状态（直接引用后端名称字段） -->
          <span class="customer-type" v-if="customerData.cooperationName">
            合作状态：{{ customerData.cooperationName }}
          </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'">
              
              <!-- 基本信息 Section -->
              <div class="section relative">
                <div class="section-header">
                  <div class="section-title">基本信息</div>
                  <template v-if="isEdit">
                    <div class="section-btns">
                      <el-button type="primary" size="small" icon="CircleCheck" @click="handleSave" class="confirm-btn">确定</el-button>
                      <el-button type="info" size="small" icon="CircleClose" @click="handleCancel" class="cancel-btn">取消</el-button>
                    </div>
                  </template>
                  <el-button v-else type="warning" class="edit-btn" icon="Edit" @click="handleEdit">编辑</el-button>
                </div>
                <!-- 调整网格布局，严格匹配截图顺序 -->
                <div class="info-grid">
                  <!-- 行1 -->
                  <div class="info-item col-span-3">
                    <span class="label">工商名称</span>
                    <span class="value">{{ customerData.businessCustomerName }}</span>
                  </div>
                  
                  <!-- 行2 -->
                  <div class="info-item">
                    <span class="label">归属公司</span>
                    <span class="value">{{ customerData.companyName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">客户来源</span>
                    <el-select v-if="isEdit" v-model="editForm.customerSourceId" placeholder="请选择" size="small">
                      <el-option v-for="item in sourceOptions" :key="item.id" :label="item.dictLabel" :value="item.id" />
                    </el-select>
                    <span v-else class="value">{{ customerData.customerSourceName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">企业类型</span>
                    <el-select v-if="isEdit" v-model="editForm.enterpriseTypeId" placeholder="请选择" size="small">
                      <el-option v-for="item in corpTypeOptions" :key="item.id" :label="item.dictLabel" :value="item.id" />
                    </el-select>
                    <span v-else class="value">{{ customerData.enterpriseTypeName }}</span>
                  </div>

                  <!-- 行3 -->
                  <div class="info-item">
                    <span class="label">客户等级</span>
                    <span class="value">{{ customerData.customerLevelName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">企业规模</span>
                    <span class="value">{{ customerData.enterpriseScale }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">企业邮箱</span>
                    <span class="value">{{ customerData.email }}</span>
                  </div>

                  <!-- 行4 -->
                  <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.industryCategory }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">国家</span>
                    <span class="value">{{ countryName }}</span>
                  </div>

                  <!-- 行5 -->
                  <div class="info-item">
                    <span class="label">省份</span>
                    <span class="value">{{ provinceName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">城市</span>
                    <span class="value">{{ cityName }}</span>
                  </div>
                  <div class="info-item"></div>

                  <!-- 行6 -->
                  <div class="info-item col-span-3">
                    <span class="label">办公地址</span>
                    <span class="value">{{ customerData.address }}</span>
                  </div>
                </div>
              </div>

              <!-- 工商信息 Section (始终显示) -->
              <div class="section">
                <div class="section-title">工商信息</div>
                <div class="info-grid mt-20">
                  <div class="info-item col-span-3">
                    <span class="label">工商名称</span>
                    <el-input v-if="isEdit" v-model="editForm.customerBusinessInfoBo.businessCustomerName" size="small" placeholder="请输入工商全称" />
                    <span v-else class="value">{{ customerData.customerBusinessInfoVo?.businessCustomerName || customerData.businessCustomerName }}</span>
                  </div>

                  <div class="info-item">
                    <span class="label">社会信用代码</span>
                    <el-input v-if="isEdit" v-model="editForm.customerBusinessInfoBo.socialCreditCode" size="small" placeholder="请输入信用代码" />
                    <span v-else class="value">{{ customerData.customerBusinessInfoVo?.socialCreditCode || customerData.socialCreditCode }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">法定代表人</span>
                    <el-input v-if="isEdit" v-model="editForm.customerBusinessInfoBo.legalPersonName" size="small" placeholder="请输入法人姓名" />
                    <span v-else class="value">{{ customerData.customerBusinessInfoVo?.legalPersonName || customerData.legalPersonName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">注册资本</span>
                    <el-input v-if="isEdit" v-model="editForm.customerBusinessInfoBo.registeredCapital" size="small" placeholder="请输入注册资本" />
                    <span v-else class="value">{{ customerData.customerBusinessInfoVo?.registeredCapital || customerData.registeredCapital }}</span>
                  </div>

                  <div class="info-item">
                    <span class="label">成立日期</span>
                    <span class="value">{{ customerData.customerBusinessInfoVo?.establishmentDate || customerData.establishmentDate }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">吊销日期</span>
                    <span class="value">{{ customerData.customerBusinessInfoVo?.revocationDate || customerData.revocationDate }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">登记状态</span>
                    <span class="value">{{ customerData.customerBusinessInfoVo?.registrationStatus || customerData.registrationStatus }}</span>
                  </div>

                  <div class="info-item col-span-3">
                    <span class="label">注册地址</span>
                    <el-input v-if="isEdit" v-model="editForm.customerBusinessInfoBo.businessAddress" size="small" placeholder="请输入注册地址" />
                    <span v-else class="value">{{ customerData.customerBusinessInfoVo?.businessAddress || customerData.address }}</span>
                  </div>
                  <!-- ... (后面略过不变) -->

                  <!-- 图片预览/编辑 -->
                  <div class="info-item img-row-item">
                    <span class="label">营业执照</span>
                    <div class="img-content">
                      <el-image 
                        v-if="businessLicenseUrl"
                        style="width: 80px; height: 80px" 
                        :src="businessLicenseUrl" 
                        :preview-src-list="[businessLicenseUrl]"
                        fit="cover"
                      />
                      <div v-else class="img-box"><el-icon><Picture /></el-icon></div>
                    </div>
                  </div>
                  <div class="info-item img-row-item">
                    <span class="label">正面身份证</span>
                    <div class="img-content">
                      <el-image 
                        v-if="idCardFrontUrl"
                        style="width: 80px; height: 80px" 
                        :src="idCardFrontUrl" 
                        :preview-src-list="[idCardFrontUrl]"
                        fit="cover"
                      />
                      <div v-else class="img-box"><el-icon><Picture /></el-icon></div>
                    </div>
                  </div>
                  <div class="info-item img-row-item">
                    <span class="label">反面身份证</span>
                    <div class="img-content">
                      <el-image 
                        v-if="idCardBackUrl"
                        style="width: 80px; height: 80px" 
                        :src="idCardBackUrl" 
                        :preview-src-list="[idCardBackUrl]"
                        fit="cover"
                      />
                      <div v-else class="img-box"><el-icon><Picture /></el-icon></div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 销售信息 Section (始终显示) -->
              <div class="section">
                <div class="section-title">销售信息</div>
                <div class="info-grid mt-20">
                  <div class="info-item">
                    <span class="label">合作状态</span>
                    <span class="value">{{ customerData.cooperationName || '暂无数据' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">开票类别</span>
                    <span class="value">{{ customerData.invoiceTypeName || customerData.invoiceType }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">归属部门</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.belongingDepartment || customerData.belongingDepartment }}</span>
                  </div>

                  <div class="info-item">
                    <span class="label">采购规模(万)</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.procurementScale || customerData.annualProcurementScale }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">销售目标(万)</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.salesTarget || customerData.salesTarget }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">采购方式</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.procurementMethod || customerData.procurementType }}</span>
                  </div>

                  <div class="info-item">
                    <span class="label">信用等级</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.creditLevel || customerData.creditLevel }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">授信额度</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.creditAmount || customerData.creditAmount || '0.00' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">应收账款</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.accountsReceivable || customerData.accountsReceivable || '0.00' }}</span>
                  </div>

                  <div class="info-item">
                    <span class="label">预收账款</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.advancePayment || customerData.advancePayment || '0.00' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">剩余额度</span>
                    <span class="value">{{ customerData.customerSalesInfoVo?.remainingQuota || customerData.remainingQuota || '0.00' }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-show="activeMainTab === 'contacts'" class="contacts-wrapper">
              <div class="contacts-header">
                <el-button type="primary" icon="Plus" class="add-contact-btn" @click="handleAddContact">新增</el-button>
              </div>
              <el-table :data="contactList" border class="contacts-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 link type="primary">编辑</el-button>
                    <el-button link type="danger">删除</el-button>
                  </template>
                </el-table-column>
                <template #empty>
                  <div class="empty-box">暂无数据</div>
                </template>
              </el-table>
            </div>
            </div>
            <div v-show="activeMainTab === 'contacts'" class="contacts-wrapper">


          </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-show="activeSidebarTab === 'team'" class="team-section">
              <div class="sidebar-section-header">
                <span class="sidebar-section-title">团队成员 ({{ teamMembers.length }})</span>
                <el-icon class="add-icon" @click="handleAddMember"><Plus /></el-icon>
              </div>
              <div class="search-input">
                <el-input v-model="memberSearch" placeholder="请输入成员" prefix-icon="Search" clearable />
              </div>
              <div v-if="filteredMembers.length > 0" class="member-list">
                <div v-for="member in filteredMembers" :key="member.id" class="member-item">
                  <el-avatar :size="32" class="member-avatar">{{ member.name ? member.name.charAt(0) : 'U' }}</el-avatar>
                  <div class="member-info">
                    <div class="member-name">{{ member.name }}</div>
                    <div class="member-role">{{ member.role }}</div>
                  </div>
                </div>
              </div>
              <div v-else class="placeholder-content">暂无成员</div>
            </div>
            <div v-show="activeSidebarTab !== 'team'" class="placeholder-content"> 暂无记录 </div>
          </div>
        </div>
      </div>
    </div>
  </el-drawer>

  <!-- 添加团队成员弹窗 -->
  <el-dialog
    v-model="memberDialogVisible"
    title="添加团队成员"
    width="450px"
    append-to-body
    class="member-dialog custom-dialog"
  >
    <el-form :model="memberForm" label-width="90px" label-position="left">
      <el-form-item label="添加人员：" required>
        <el-select v-model="memberForm.userNo" placeholder="请选择" filterable style="flex: 1">
          <el-option
            v-for="item in allUsers"
            :key="item.staffId"
            :label="item.staffName"
            :value="item.staffId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成员角色：">
        <el-select v-model="memberForm.roleCode" placeholder="请选择" style="width: 100%">
          <el-option
            v-for="item in teamRoleOptions"
            :key="item.id"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="权限：">
        <el-checkbox v-model="memberForm.updateAccredit" :true-label="1" :false-label="0">分配修改权限</el-checkbox>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitMember">确认</el-button>
        <el-button @click="memberDialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 联系人新增/编辑抽屉 -->
  <el-drawer
    v-model="contactVisible"
    :title="contactForm.id ? '编辑联系人' : '新增联系人'"
    size="70%"
    class="contact-detail-drawer"
    append-to-body
  >
    <el-form :model="contactForm" :rules="contactRules" ref="contactRef" label-width="85px" label-position="right">
      <!-- 基本信息 -->
      <div class="drawer-header-section">基本信息</div>
      <div class="drawer-content-body">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名" required prop="contactName">
              <el-input v-model="contactForm.contactName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人类型" prop="type">
              <el-radio-group v-model="contactForm.type">
                <el-radio label="1">公司职员</el-radio>
                <el-radio label="2">关系资源人</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="contactForm.gender">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="contactForm.age" :min="0" :max="150" controls-position="right" style="width: 100%" />
            </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="请选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input v-model="contactForm.remark" type="textarea" :rows="3" placeholder="请输入描述信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 办公信息 -->
      <div class="drawer-header-section">办公信息</div>
      <div class="drawer-content-body">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="在职状态" prop="jobStatus">
              <el-radio-group v-model="contactForm.jobStatus">
                <el-radio label="1">在职</el-radio>
                <el-radio label="2">离职</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号码" required prop="phone">
              <el-input v-model="contactForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门" required prop="deptName">
              <el-input v-model="contactForm.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="职位" prop="roleName">
              <el-input v-model="contactForm.roleName" placeholder="请输入职位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="办公座机" prop="officePhone">
              <el-input v-model="contactForm.officePhone" placeholder="请输入座机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作内容" prop="jobContent">
              <el-input v-model="contactForm.jobContent" type="textarea" :rows="3" placeholder="请输入工作职责" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 家庭信息 -->
      <div class="drawer-header-section">家庭信息</div>
      <div class="drawer-content-body">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="家庭住址" prop="homeAddress">
               <el-input v-model="contactForm.homeAddressDetail" placeholder="请输入详细家庭地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="家庭情况" prop="familyStatus">
              <el-input v-model="contactForm.familyStatus" placeholder="请输入家庭背景" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="爱好" prop="hobby">
              <el-input v-model="contactForm.hobby" placeholder="请输入兴趣爱好" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性格特征" prop="characterTrait">
              <el-input v-model="contactForm.characterTrait" placeholder="请输入性格描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="是否抽烟" prop="isSmoke">
              <el-radio-group v-model="contactForm.isSmoke">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否喝酒" prop="isDrink">
              <el-radio-group v-model="contactForm.isDrink">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <template #footer>
      <div style="padding: 10px 20px 20px; text-align: right;">
        <el-button @click="contactVisible = false">取消</el-button>
        <el-button type="primary" color="#3b82f6" @click="handleSaveContact">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, computed, reactive, getCurrentInstance, onMounted } from 'vue';
import { Close, Picture, Search, Plus, Edit, CircleCheck, CircleClose } from '@element-plus/icons-vue';
import { listTeamMember, addTeamMember, delTeamMember } from "@/api/customer/teamMember";
import { selectStaffOptionList } from "@/api/customer/crmStaff";
import { getPool, updatePool } from "@/api/customer/customerPool";
import { listByIds } from "@/api/system/oss";
import { listCommonDict, listCustomerTypeOption } from "@/api/customer/customerDict";
import { addContact, updateContact } from "@/api/customer/crmContact";

const { proxy } = getCurrentInstance();
const props = defineProps({
  id: {
    type: [Number, String],
    default: null
  }
});

const emit = defineEmits(['close', 'edit', 'success']);

const visible = ref(false);
const isEdit = ref(false);
const customerData = ref(null); 
const contactList = ref([]);
const opportunityList = ref([]);
const annualAdmissionList = ref([]);
const customerCareList = ref([]);
const attachmentList = ref([]);
const activeMainTab = ref('profile');
const activeSidebarTab = ref('team');
const memberSearch = ref('');

// 编辑表单数据
const editForm = reactive({
  id: undefined,
  customerSourceId: undefined,
  enterpriseTypeId: undefined,
  cooperation: undefined,
  purchaseSize: '',
  saleTarget: '',
  purchaseMethod: '',
});

// 团队成员弹窗相关
const memberDialogVisible = ref(false);
const allUsers = ref([]);
const teamRoleOptions = ref([]);
const memberForm = reactive({
  userNo: undefined,
  roleCode: undefined,
  updateAccredit: 0,
  objectNo: ''
});

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

const contactRules = reactive({
  contactName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  phone: [{ required: true, message: "手机号码不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "部门不能为空", trigger: "blur" }]
});

const { cooperation_status: cooperationOptions, purchase_method: purchaseMethodOptions } = proxy.useDict("cooperation_status", "purchase_method");

// 业务下拉选项
const sourceOptions = ref([]);
const corpTypeOptions = ref([]);

/** 加载业务下拉选项 */
const initOptions = () => {
  // 加载客户来源 (表中 Code 为 K0001)
  listCommonDict('K0001').then(res => {
    sourceOptions.value = res.data || [];
  });
  // 加载企业类型 (表中 Code 为 Q0001)
  listCommonDict('Q0001').then(res => {
    corpTypeOptions.value = res.data || [];
  });
  // 加载团队角色 (表中 Code 为 C0001)
  listCommonDict('C0001').then(res => {
    teamRoleOptions.value = res.data || [];
  });
};

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

// 图片 URL 响应式变量
const businessLicenseUrl = ref('');
const idCardFrontUrl = ref('');
const idCardBackUrl = ref('');
const countryName = ref('中国');

const mainTabs = [
  { key: 'profile', label: '客户资料' },
  { key: 'contacts', label: '客户联系人' }
];

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

const teamMembers = ref([]); 

const filteredMembers = computed(() => {
  if (!memberSearch.value) return teamMembers.value;
  return teamMembers.value.filter(m => m.name && m.name.includes(memberSearch.value));
});

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

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

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

const handleEdit = () => {
  isEdit.value = true;
  // 初始化编辑数据，严格按照原型图
  Object.assign(editForm, {
    id: customerData.value.id,
    customerSourceId: customerData.value.customerSourceId,
    enterpriseTypeId: customerData.value.enterpriseTypeId,
    cooperation: customerData.value.cooperation,
    purchaseSize: customerData.value.customerSalesInfoVo?.purchaseSize || '',
    saleTarget: customerData.value.customerSalesInfoVo?.saleTarget || '',
    purchaseMethod: customerData.value.customerSalesInfoVo?.purchaseMethod || '',
    // 初始化工商信息编辑表单
    customerBusinessInfoBo: customerData.value.customerBusinessInfoVo ? { ...customerData.value.customerBusinessInfoVo } : {
      businessCustomerName: customerData.value.businessCustomerName || '',
      socialCreditCode: '',
      legalPersonName: '',
      registeredCapital: '',
      businessAddress: customerData.value.address || ''
    }
  });
};

/** 打开添加成员弹窗 */
const handleAddMember = () => {
  // 加载 CRM 员工列表
  selectStaffOptionList().then(res => {
    allUsers.value = res.data || [];
  });
  // 重置表单
  Object.assign(memberForm, {
    userNo: undefined,
    roleCode: undefined,
    updateAccredit: 0,
    objectNo: customerData.value.customerNo
  });
  memberDialogVisible.value = true;
};

/** 提交添加成员 */
const submitMember = () => {
  if (!memberForm.userNo) {
    proxy.$modal.msgError("请选择人员");
    return;
  }
  
  // 查找选中人员的真实姓名并填充及其它必填字段
  const selectedUser = allUsers.value.find(u => u.staffId === memberForm.userNo);
  if (selectedUser) {
    memberForm.realName = selectedUser.staffName;
  }
  memberForm.dataType = 2; // 客户对象类型
  memberForm.izManager = 0; // 默认普通成员

  addTeamMember(memberForm).then(res => {
    proxy.$modal.msgSuccess("添加成功");
    memberDialogVisible.value = false;
    refreshTeamMembers();
  });
};

/** 刷新团队成员列表 */
const refreshTeamMembers = () => {
  if (!customerData.value?.customerNo) return;
  listTeamMember(customerData.value.customerNo).then(res => {
    // 渲染列表：转换后端字段到列表展示字段
    teamMembers.value = (res.data || []).map(m => {
      // 优先取后端名，若无则根据本地字典匹配，最后降级显示代码
      let roleName = m.roleCodeName;
      if (!roleName && teamRoleOptions.value.length > 0) {
        const option = teamRoleOptions.value.find(o => String(o.dictValue) === String(m.roleCode));
        if (option) roleName = option.dictLabel;
      }
      
      return {
        id: m.id,
        name: m.realName || '未知',
        role: roleName || m.roleCode
      };
    });
  });
};

/** 取消编辑 */
const handleCancel = () => {
  isEdit.value = false;
};

/** 保存更新 */
const handleSave = () => {
  const submitData = {
    ...customerData.value,
    id: editForm.id,
    customerSourceId: editForm.customerSourceId,
    enterpriseTypeId: editForm.enterpriseTypeId,
    cooperation: editForm.cooperation
  };

  // 销售信息
  if (!submitData.customerSalesInfoBo) {
    submitData.customerSalesInfoBo = { ...customerData.value.customerSalesInfoVo };
  }
  submitData.customerSalesInfoBo.purchaseSize = editForm.purchaseSize;
  submitData.customerSalesInfoBo.saleTarget = editForm.saleTarget;
  submitData.customerSalesInfoBo.purchaseMethod = editForm.purchaseMethod;
  
  // 工商信息：映射 editForm 中的数据到提交对象
  submitData.customerBusinessInfoBo = { ...editForm.customerBusinessInfoBo };

  updatePool(submitData).then(res => {
    proxy.$modal.msgSuccess("保存成功");
    
    // 如果工商信息之前是空的，手动更新本地状态以触发显示
    if (!customerData.value.customerBusinessInfoVo && editForm.customerBusinessInfoBo) {
      customerData.value.customerBusinessInfoVo = { ...editForm.customerBusinessInfoBo };
    }
    if (editForm.customerSourceId) {
      const source = sourceOptions.value.find(o => o.id === editForm.customerSourceId);
      if (source) customerData.value.customerSourceName = source.dictLabel;
    }
    if (editForm.enterpriseTypeId) {
      const corp = corpTypeOptions.value.find(o => o.id === editForm.enterpriseTypeId);
      if (corp) customerData.value.enterpriseTypeName = corp.dictLabel;
    }

    isEdit.value = false;
    loadData(submitData.id); 
    emit('success');
  });
};

/** 新增联系人 */
const handleAddContact = () => {
  if (!customerData.value?.id) {
    proxy.$modal.msgError("无法获取客户ID");
    return;
  }
  Object.assign(contactForm, {
    id: undefined,
    customerId: customerData.value.id,
    contactName: '', type: '1', gender: '1', age: 0, nativePlace: '',
    birthday: '', remark: '', jobStatus: '1', phone: '', deptName: '',
    roleName: '', officePhone: '', jobContent: '', homeProvinceId: undefined,
    homeCityId: undefined, homeAddressDetail: '', familyStatus: '',
    hobby: '', characterTrait: '', isSmoke: '0', isDrink: '0'
  });
  contactVisible.value = true;
};

/** 保存联系人（直接入库） */
const handleSaveContact = () => {
  contactRef.value.validate(valid => {
    if (valid) {
      if (contactForm.id) {
        updateContact(contactForm).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          contactVisible.value = false;
          loadData(customerData.value.id);
        });
      } else {
        addContact(contactForm).then(() => {
          proxy.$modal.msgSuccess("保存成功");
          contactVisible.value = false;
          loadData(customerData.value.id);
        });
      }
    }
  });
};

/** 新增关怀（公海详情暂不使用，保留空函数或移除） */
const handleAddCare = () => {
  proxy.$modal.msgWarning("该功能在公海状态下不可用");
};

const loadData = async (id) => {
  if (!id) return;
  // 重置状态
  isEdit.value = false;
  // 重置 URL
  businessLicenseUrl.value = '';
  idCardFrontUrl.value = '';
  idCardBackUrl.value = '';

  getPool(id).then(response => {
    customerData.value = response.data;
    contactList.value = response.data.customerContactVoList || [];
    
    // 图片转换逻辑：兼容嵌套对象和根级平铺字段
    const bizData = response.data.customerBusinessInfoVo || response.data;
    const bizLicense = bizData.businessLicense || response.data.businessLicense;
    if (bizLicense) {
      listByIds(bizLicense).then(res => {
        if (res.data && res.data.length > 0) {
          businessLicenseUrl.value = res.data[0].url;
        }
      });
    }
    
    const idCard = bizData.legalPersonCardUrl || response.data.legalPersonCardUrl;
    if (idCard) {
      listByIds(idCard).then(res => {
        if (res.data && res.data.length > 0) {
          idCardFrontUrl.value = res.data[0]?.url || '';
          idCardBackUrl.value = res.data[1]?.url || '';
        }
      });
    }
    
    // 名称字段补偿逻辑：如果后端返回的文字为空，根据 ID 从选项中匹配 (移出 bizVo 判断)
    if (response.data.customerSourceId && !response.data.customerSourceName) {
      const source = sourceOptions.value.find(o => o.id === response.data.customerSourceId);
      if (source) customerData.value.customerSourceName = source.dictLabel;
    }
    if (response.data.enterpriseTypeId && !response.data.enterpriseTypeName) {
      const corp = corpTypeOptions.value.find(o => o.id === response.data.enterpriseTypeId);
      if (corp) customerData.value.enterpriseTypeName = corp.dictLabel;
    }
    
    // 加载团队成员：移出 bizVo 嵌套，确保始终尝试加载
    refreshTeamMembers();
  });
};

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

defineExpose({ open });
</script>

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

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

// 头部
.info-header {
  height: 64px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  background-color: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  
  .header-left {
    display: flex;
    align-items: baseline;
    gap: 16px;
    
    .company-name {
      font-size: 20px;
      font-weight: bold;
      color: #111827;
    }
    
    .customer-type {
      font-size: 14px;
      color: #6b7280;
    }
  }
  
  .close-icon {
    font-size: 22px;
    color: #9ca3af;
    cursor: pointer;
    &:hover { color: #374151; }
  }
}

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

// 左侧主内容区域
.info-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-right: 1px solid #f1f5f9;
}

// 标签页
.main-tabs {
  display: flex;
  padding: 0 24px;
  background-color: #ffffff;
  border-bottom: 1px solid #f1f5f9;
  
  .tab-item {
    padding: 16px 20px;
    font-size: 14px;
    color: #374151;
    cursor: pointer;
    position: relative;
    transition: all 0.2s;
    
    &.active {
      color: #ea5413;
      font-weight: bold;
      &::after {
        content: '';
        position: absolute;
        bottom: 0px;
        left: 20px;
        right: 20px;
        height: 2px;
        background-color: #ea5413;
      }
    }
    
    &:hover {
      color: #ea5413;
    }
  }
}

// 滚动区域
.scroll-content {
  flex: 1;
  overflow-y: auto;
  padding: 30px 48px;
  background-color: #ffffff;
  
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }
}

// 区块样式
.section {
  margin-bottom: 48px;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }

  .section-title {
    font-size: 16px;
    font-weight: 700;
    color: #111827;
  }

  .edit-btn {
    background-color: #f97316 !important;
    border-color: #f97316 !important;
    color: white !important;
    height: 32px;
    border-radius: 4px;
    font-size: 13px;
    &:hover {
      background-color: #ea580c !important;
    }
  }

  .section-btns {
    display: flex;
    gap: 12px;
    
    .confirm-btn {
      background-color: #409eff !important;
      border-color: #409eff !important;
      padding: 0 15px;
      height: 32px;
    }

    .cancel-btn {
      background-color: #94a3b8 !important;
      border-color: #94a3b8 !important;
      color: #fff !important;
      padding: 0 15px;
      height: 32px;
    }
  }
}

// 网格布局
.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px 40px;
}

.col-span-3 { grid-column: span 3; }

.info-item {
  display: flex;
  align-items: flex-start;
  min-height: 24px;
  
  .label {
    width: 100px;
    font-size: 13px;
    color: #6b7280;
    flex-shrink: 0;
  }
  
  .value {
    font-size: 13px;
    color: #1f2937;
    font-weight: 500;
  }

  // 图片专用样式
  &.img-row-item {
    flex-direction: column;
    gap: 12px;
    .img-content {
      display: flex;
      gap: 10px;
    }
    .img-box {
      width: 80px;
      height: 80px;
      border-radius: 4px;
      border: 1px solid #e5e7eb;
      background-color: #f9fafb;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      font-size: 24px;
      color: #d1d5db;
      &:hover { border-color: #ea5413; }
    }
  }
}

// 右侧侧边栏
.info-sidebar {
  width: 320px;
  display: flex;
  flex-direction: column;
  background-color: #fcfcfc;
  border-left: 1px solid #f1f5f9;
}

.sidebar-tabs {
  display: flex;
  padding: 0 16px;
  border-bottom: 1px solid #f1f5f9;
  justify-content: space-between;
  
  .sidebar-tab-item {
    padding: 16px 4px;
    font-size: 13px;
    color: #6b7280;
    cursor: pointer;
    position: relative;
    
    &.active {
      color: #ea5413;
      font-weight: 600;
      &::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 4px;
        right: 4px;
        height: 2px;
        background-color: #ea5413;
      }
    }
  }
}

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

.sidebar-section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .sidebar-section-title {
    font-size: 14px;
    font-weight: bold;
    color: #111827;
  }
  
  .add-icon {
    font-size: 18px;
    color: #9ca3af;
    cursor: pointer;
    &:hover { color: #ea5413; }
  }
}

.search-input {
  margin-bottom: 24px;
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #e5e7eb inset !important;
    border-radius: 4px;
    height: 36px;
  }
}

.member-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.member-item {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .member-avatar {
    background-color: #f1f5f9;
    color: #94a3b8;
    font-size: 12px;
  }
  
  .member-info {
    .member-name {
      font-size: 13px;
      font-weight: 500;
      color: #333;
    }
    .member-role {
      font-size: 12px;
      color: #999;
    }
  }
}

.placeholder-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 120px;
  color: #bbb;
  font-size: 12px;
}

// “客户联系人” & 其他 Tab 表格容器
.attachments-wrapper, .tab-table-wrapper, .contacts-wrapper, .care-wrapper {
  padding: 0 0 20px;
}
.attachments-header, .table-toolbar, .care-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  .el-button {
    height: 32px;
  }
}

.contacts-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  .add-contact-btn {
    background-color: #3b82f6;
    border-color: #3b82f6;
    height: 32px;
  }
}

.contacts-table, .custom-tab-table {
  border-radius: 4px;
  overflow: hidden;
  margin-top: 10px;
  :deep(.el-table__header) {
    th {
      border-bottom: 1px solid #f1f5f9;
      background-color: #f8fafc !important;
      font-weight: bold;
      color: #333;
    }
  }
}

.empty-box {
  padding: 40px 0;
  color: #94a3b8;
  font-size: 14px;
}
.member-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }
  :deep(.el-form-item) {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    .el-form-item__label {
      padding-bottom: 0px;
      line-height: 32px;
    }
    .el-form-item__content {
      margin-left: 0 !important;
      display: flex;
      flex: 1;
    }
  }
}

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

.drawer-content-body {
  padding: 0 10px 20px;
}

:deep(.contact-detail-drawer) {
  .el-drawer__header {
    margin-bottom: 0;
    padding: 20px 24px;
    border-bottom: 1px solid #f1f5f9;
    span {
      font-weight: bold;
      color: #111827;
    }
  }
  .el-drawer__body {
    padding: 24px;
    background-color: #fdfdfd;
  }
}
</style>
