<template>
  <el-drawer
    v-model="visible"
    size="85%"
    class="detail-drawer"
    :with-header="false"
    destroy-on-close
  >
    <div class="detail-wrapper" v-loading="loading">
      <!-- 顶部标题栏 -->
      <div class="detail-header">
        <span class="main-title">{{ form.projectName || '销售线索详情' }}</span>
        <el-icon class="close-btn" @click="visible = false"><Close /></el-icon>
      </div>

      <!-- 主体内容区 -->
      <div class="detail-main">
        <!-- 左侧内容区 -->
        <div class="detail-left">
          <!-- 顶部标签页 -->
          <div class="left-tabs">
            <div
              v-for="tab in [{k:'info',n:'项目信息'},{k:'contact',n:'项目联系人'},{k:'analysis',n:'结果分析'},{k:'attachment',n:'附件'}]"
              :key="tab.k"
              :class="['left-tab-item', { active: activeTab === tab.k }]"
              @click="activeTab = tab.k"
            >{{ tab.n }}</div>
          </div>

          <!-- 基本信息 Tab -->
          <div v-show="activeTab === 'info'" class="tab-content">
            <div class="info-section">
              <div class="section-header">
                <span class="section-label">基本信息</span>
                <el-button v-if="!isReadOnly" type="primary" size="small" @click="handleEdit"><el-icon style="margin-right:4px;vertical-align:-2px;"><Edit /></el-icon>编 辑</el-button>
              </div>
              <div class="info-row-item">
                <span class="info-label">项目名称</span>
                <span class="info-value">{{ form.projectName }}</span>
              </div>
              <div class="info-grid">
                <div class="info-item"><span class="info-label">归属公司</span><span class="info-value">{{ findCompanyName(form.companyNo) }}</span></div>
                <div class="info-item"><span class="info-label">客户名称</span><span class="info-value">{{ form.customerName }}</span></div>
                <div class="info-item"></div>
              </div>
              <div class="info-grid">
                <div class="info-item"><span class="info-label">行业</span><span class="info-value">{{ findIndustryName(form.profession) }}</span></div>
                <div class="info-item"><span class="info-label">部门</span><span class="info-value">{{ form.deptName }}</span></div>
                <div class="info-item"><span class="info-label">营销活动</span><span class="info-value">{{ form.marketingActivityName }}</span></div>
              </div>
              <div class="info-grid">
                <div class="info-item"><span class="info-label">金额(万)</span><span class="info-value">{{ Number(form.projectBudget || 0).toFixed(2) }}</span></div>
                <div class="info-item"><span class="info-label">赢单率(%)</span><span class="info-value">{{ form.winRate ? form.winRate + '%' : '' }}</span></div>
                <div class="info-item"><span class="info-label">立项时间</span><span class="info-value">{{ parseTime(form.approvalDate, '{y}-{m}-{d}') }}</span></div>
              </div>
              <div class="info-grid">
                <div class="info-item"><span class="info-label">成单时间</span><span class="info-value">{{ parseTime(form.expectedCompletionTime, '{y}-{m}-{d}') }}</span></div>
                <div class="info-item"><span class="info-label">项目状态</span><span class="info-value"><el-tag :type="form.status === '1' ? 'success' : 'primary'">{{ form.statusName }}</el-tag></span></div>
                <div class="info-item"></div>
              </div>
              <div class="info-grid">
                <div class="info-item"><span class="info-label">项目负责人</span><span class="info-value">{{ form.leaderName || findUserName(form.leader) }}</span></div>
                <div class="info-item"><span class="info-label">产品支持</span><span class="info-value">{{ form.productSupportName || findUserName(form.productSupport) }}</span></div>
                <div class="info-item"></div>
              </div>
            </div>

            <div class="info-section">
              <div class="section-header"><span class="section-label">项目情况</span></div>
              <div class="info-grid">
                <div class="info-item"><span class="info-label">信息来源</span><span class="info-value">{{ findInfoSourceName(form.infoSource) }}</span></div>
                <div class="info-item"><span class="info-label">项目级别</span><span class="info-value">{{ findProjectLevelName(form.projectLevel) }}</span></div>
                <div class="info-item"><span class="info-label">项目区域</span><span class="info-value">{{ form.projectArea }}</span></div>
              </div>
              <div class="info-grid">
                 <div class="info-item"><span class="info-label">采购方式</span><span class="info-value">{{ findProcurementMethodName(form.procurementMethod) }}</span></div>
                 <div class="info-item"><span class="info-label">平台名称</span><span class="info-value">{{ form.platformCode }}</span></div>
                 <div class="info-item"></div>
              </div>
              <div class="info-row-item"><span class="info-label">采购内容</span><span class="info-value">{{ form.purchaseContent }}</span></div>
              <div class="info-row-item"><span class="info-label">项目描述</span><span class="info-value">{{ form.projectDescription }}</span></div>
              <div class="info-row-item"><span class="info-label">竞争对手</span><span class="info-value">{{ form.competitor }}</span></div>
            </div>
          </div>

          <!-- 项目联系人 Tab -->
          <div v-show="activeTab === 'contact'" class="tab-content">
            <div class="contact-section">
              <div class="contact-header">
                <el-dropdown v-if="!isReadOnly" trigger="hover" @command="handleContactCommand">
                  <el-button type="primary" size="small" icon="Plus">
                    新建联系人 <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-item command="associate">关联客户联系人</el-dropdown-item>
                    <el-dropdown-item command="create">新建联系人</el-dropdown-item>
                  </template>
                </el-dropdown>
              </div>
              <el-table :data="contactList" border class="contact-table" v-loading="contactLoading">
                <el-table-column label="姓名" align="center" min-width="100">
                  <template #default="scope">
                    <el-link type="primary" :underline="false" @click="viewContactDetail(scope.row)">
                      {{ scope.row.name || scope.row.contactName }}
                    </el-link>
                  </template>
                </el-table-column>
                <el-table-column label="性别" align="center" width="80">
                  <template #default="scope">
                    <dict-tag :options="genderOptions" :value="scope.row.sex || scope.row.gender" />
                  </template>
                </el-table-column>
                <el-table-column label="部门" align="center" width="120">
                  <template #default="scope">
                    {{ scope.row.department || scope.row.deptName }}
                  </template>
                </el-table-column>
                <el-table-column label="职位" align="center" prop="position" min-width="120" show-overflow-tooltip />
                <el-table-column label="项目角色" align="center" width="120">
                  <template #default="scope">
                    <dict-tag :options="projectRoleOptions" :value="scope.row.projectRole" />
                  </template>
                </el-table-column>
                <el-table-column label="公关情况" align="center" width="150" show-overflow-tooltip>
                  <template #default="scope">
                    {{ scope.row.prStatus }}
                  </template>
                </el-table-column>
                <el-table-column label="是否关键人" align="center" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.isKeyPerson == 1 ? 'danger' : 'info'">
                      {{ scope.row.isKeyPerson == 1 ? '是' : '否' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="140" fixed="right">
                  <template #default="scope">
                    <el-button v-if="!isReadOnly" link type="primary" size="small" @click="handleEditContact(scope.row)">编辑</el-button>
                    <el-button v-if="!isReadOnly" link type="danger" size="small" @click="handleDeleteContact(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <!-- 结果分析 Tab -->
          <div v-show="activeTab === 'analysis'" class="tab-content">
            <div class="analysis-section">
              <div class="analysis-form">
                <div class="analysis-row">
                  <span class="form-label">成交结果</span>
                  <el-radio-group v-model="analysisForm.resultType" class="result-radio">
                    <el-radio value="win">赢单</el-radio>
                    <el-radio value="lose">丢单</el-radio>
                  </el-radio-group>
                  <div style="flex:1"></div>
                  <el-button v-if="!isReadOnly" type="primary" icon="CircleCheck" @click="handleSaveAnalysis">保 存</el-button>
                </div>
                <template v-if="analysisForm.resultType === 'win'">
                  <div class="analysis-row"><span class="form-label">赢单总结</span></div>
                  <div class="summary-textarea-wrap">
                    <el-input v-model="analysisForm.summary" type="textarea" :rows="4" placeholder="请输入赢单总结" />
                  </div>
                </template>
                <template v-else>
                  <div class="analysis-row"><span class="form-label">丢单原因</span></div>
                  <div class="summary-textarea-wrap">
                    <el-input v-model="analysisForm.loseReason" type="textarea" :rows="4" placeholder="请输入丢单原因" />
                  </div>
                </template>
                <div class="analysis-row" style="margin-top: 20px;"><span class="form-label">附件</span></div>
                <div v-if="!isReadOnly" class="upload-area">
                  <el-upload
                    :action="uploadFileUrl"
                    :headers="headers"
                    :on-success="handleAnalysisUploadSuccess"
                    :show-file-list="false"
                    multiple
                  >
                    <el-button type="primary" icon="Upload">上 传</el-button>
                  </el-upload>
                </div>
                <div v-if="analysisFileList.length > 0" class="analysis-file-list" style="margin-top:10px;">
                  <el-table :data="analysisFileList" border size="small">
                    <el-table-column label="文件名称" prop="name" show-overflow-tooltip />
                    <el-table-column label="操作" width="120" align="center">
                       <template #default="scope">
                          <el-button link type="primary" @click="downloadFile(scope.row)">下载</el-button>
                          <el-button v-if="!isReadOnly" link type="danger" @click="handleAnalysisDeleteFile(scope.$index)">删除</el-button>
                       </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </div>

          <!-- 附件 Tab -->
          <div v-show="activeTab === 'attachment'" class="tab-content">
            <div class="attachment-section">
              <div v-if="!isReadOnly" style="margin-bottom: 12px; display: flex; justify-content: flex-end;">
                <el-upload
                  :action="uploadFileUrl"
                  :headers="headers"
                  :on-success="handleUploadSuccess"
                  :show-file-list="false"
                  multiple
                >
                  <el-button type="primary" icon="Upload">上传附件</el-button>
                </el-upload>
              </div>
              <el-table :data="detailFileList" border class="attach-table">
                <el-table-column label="文件名称" prop="name" show-overflow-tooltip />
                <el-table-column label="文件类型" prop="type" width="120" align="center" />
                <el-table-column label="上传时间" prop="uploadTime" width="170" align="center" />
                <el-table-column label="操作" width="150" align="center">
                  <template #default="scope">
                    <el-link type="primary" :underline="false" @click="handleDownloadFile(scope.row)" style="margin-right: 10px;">下载</el-link>
                    <el-link v-if="!isReadOnly" type="danger" :underline="false" @click="handleDeleteFile(scope.row)">删除</el-link>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 右侧侧边栏 (整合通用组件) -->
        <div class="detail-right">
          <BusinessActivity 
            v-if="form.id"
            :business-id="form.id" 
            :dataType="1"
            business-type="leads"
            :info-data="{
              ...form,
              industryName: findIndustryName(form.profession),
              profession: findIndustryName(form.profession),
              customerName: form.customerName
            }"
            @update-readonly="val => isReadOnly = val"
          />
        </div>
      </div>
    </div>

    <!-- 关联客户联系人弹窗 -->
    <el-dialog title="关联客户联系人" v-model="associateVisible" width="900px" append-to-body>
      <el-table
        v-loading="associateLoading"
        :data="associateList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="联系人" align="center">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="viewContactDetail(scope.row)">
              {{ scope.row.name || scope.row.contactName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center">
          <template #default="scope">
            {{ scope.row.department || scope.row.deptName }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="customerName" show-overflow-tooltip />
        <el-table-column label="职位" align="center">
          <template #default="scope">
            {{ scope.row.position || scope.row.roleName }}
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center" prop="phone" />
        <el-table-column label="办公电话" align="center">
          <template #default="scope">
            {{ scope.row.officePhone || scope.row.landline || '' }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssociate">确 认</el-button>
          <el-button @click="associateVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 编辑/新建项目联系人抽屉 (完全对齐商机模块) -->
    <el-drawer v-model="projectContactDrawerOpen" direction="rtl" size="80%" destroy-on-close :with-header="false">
      <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;">{{ projectContactForm.id ? '编辑项目联系人' : '新建项目联系人' }}</span>
        <el-icon @click="projectContactDrawerOpen = false" style="cursor: pointer; font-size: 18px; color: #94a3b8;"><Close /></el-icon>
      </div>

      <div class="drawer-body-custom" style="padding: 0; overflow-y: auto; height: calc(100% - 110px);">
        <el-form :model="projectContactForm" :rules="projectContactRules" ref="projectContactFormRef" label-width="100px" class="no-bold-label">
          <!-- 基本信息 -->
          <div class="form-section-group">
            <div class="section-group-title">基本信息</div>
            <div class="section-group-content">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="姓名" prop="contactName">
                    <el-input v-model="projectContactForm.contactName" placeholder="请输入" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="联系人类型" prop="type">
                    <el-radio-group v-model="projectContactForm.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="projectContactForm.gender">
                      <el-radio value="0">男</el-radio>
                      <el-radio value="1">女</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 v-model="projectContactForm.age" placeholder="请输入" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="籍贯" prop="nativePlace">
                    <el-input v-model="projectContactForm.nativePlace" placeholder="请输入" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="生日" prop="birthday">
                    <el-date-picker v-model="projectContactForm.birthday" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="描述" prop="remark">
                    <el-input v-model="projectContactForm.remark" type="textarea" :rows="2" maxlength="200" show-word-limit placeholder="请输入" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 办公信息 -->
          <div class="form-section-group">
            <div class="section-group-title">办公信息</div>
            <div class="section-group-content">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="在职状态" prop="jobStatus">
                    <el-radio-group v-model="projectContactForm.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="手机号码" prop="phone">
                    <el-input v-model="projectContactForm.phone" placeholder="请输入" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="部门" prop="deptName">
                    <el-input v-model="projectContactForm.deptName" placeholder="请输入" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="职位" prop="position">
                    <el-input v-model="projectContactForm.position" placeholder="请输入" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="办公座机" prop="officePhone">
                    <el-input v-model="projectContactForm.officePhone" placeholder="请输入" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="16">
                  <el-form-item label="办公地址" prop="addressDetail">
                    <div style="display: flex; gap: 10px; width: 100%">
                      <el-cascader
                        v-model="projectContactForm.officeRegion"
                        ref="officeRegionCascader"
                        :options="areaOptions"
                        :props="{ label: 'areaName', value: 'id', children: 'children' }"
                        placeholder="请选择省/市/县"
                        style="width: 220px"
                        clearable
                      />
                      <el-input v-model="projectContactForm.addressDetail" placeholder="请输入详细地址" style="flex: 1" />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="工作内容" prop="jobContent">
                    <el-input v-model="projectContactForm.jobContent" type="textarea" :rows="2" maxlength="200" show-word-limit placeholder="请输入" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 项目决策 -->
          <div class="form-section-group">
            <div class="section-group-title">项目决策</div>
            <div class="section-group-content">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="项目角色" prop="projectRole">
                    <el-select v-model="projectContactForm.projectRole" style="width: 100%" placeholder="请选择" filterable>
                      <el-option v-for="item in projectRoleOptions" :key="item.value" :label="item.label" :value="parseInt(item.value)" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否关键人" prop="isKeyPerson">
                    <el-select v-model="projectContactForm.isKeyPerson" style="width: 100%" placeholder="请选择">
                      <el-option label="是" :value="1" />
                      <el-option label="否" :value="0" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="公关情况" prop="prStatus">
                    <el-input v-model="projectContactForm.prStatus" type="textarea" :rows="2" maxlength="500" show-word-limit placeholder="请输入详细公关情况" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 家庭信息 -->
          <div class="form-section-group">
            <div class="section-group-title">家庭信息</div>
            <div class="section-group-content">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="家庭住址" prop="homeAddressDetail">
                    <div style="display: flex; gap: 10px; width: 100%">
                      <el-cascader
                        v-model="projectContactForm.homeRegion"
                        ref="homeRegionCascader"
                        :options="areaOptions"
                        :props="{ label: 'areaName', value: 'id', children: 'children' }"
                        placeholder="请选择省/市/县"
                        style="width: 220px"
                        clearable
                      />
                      <el-input v-model="projectContactForm.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="projectContactForm.familyStatus" placeholder="请输入家庭情况" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="爱好" prop="hobby">
                    <el-input v-model="projectContactForm.hobby" placeholder="请输入爱好" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="性格特征" prop="characterTrait">
                    <el-input v-model="projectContactForm.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="projectContactForm.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="projectContactForm.isDrink">
                      <el-radio value="1">是</el-radio>
                      <el-radio value="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form>
      </div>

      <div class="drawer-footer-standard" style="padding: 15px 20px; border-top: 1px solid #f0f0f0; text-align: right;">
        <el-button @click="projectContactDrawerOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitProjectContact" :loading="contactSubmitting">确 定</el-button>
      </div>
    </el-drawer>

    <!-- 联系人详情预览弹窗 -->
    <el-dialog title="联系人详情" v-model="contactDetailVisible" width="600px" append-to-body>
      <div v-loading="contactDetailLoading" class="contact-detail-preview">
        <div class="preview-section">
          <div class="preview-title">个人信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">{{ contactForm.contactName || contactForm.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ contactForm.gender == '0' ? '男' : (contactForm.gender == '1' ? '女' : '未知') }}</el-descriptions-item>
            <el-descriptions-item label="人员编号">{{ contactForm.contactNo }}</el-descriptions-item>
            <el-descriptions-item label="籍贯">{{ contactForm.nativePlace }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ contactForm.age }}</el-descriptions-item>
            <el-descriptions-item label="生日">{{ parseTime(contactForm.birthday, '{y}-{m}-{d}') }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="preview-section" style="margin-top: 20px;">
          <div class="preview-title">办公信息</div>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="客户名称">{{ contactForm.customerName }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ contactForm.deptName || contactForm.department }}</el-descriptions-item>
            <el-descriptions-item label="职位">{{ contactForm.roleName || contactForm.position }}</el-descriptions-item>
            <el-descriptions-item label="手机号码">{{ contactForm.phone }}</el-descriptions-item>
            <el-descriptions-item label="办公座机">{{ contactForm.officePhone }}</el-descriptions-item>
            <el-descriptions-item label="办公地址">{{ contactForm.addressDetail }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="preview-section" style="margin-top: 20px;">
          <div class="preview-title">项目决策</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="项目角色">
              <dict-tag :options="projectRoleOptions" :value="contactForm.projectRole" />
            </el-descriptions-item>
            <el-descriptions-item label="是否关键人">
              <el-tag :type="contactForm.isKeyPerson == 1 ? 'danger' : 'info'">
                {{ contactForm.isKeyPerson == 1 ? '是' : '否' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="公关情况" :span="2">
              {{ contactForm.prStatus }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <el-button @click="contactDetailVisible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, watch, getCurrentInstance, toRefs } from 'vue';
import { getLeads, updateLeads } from '@/api/saleManage/leads/index';
import { listContact, addContact, updateContact, delContact, getContact } from '@/api/customer/crmContact';
import { getSalesResultAnalyzeByObjectNo, addSalesResultAnalyze, updateSalesResultAnalyze } from '@/api/saleManage/leads/salesResultAnalyze';
import { listByIds } from '@/api/system/oss/index';
import { listProvinceWithCities } from "@/api/customer/addressArea";
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { globalHeaders } from '@/utils/request';
import BusinessActivity from '../../common/businessActivity.vue';
import { Close, Edit, Plus, Upload, CircleCheck, ArrowDown } from '@element-plus/icons-vue';
import { onMounted } from 'vue';

const props = defineProps({
  modelValue: Boolean,
  id: [String, Number],
  infoData: Object,
  saleStatusOptions: Array,
  companyOptions: Array,
  industryOptions: Array,
  projectLevelOptions: Array,
  procurementMethodOptions: Array,
  infoSourceOptions: Array,
  userOptions: Array
});

const emit = defineEmits(['update:modelValue', 'edit']);

const visible = ref(props.modelValue);
const isReadOnly = ref(true);
const loading = ref(false);
const activeTab = ref('info');
const form = ref({});
const contactList = ref([]);
const contactLoading = ref(false);
const analysisForm = reactive({ resultType: 'win' });
const analysisFileList = ref([]);
const detailFileList = ref([]);
const associateVisible = ref(false);
const associateLoading = ref(false);
const associateList = ref([]);
const selectedContacts = ref([]);
const contactDetailVisible = ref(false);
const contactDetailLoading = ref(false);
const contactForm = ref({});
const areaOptions = ref([]);
const projectContactDrawerOpen = ref(false);
const projectContactFormRef = ref(null);
const officeRegionCascader = ref(null);
const homeRegionCascader = ref(null);
const contactSubmitting = ref(false);
const currentId = ref(props.id);
const projectContactForm = reactive({
  id: undefined,
  customerId: undefined,
  contactName: '',
  type: '1',
  gender: '0',
  age: null,
  nativePlace: '',
  birthday: null,
  remark: null,
  jobStatus: '1',
  phone: '',
  deptName: '',
  position: '',
  officePhone: '',
  officeRegion: [],
  provincialCityCounty: '',
  addressDetail: '',
  jobContent: null,
  projectRole: null,
  isKeyPerson: 0,
  prStatus: null,
  familyStatus: null,
  hobby: null,
  characterTrait: null,
  isSmoke: '0',
  isDrink: '0',
  homeRegion: [],
  homeAddressDetail: null
});
const projectContactRules = {
  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' }
  ]
};
const proxy = getCurrentInstance().proxy;
const { 
  LXRJE0001: projectRoleOptions,
  sys_user_sex: genderOptions
} = toRefs(reactive(proxy.useDict("LXRJE0001", "sys_user_sex")));

const uploadFileUrl = import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload';
const headers = globalHeaders();

watch(() => props.modelValue, (val) => {
  visible.value = val;
}, { immediate: true });

watch(() => visible.value, (val) => {
  if (val) {
    loadDicts();
    loadAreaOptions();
    if (props.infoData && Object.keys(props.infoData).length > 0) {
      form.value = { ...props.infoData };
    }
    const targetId = props.id || currentId.value;
    if (targetId) {
      getDetail(targetId);
    }
    // 强制触发一次地址加载
    loadAreaOptions();
  }
  emit('update:modelValue', val);
});

const open = (id, options = {}) => {
  visible.value = true;
  activeTab.value = options.activeTab || 'info';
  currentId.value = id;
  // 这种情况下，watch 也会触发，但我们可以显式调用以防万一
  if (id) {
    getDetail(id);
  }
  
  if (options.autoCreateContact) {
    // 延迟确保详情加载和抽屉组件就绪
    setTimeout(() => {
      handleNewProjectContact();
    }, 500);
  }
};

const loadDicts = () => {
};

const loadAreaOptions = () => {
  listProvinceWithCities().then(res => {
    // 接口返回的是分页对象 res.rows
    const list = res.rows || [];
    if (list.length > 0) {
      // 这里的 props 映射是 { label: 'areaName', value: 'id', children: 'children' }
      // 我们通过 handleTree 构建树形结构
      areaOptions.value = handleTree(list, "id", "parentId");
    }
  });
};

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

const getDetail = (id) => {
  if (!id) return;
  loading.value = true;
  getLeads(id).then(res => {
    // 兼容处理：有些接口返回 res.data，有些直接返回对象
    const data = res.data || res;
    if (data && typeof data === 'object') {
      form.value = data;
      // 如果数据中已经带了 customerId，直接作为 realCustomerId
      if (data.customerId) {
        form.value.realCustomerId = data.customerId;
      }
      // 通过客户编号查询真实的客户 ID (作为补充校验)
      if (data.customerNo) {
        listCustomerInfo({ customerNo: data.customerNo }).then(res => {
          if (res.rows && res.rows.length > 0) {
            form.value.realCustomerId = res.rows[0].id;
          }
          loadProjectContacts();
          loadAnalysisData();
          loadOssFiles();
        });
      } else {
        loadProjectContacts();
        loadAnalysisData();
        loadOssFiles();
      }
    } else {
      proxy.$modal.msgWarning("未获取到详情数据");
    }
  }).catch(err => {
    console.error('获取详情失败:', err);
  }).finally(() => {
    loading.value = false;
  });
};

const findUserName = (id) => {
  if (!id) return '';
  const user = (props.userOptions || []).find(u => String(u.staffId || u.userId) === String(id));
  return user ? (user.staffName || user.nickName) : id;
};

const loadProjectContacts = () => {
  contactLoading.value = true;
  
  const params = {};
  // 根据数据库表结构，联系人关联项目的字段是 platform_code，因此这里必须传 platformCode
  if (form.value.realCustomerId || form.value.customerId) {
    params.customerId = form.value.realCustomerId || form.value.customerId;
  }
  if (form.value.projectNo) {
    params.platformCode = form.value.projectNo;
  }

  // 兜底：如果既没有客户ID也没有项目编号，尝试用客户名称
  if (!params.customerId && !params.platformCode && form.value.customerName) {
    params.customerName = form.value.customerName;
  }

  // 必须要有查询条件，避免无条件查询出系统中所有的联系人
  if (Object.keys(params).length === 0) {
    contactList.value = [];
    contactLoading.value = false;
    return;
  }

  listContact(params).then(res => {
    contactList.value = res.rows || [];
  }).finally(() => {
    contactLoading.value = false;
  });
};

const loadAnalysisData = async () => {
  if (!form.value.projectNo) return;
  const res = await getSalesResultAnalyzeByObjectNo(form.value.projectNo);
  if (res.data) {
    Object.assign(analysisForm, {
      id: res.data.id,
      resultType: res.data.dealResult === 1 ? 'win' : 'lose',
      summary: res.data.winSumUp,
      loseReason: res.data.loseReason,
      fileNo: res.data.fileNo
    });
    if (analysisForm.fileNo) {
      const ossRes = await listByIds(analysisForm.fileNo);
      analysisFileList.value = ossRes.data.map(i => ({ 
        name: i.originalName || i.fileName, 
        url: i.url, 
        ossId: i.ossId, 
        type: (i.originalName || i.fileName || '').split('.').pop().toUpperCase() 
      }));
    }
  }
};

const loadOssFiles = async () => {
  if (form.value.fileNo) {
    const res = await listByIds(form.value.fileNo);
    detailFileList.value = res.data.map(i => ({ 
      name: i.originalName || i.fileName, 
      url: i.url, 
      ossId: i.ossId,
      uploadTime: i.createTime, 
      type: (i.originalName || i.fileName || '').split('.').pop().toUpperCase() 
    }));
  } else {
    detailFileList.value = [];
  }
};

const handleUploadSuccess = async (res) => {
  if (res.code === 200) {
    const file = res.data;
    const ossId = file.ossId;
    const currentFileNo = form.value.fileNo ? form.value.fileNo.split(',').filter(Boolean) : [];
    currentFileNo.push(ossId);
    const newFileNo = currentFileNo.join(',');
    try {
      await updateLeads({ id: form.value.id, fileNo: newFileNo });
      form.value.fileNo = newFileNo;
      loadOssFiles();
      proxy.$modal.msgSuccess("上传成功");
    } catch (e) {
      proxy.$modal.msgError("附件保存失败");
    }
  } else {
    proxy.$modal.msgError(res.msg || "上传失败");
  }
};

const handleAnalysisUploadSuccess = (res) => {
  if (res.code === 200) {
    const file = res.data;
    const fileName = file.originalName || file.fileName || '未知文件';
    analysisFileList.value.push({
      name: fileName,
      url: file.url,
      ossId: file.ossId,
      type: fileName.split('.').pop().toUpperCase()
    });
    proxy.$modal.msgSuccess("上传成功");
  } else {
    proxy.$modal.msgError(res.msg || "上传失败");
  }
};

const handleAnalysisDeleteFile = (index) => {
  analysisFileList.value.splice(index, 1);
};

const handleSaveAnalysis = async () => {
  if (!form.value.projectNo) {
    proxy.$modal.msgWarning("项目编号缺失，无法保存");
    return;
  }
  
  const ossIds = analysisFileList.value.map(f => f.ossId).join(',');
  const payload = {
    ...analysisForm,
    objectNo: form.value.projectNo,
    dealResult: analysisForm.resultType === 'win' ? 1 : 2,
    winSumUp: analysisForm.summary,
    fileNo: ossIds
  };

  proxy.$modal.loading("正在保存...");
  try {
    if (analysisForm.id) {
      await updateSalesResultAnalyze(payload);
    } else {
      await addSalesResultAnalyze(payload);
    }
    proxy.$modal.msgSuccess("保存成功");
    loadAnalysisData(); // 重新加载数据
  } finally {
    proxy.$modal.closeLoading();
  }
};

const downloadFile = (file) => {
  if (file.url) {
    window.open(file.url, '_blank');
  }
};

// 工具方法
const findCompanyName = (no) => props.companyOptions?.find(i => i.companyCode == no)?.companyName || no;
const findIndustryName = (id) => props.industryOptions?.find(i => i.id == id)?.industryCategoryName || id;
const findProjectLevelName = (v) => props.projectLevelOptions?.find(i => i.value == v)?.label || v;
const findInfoSourceName = (v) => props.infoSourceOptions?.find(i => i.value == v)?.label || v;
const findProcurementMethodName = (v) => props.procurementMethodOptions?.find(i => i.value == v)?.label || v;

const handleEdit = () => { emit('edit', form.value); };

// 处理联系人下拉菜单命令
const handleContactCommand = (command) => {
  if (command === 'associate') {
    openAssociateDialog();
  } else if (command === 'create') {
    handleNewProjectContact();
  }
};

const handleNewProjectContact = () => {
  Object.assign(projectContactForm, {
    id: undefined,
    customerId: form.value.customerId,
    contactName: '', type: '1', gender: '0', age: null, deptName: '',
    position: '', projectRole: null, isKeyPerson: 0, jobStatus: '1', phone: '',
    nativePlace: '', birthday: null, remark: null, officePhone: '', officeRegion: [], provincialCityCounty: '', addressDetail: '',
    jobContent: null, prStatus: null,
    familyStatus: null, hobby: null, characterTrait: null, isSmoke: '0', isDrink: '0',
    homeRegion: [], homeAddressDetail: null
  });
  projectContactDrawerOpen.value = true;
};

// 打开关联联系人弹窗
const openAssociateDialog = () => {
  if (!form.value.customerName) {
    proxy.$modal.msgWarning("当前线索未绑定客户，无法关联联系人");
    return;
  }
  associateVisible.value = true;
  associateLoading.value = true;
  // 关联客户联系人需要显示系统中所有的联系人供用户选择
  listContact({}).then(res => {
    // 过滤掉已经关联到当前线索的联系人
    const currentIds = contactList.value.map(c => c.id);
    associateList.value = (res.rows || []).filter(item => !currentIds.includes(item.id));
  }).finally(() => {
    associateLoading.value = false;
  });
};

// 选择变更
const handleSelectionChange = (selection) => {
  selectedContacts.value = selection;
};

// 提交关联
const submitAssociate = async () => {
  if (selectedContacts.value.length === 0) {
    proxy.$modal.msgWarning("请选择要关联的联系人");
    return;
  }
  
  try {
    proxy.$modal.loading("正在关联...");
    const promises = selectedContacts.value.map(contact => {
      const payload = {
        ...contact,
        customerId: form.value.realCustomerId || form.value.customerId || contact.customerId,
        platformCode: form.value.projectNo || ''
      };
      return updateContact(payload);
    });
    
    await Promise.all(promises);
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("关联成功");
    associateVisible.value = false;
    loadProjectContacts();
  } catch (error) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("关联失败");
  }
};

// 查看联系人详情
const viewContactDetail = (row) => {
  const contactId = row.id;
  if (!contactId) return;
  contactDetailVisible.value = true;
  contactDetailLoading.value = true;
  getContact(contactId).then(res => {
    contactForm.value = res.data || {};
  }).finally(() => {
    contactDetailLoading.value = false;
  });
};

const handleEditContact = (row) => {
  const contactId = row.contactId || row.id;
  if (!contactId) return;

  // 1. 重置表单，确保不残留上次的数据
  Object.assign(projectContactForm, {
    id: undefined,
    customerId: undefined,
    contactName: '', type: '1', gender: '0', age: null, deptName: '',
    position: '', projectRole: null, isKeyPerson: 0, jobStatus: '1', phone: '',
    nativePlace: '', birthday: null, remark: null, officePhone: '', officeRegion: [], provincialCityCounty: '', addressDetail: '',
    jobContent: null, prStatus: null,
    familyStatus: null, hobby: null, characterTrait: null, isSmoke: '0', isDrink: '0',
    homeRegion: [], homeAddressDetail: null
  });

  // 2. 请求详情数据
  proxy.$modal.loading("正在获取详情...");
  getContact(contactId).then(res => {
    const data = res.data || {};
    if (!data.id) {
      proxy.$modal.msgError("获取联系人详情失败");
      return;
    }

    // 3. 赋值回显
    projectContactForm.id = data.id;
    projectContactForm.customerId = data.customerId;
    projectContactForm.contactName = data.contactName;
    projectContactForm.gender = String(data.gender || '0');
    projectContactForm.deptName = data.deptName;
    projectContactForm.position = data.position;
    projectContactForm.projectRole = data.projectRole !== null && data.projectRole !== undefined ? Number(data.projectRole) : null;
    projectContactForm.isKeyPerson = data.isKeyPerson !== null && data.isKeyPerson !== undefined ? Number(data.isKeyPerson) : 0;
    projectContactForm.prStatus = data.prStatus;
    projectContactForm.phone = data.phone;
    projectContactForm.type = String(data.type || '1');
    projectContactForm.jobStatus = String(data.jobStatus || '1');
    projectContactForm.age = data.age;
    projectContactForm.nativePlace = data.nativePlace;
    projectContactForm.birthday = data.birthday;
    projectContactForm.remark = data.remark;
    projectContactForm.officePhone = data.officePhone;
    projectContactForm.addressDetail = data.addressDetail;
    projectContactForm.jobContent = data.jobContent;
    projectContactForm.familyStatus = data.familyStatus;
    projectContactForm.hobby = data.hobby;
    projectContactForm.characterTrait = data.characterTrait;
    projectContactForm.isSmoke = String(data.isSmoke || '0');
    projectContactForm.isDrink = String(data.isDrink || '0');
    projectContactForm.homeAddressDetail = data.homeAddressDetail;
    
    // 区域级联处理 (由于办公地址数据库存的是代码 String，而家庭住址存的是 ID Long，这里需要做特殊转换)
    const findIdByCode = (code) => {
        if (!code) return null;
        // 在扁平的原始列表中查找（由于 loadAreaOptions 是异步的，这里从 areaOptions 树中递归找或者从接口缓存中找更稳）
        // 简单处理：我们通过深度优先搜索在已有的树中查找
        const findInTree = (nodes, targetCode) => {
            for (const node of nodes) {
                if (String(node.areaCode) === String(targetCode)) return node.id;
                if (node.children) {
                    const found = findInTree(node.children, targetCode);
                    if (found) return found;
                }
            }
            return null;
        };
        return findInTree(areaOptions.value, code);
    };

    const officeArr = [];
    if (data.addressProvince) {
        // 如果是代码，转为 ID
        const pid = /^\d+$/.test(data.addressProvince) && data.addressProvince.length < 5 ? data.addressProvince : findIdByCode(data.addressProvince);
        if (pid) officeArr.push(Number(pid));
    }
    if (data.addressCity) {
        const cid = /^\d+$/.test(data.addressCity) && data.addressCity.length < 7 ? data.addressCity : findIdByCode(data.addressCity);
        if (cid) officeArr.push(Number(cid));
    }
    if (data.addressCounty) {
        const aid = /^\d+$/.test(data.addressCounty) && data.addressCounty.length < 9 ? data.addressCounty : findIdByCode(data.addressCounty);
        if (aid) officeArr.push(Number(aid));
    }
    projectContactForm.officeRegion = officeArr;
    
    const homeArr = [];
    if (data.homeProvinceId) homeArr.push(Number(data.homeProvinceId));
    if (data.homeCityId) homeArr.push(Number(data.homeCityId));
    if (data.homeAreaId) homeArr.push(Number(data.homeAreaId));
    projectContactForm.homeRegion = homeArr;

    // 4. 全部数据就绪后再打开抽屉
    projectContactDrawerOpen.value = true;
  }).finally(() => {
    proxy.$modal.closeLoading();
  });
};

const submitProjectContact = () => {
  projectContactFormRef.value.validate(async (valid) => {
    if (valid) {
      contactSubmitting.value = true;
      try {
        // 获取省市区名称
        const checkedNodes = officeRegionCascader.value?.getCheckedNodes();
        let provincialCityCounty = '';
        if (checkedNodes && checkedNodes.length > 0) {
          provincialCityCounty = checkedNodes[0].pathLabels.join("");
        }

        // 获取选中的 AreaCode 列表 (用于办公地址)
        const findCodeById = (id) => {
            const findInTree = (nodes, targetId) => {
                for (const node of nodes) {
                    if (Number(node.id) === Number(targetId)) return node.areaCode;
                    if (node.children) {
                        const found = findInTree(node.children, targetId);
                        if (found) return found;
                    }
                }
                return null;
            };
            return findInTree(areaOptions.value, id);
        };

        const payload = {
          ...projectContactForm,
          roleId: projectContactForm.type === '1' ? 1 : 2,
          // 优先使用异步查询到的 ID，其次使用主表 ID，最后使用表单内的 ID
          customerId: form.value.realCustomerId || form.value.customerId || projectContactForm.customerId,
          platformCode: form.value.projectNo || '',
          customerName: form.value.customerName || '',
          customerNo: form.value.customerNo || '',
          projectNo: form.value.projectNo || '',
          // age 字段转换
          age: projectContactForm.age ? parseInt(projectContactForm.age, 10) : null,
          // 办公地址存储为代码 (String)
          addressProvince: projectContactForm.officeRegion?.[0] ? findCodeById(projectContactForm.officeRegion[0]) : null,
          addressCity: projectContactForm.officeRegion?.[1] ? findCodeById(projectContactForm.officeRegion[1]) : null,
          addressCounty: projectContactForm.officeRegion?.[2] ? findCodeById(projectContactForm.officeRegion[2]) : null,
          provincialCityCounty: provincialCityCounty,
          // 家庭地址存储为 ID (Long)
          homeProvinceId: projectContactForm.homeRegion?.[0] || null,
          homeCityId: projectContactForm.homeRegion?.[1] || null,
          homeAreaId: projectContactForm.homeRegion?.[2] || null,
        };
        if (projectContactForm.id) {
          await updateContact(payload);
        } else {
          await addContact(payload);
        }
        proxy.$modal.msgSuccess("保存成功");
        projectContactDrawerOpen.value = false;
        loadProjectContacts();
      } catch (e) {
        // 显示真实错误，避免静默失败
        proxy.$modal.msgError(e?.message || "保存失败，请检查控制台");
        console.error("保存联系人失败:", e);
      } finally {
        contactSubmitting.value = false;
      }
    }
  });
};

const handleDeleteContact = (row) => {
  proxy.$modal.confirm('确认要删除该联系人吗？').then(() => {
    return delContact(row.id);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    loadProjectContacts();
  });
};

const handleDownloadFile = (row) => {
  if (row.ossId) {
    proxy.$download.oss(row.ossId);
  } else if (row.url) {
    window.open(row.url, '_blank');
  } else {
    proxy.$modal.msgError("下载地址不存在");
  }
};

const handleDeleteFile = (row) => {
  proxy.$modal.confirm(`确认删除附件「${row.name}」吗？`).then(async () => {
    const currentFileNos = form.value.fileNo ? form.value.fileNo.split(',') : [];
    const newFileNo = currentFileNos.filter(id => String(id) !== String(row.ossId)).join(',');
    
    try {
      proxy.$modal.loading("正在删除...");
      await updateLeads({ id: form.value.id, fileNo: newFileNo });
      form.value.fileNo = newFileNo;
      loadOssFiles();
      proxy.$modal.msgSuccess("删除成功");
    } finally {
      proxy.$modal.closeLoading();
    }
  });
};

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

defineExpose({ open });
</script>

<style scoped lang="scss">
.detail-wrapper { height: 100%; display: flex; flex-direction: column; background: #f5f7fa; }
.detail-header { 
  height: 40px; 
  padding: 0 16px; 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
  background: #fff; 
  border-bottom: 1px solid #e4e7ed; 
  .main-title { font-size: 16px; font-weight: normal; color: #303133; line-height: 40px; } 
  .close-btn { cursor: pointer; font-size: 18px; color: #909399; line-height: 40px; &:hover { color: #409eff; } } 
}
.detail-main { flex: 1; display: flex; overflow: hidden; }
.detail-left { flex: 1; display: flex; flex-direction: column; background: #fff; overflow: hidden; }
.detail-right { 
  width: 450px; 
  background: #fff; 
  display: flex; 
  flex-direction: column; 
  border-left: 1px solid #e4e7ed; 
  
  :deep(.activity-container) {
    .el-tabs__header {
      margin-top: 0;
      margin-bottom: 0;
      height: 48px;
      .el-tabs__nav-wrap {
        height: 100%;
        display: flex;
        align-items: center;
      }
    }
  }
}

.left-tabs { 
  display: flex; 
  padding: 0; // 移除容器边距
  border-bottom: 1px solid #f0f0f0; 
  height: 48px; 
  box-sizing: border-box;
  background: #fff;
  .left-tab-item { 
    padding: 0 15px; 
    height: 48px;
    line-height: 48px;
    cursor: pointer; 
    font-size: 14px; 
    color: #333;
    position: relative; 
    transition: all 0.3s; 
    &.active { 
      color: #409eff; 
      font-weight: normal; 
      &::after { 
        content: ""; 
        position: absolute; 
        bottom: 0; 
        left: 15px; 
        right: 15px; 
        height: 3px; 
        background: #409eff; 
        border-radius: 2px;
      } 
    } 
  } 
}
.tab-content, .el-dialog { 
  flex: 1; 
  padding: 15px 20px; 
  overflow-y: auto; 
  :deep(.el-table__header th) {
    font-weight: normal !important;
    background-color: #f8f9fb;
    color: #606266;
  }
  :deep(.el-table__cell) {
    font-weight: normal !important;
  }
  :deep(.el-button) {
    font-weight: normal;
  }
}

.info-section { 
  margin-bottom: 25px; 
  .section-header { 
    display: flex; 
    justify-content: space-between; 
    align-items: center; 
    margin-bottom: 15px; 
    padding-bottom: 8px; 
    border-bottom: 1px solid #f2f6fc; 
    .section-label { 
      font-size: 14px; 
      font-weight: normal; 
      color: #409eff;
      padding-left: 0; 
    } 
  } 
}
.info-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0 24px; margin-bottom: 4px; }
.info-item, .info-row-item { 
  display: flex;
  font-size: 13px; 
  line-height: 2; 
  margin-bottom: 8px; 
  .info-label { 
    color: #8c8c8c; 
    width: 90px; 
    flex-shrink: 0; 
  } 
  .info-value { 
    color: #262626; 
    flex: 1;
    word-break: break-all;
  } 
}
.info-row-item { margin-top: 4px; }

.contact-section { .contact-header { margin-bottom: 12px; text-align: right; } }
.analysis-form { 
  .analysis-row { 
    display: flex; 
    align-items: center; 
    margin-bottom: 12px; 
    .form-label { font-size: 14px; font-weight: normal; width: 80px; } 
  } 
  .summary-textarea-wrap { 
    margin-bottom: 15px; 
    :deep(.el-textarea__inner) {
      background-color: #fff;
      &:focus {
        background-color: #fff;
      }
    }
  } 
}

.form-section {
  margin-bottom: 25px;
  .form-section-title {
    font-size: 14px;
    color: #409eff;
    background: #f8f9fb;
    padding: 8px 15px;
    margin-bottom: 20px;
    border-radius: 4px;
    font-weight: normal;
  }
}

.contact-detail-preview {
  padding: 0 10px;
  .preview-title {
    font-size: 14px;
    font-weight: normal;
    color: #409eff;
    margin-bottom: 12px;
    padding-left: 8px;
    border-left: 3px solid #409eff;
  }
}

.form-section-group {
  margin-bottom: 20px;
  .section-group-title {
    padding: 8px 15px;
    background-color: #f8fbff;
    color: #409eff;
    font-size: 14px;
    margin-bottom: 15px;
  }
  .section-group-content { padding: 0 15px; }
}

.no-bold-label {
  :deep(.el-form-item__label) { font-weight: normal !important; color: #666; }
  :deep(.el-form-item) { margin-bottom: 18px !important; }
}

.drawer-body-custom {
  &::-webkit-scrollbar {
    display: none;
  }
  -ms-overflow-style: none;
  scrollbar-width: none;
}
:deep(.el-descriptions__label) {
  width: 100px;
  background-color: #f8f9fb !important;
  font-weight: normal !important;
}
:deep(.el-descriptions__content) {
  font-weight: normal !important;
}
:deep(*) {
  font-weight: normal !important;
}

.edit-contact-drawer {
  :deep(.el-drawer__body) {
    &::-webkit-scrollbar {
      display: none;
    }
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
}
</style>
