<template>
    <el-drawer
      v-model="visible"
      size="90%"
      :with-header="false"
      direction="rtl"
      @close="handleBack"
      destroy-on-close
      class="detail-drawer"
    >
      <div class="detail-wrapper" v-loading="loading" element-loading-text="数据加载中...">
        <!-- 顶部标题栏 -->
        <div class="detail-header">
          <div class="header-left">
            <span class="customer-title">{{ customerData?.customerName }}</span>
            <span class="customer-type-text" v-if="customerData?.customerCategoryName">类型：{{ customerData.customerCategoryName }}</span>
          </div>
          <div class="header-right">
            <el-icon class="close-icon" @click="handleBack"><Close /></el-icon>
          </div>
        </div>

        <div class="detail-body">
          <!-- 左侧主要内容区 -->
          <div class="main-content">
            <div class="content-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="tab-pane-container">
              <div v-show="activeMainTab === 'profile'" class="profile-pane">
                <div v-if="!isReadOnly" class="pane-header">
                  <el-button type="primary" icon="Edit" @click="handleEdit" class="edit-btn">编辑</el-button>
                </div>


                <div class="detail-section">
                  <div class="section-title">基本信息</div>
                  <div class="field-grid">

                    <div class="field-item">
                      <span class="field-label">所属公司</span>
                      <span class="field-value">{{ customerData?.companyName || customerData?.customerBusinessVo?.companyName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">客户来源</span>
                      <span class="field-value">{{ customerData?.customerSourceName || customerData?.customerBusinessVo?.customerSourceName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">企业类型</span>
                      <span class="field-value">{{ customerData?.enterpriseTypeName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">客户等级</span>
                      <span class="field-value">{{ customerData?.customerLevelName || customerData?.customerBusinessVo?.customerLevelName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">企业规模</span>
                      <span class="field-value">{{ customerData?.enterpriseScale || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">企业邮箱</span>
                      <span class="field-value">{{ customerData?.email || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">办公电话</span>
                      <span class="field-value">{{ customerData?.landline || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">行业</span>
                      <span class="field-value">{{ customerData?.industryName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">国家</span>
                      <span class="field-value">{{ customerData?.countryName || '中国' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">省份</span>
                      <span class="field-value">{{ provinceDisplay }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">城市</span>
                      <span class="field-value">{{ cityDisplay }}</span>
                    </div>
                    <div class="field-item full-width">
                      <span class="field-label">办公地址</span>
                      <span class="field-value">{{ customerData?.address || customerData?.customerBusinessVo?.address || '' }}</span>
                    </div>
                  </div>
                </div>

                <div class="detail-section">
                  <div class="section-title">工商信息</div>
                  <div class="field-grid">
                    <div class="field-item full-width">
                      <span class="field-label">工商名称</span>
                      <span class="field-value">{{ customerData?.businessCustomerName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">社会信用代码</span>
                      <span class="field-value">{{ customerData?.socialCreditCode || customerData?.customerBusinessInfoVo?.socialCreditCode || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">法定代表人</span>
                      <span class="field-value">{{ customerData?.customerBusinessInfoVo?.legalPersonName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">注册资本</span>
                      <span class="field-value">{{ customerData?.customerBusinessInfoVo?.registeredCapital || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">成立日期</span>
                      <span class="field-value">{{ customerData?.customerBusinessInfoVo?.establishmentDate || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">吊销日期</span>
                      <span class="field-value">{{ customerData?.customerBusinessInfoVo?.revocationDate || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">登记状态</span>
                      <span class="field-value">{{ customerData?.customerBusinessInfoVo?.registrationStatus || '' }}</span>
                    </div>
                    <div class="field-item full-width">
                      <span class="field-label">注册地址</span>
                      <span class="field-value">{{ customerData?.customerBusinessInfoVo?.businessAddress || customerData?.address || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">营业执照</span>
                      <div class="image-preview" v-if="businessLicenseUrl">
                        <el-image :src="businessLicenseUrl" :preview-src-list="[businessLicenseUrl]" fit="cover" />
                      </div>
                      <span class="field-value" v-else></span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">正面身份证</span>
                      <div class="image-preview" v-if="idCardFrontUrl">
                        <el-image :src="idCardFrontUrl" :preview-src-list="[idCardFrontUrl]" fit="cover" />
                      </div>
                      <span class="field-value" v-else></span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">反面身份证</span>
                      <div class="image-preview" v-if="idCardBackUrl">
                        <el-image :src="idCardBackUrl" :preview-src-list="[idCardBackUrl]" fit="cover" />
                      </div>
                      <span class="field-value" v-else></span>
                    </div>
                  </div>
                </div>

                <div class="detail-section">
                  <div class="section-title">销售信息</div>
                  <div class="field-grid">
                    <div class="field-item">
                      <span class="field-label">合作状况</span>
                      <span class="field-value">{{ customerData?.cooperationName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">开票类型</span>
                      <span class="field-value">{{ customerData?.sellInvoiceType || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">归属部门</span>
                      <span class="field-value">{{ customerData?.belongingDepartmentName || customerData?.deptName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">采购规模(万)</span>
                      <span class="field-value">{{ customerData?.customerSalesInfoVo?.procurementScale || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">销售目标(万)</span>
                      <span class="field-value">{{ customerData?.customerSalesInfoVo?.salesTarget || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">采购方式</span>
                      <span class="field-value">{{ customerData?.procurementMethod || customerData?.customerSalesInfoVo?.purchaseWayName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">信用等级</span>
                      <span class="field-value">{{ customerData?.customerSalesInfoVo?.creditLevel || customerData?.customerLevelName || '' }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">授信额度</span>
                      <span class="field-value">{{ formatMoney(customerData?.customerSalesInfoVo?.creditAmount) }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">应收账款</span>
                      <span class="field-value">{{ formatMoney(customerData?.customerSalesInfoVo?.accountsReceivable) }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">预收账款</span>
                      <span class="field-value">{{ formatMoney(customerData?.customerSalesInfoVo?.prepaidAmount || customerData?.deptCredit) }}</span>
                    </div>
                    <div class="field-item">
                      <span class="field-label">剩余额度</span>
                      <span class="field-value">{{ formatMoney(customerData?.customerSalesInfoVo?.remainingQuota) }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <div v-show="activeMainTab === 'contacts'" class="contacts-pane">
                <div v-if="!isReadOnly" class="pane-header">
                  <el-button type="primary" icon="Plus" class="add-btn" @click="handleAddContact">新增</el-button>
                </div>
                <el-table :data="customerData?.customerContactVoList || []" border class="custom-tab-table">
                  <el-table-column label="联系人姓名" align="center" prop="contactName" />
                  <el-table-column label="部门" align="center" prop="deptName" />
                  <el-table-column label="职位" align="center" prop="roleName" />
                  <el-table-column label="手机号码" align="center" prop="phone" />
                  <el-table-column label="办公座机" align="center" prop="officePhone" />
                  <el-table-column label="操作" align="center" width="120">
                    <template #default="scope">
                      <el-button v-if="!isReadOnly" link type="primary" @click="handleEditContact(scope.row)">编辑</el-button>
                      <el-button v-if="!isReadOnly" link type="danger" @click="handleDeleteContact(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                  <template #empty>暂无数据</template>
                </el-table>
              </div>

              <div v-show="activeMainTab === 'opportunity'" class="opportunity-pane">
                <el-table :data="opportunityList" border class="custom-tab-table">
                  <el-table-column label="登记日期" align="center" prop="createTime" width="150">
                    <template #default="scope">
                      {{ scope.row.createTime ? scope.row.createTime.substring(0, 10) : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="项目商机名称" align="center" prop="projectName" show-overflow-tooltip />
                  <el-table-column label="项目类型" align="center" width="120">
                    <template #default="scope">
                      {{ translateDict(scope.row.projectType, dictOptions.projectType) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="项目预算(万)" align="center" width="120">
                    <template #default="scope">{{ formatMoney(scope.row.projectBudget) }}</template>
                  </el-table-column>
                  <el-table-column label="最终成交金额" align="center" width="120">
                    <template #default="scope">{{ formatMoney(scope.row.dealAmount) }}</template>
                  </el-table-column>
                  <el-table-column label="成交结果" align="center" width="100">
                    <template #default="scope">
                      {{ scope.row.dealResult || scope.row.result || '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="100">
                    <template #default="scope">
                      <el-button link type="primary" @click="handleOpportunityDetail(scope.row)">详情</el-button>
                    </template>
                  </el-table-column>
                  <template #empty>暂无数据</template>
                </el-table>
              </div>

              <div v-show="activeMainTab === 'annual'" class="annual-pane">
                <el-table :data="annualList" border class="custom-tab-table">
                  <el-table-column label="登记日期" align="center" prop="createTime" width="150">
                    <template #default="scope">
                      {{ scope.row.createTime ? scope.row.createTime.substring(0, 10) : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="年度入围名称" align="center" prop="projectName" show-overflow-tooltip />
                  <el-table-column label="项目等级" align="center" width="100">
                    <template #default="scope">
                      {{ translateDict(scope.row.projectLevel, dictOptions.annualLevel) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="金额(万)" align="center" width="100">
                    <template #default="scope">{{ formatMoney(scope.row.amount) }}</template>
                  </el-table-column>
                  <el-table-column label="标期(年)" align="center" prop="standardPeriod" width="100" />
                  <el-table-column label="投标截止时间" align="center" prop="tenderDeadline" width="150">
                    <template #default="scope">
                      {{ scope.row.tenderDeadline ? scope.row.tenderDeadline.substring(0, 10) : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="成交结果" align="center" width="100">
                    <template #default="scope">
                      {{ scope.row.result || scope.row.dealResult || '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="100">
                    <template #default="scope">
                      <el-button link type="primary" @click="handleAnnualDetail(scope.row)">详情</el-button>
                    </template>
                  </el-table-column>
                  <template #empty>暂无数据</template>
                </el-table>
              </div>

              <div v-show="activeMainTab === 'care'" class="care-pane">
                <div v-if="!isReadOnly" class="pane-header">
                  <el-button type="primary" icon="Plus" class="add-btn" @click="handleAddCare">新增</el-button>
                </div>
                <el-table :data="careList" border class="custom-tab-table">
                  <el-table-column label="单据编号" align="center" prop="receiptId" width="150" />
                  <el-table-column label="登记日期" align="center" prop="createTime" width="150">
                    <template #default="scope">
                      {{ scope.row.createTime ? scope.row.createTime.substring(0, 10) : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="联系人" align="center" prop="contactPerson" />
                  <el-table-column label="关怀类型" align="center" prop="concernType">
                    <template #default="scope">
                      {{ translateDict(scope.row.concernType, careTypeOptions) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="金额" align="center">
                    <template #default="scope">{{ formatMoney(scope.row.amount) }}</template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="100">
                    <template #default="scope">
                      <el-button link type="primary" @click="handleCareDetail(scope.row)">详情</el-button>
                    </template>
                  </el-table-column>
                  <template #empty>暂无数据</template>
                </el-table>
              </div>

              <div v-show="activeMainTab === 'attachment'" class="attachment-pane">
                <div v-if="!isReadOnly" class="pane-header">
                  <el-upload
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :on-success="handleUploadSuccess"
                    :show-file-list="false"
                    multiple
                  >
                    <el-button type="primary" icon="Upload" class="add-btn">上传附件</el-button>
                  </el-upload>
                </div>
                <el-table :data="fileList" border class="custom-tab-table">
                  <el-table-column label="文件名称" align="center" prop="name" show-overflow-tooltip />
                  <el-table-column label="文件类型" align="center" prop="type" width="120" />
                  <el-table-column label="上传时间" align="center" prop="createTime" width="180" />
                  <el-table-column label="操作" align="center" width="120">
                    <template #default="scope">
                      <el-button link type="primary" @click="handleDownload(scope.row)">下载</el-button>
                      <el-button v-if="!isReadOnly" link type="danger" @click="handleDeleteFile(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                  <template #empty>暂无数据</template>
                </el-table>
              </div>
            </div>
          </div>

          <!-- 右侧侧边栏 (通用业务活动组件) -->
          <div class="sidebar-content">
            <BusinessActivity 
              v-if="customerData"
              :business-id="customerData.id" 
              business-type="customer"
              :info-data="{
                ...customerData,
                customerName: customerData.customerName,
                customerNo: customerData.customerNo || customerData.customNo || '',
                deptName: customerData.belongingDepartmentName || customerData.deptName || '',
                department: customerData.belongingDepartmentName || customerData.deptName || '',
                industryName: customerData.industryName || '',
                profession: customerData.industryName || '',
                /* 业务员：优先取销售信息中的 salesPersonName 或 salesPerson，兼容多种字段名 */
                leaderName: customerData.customerSalesInfoVo?.salesPersonName || customerData.customerSalesInfoVo?.salesPerson || customerData.salesPersonName || customerData.leaderName || customerData.staffName || customerData.salesman || '',
                staffName: customerData.customerSalesInfoVo?.salesPersonName || customerData.customerSalesInfoVo?.salesPerson || customerData.salesPersonName || customerData.leaderName || customerData.staffName || customerData.salesman || ''
              }"
              @update-readonly="val => isReadOnly = val"
            />
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 客户编辑抽屉 -->
    <customer-edit ref="editRef" @success="loadData(customerData.id)" />

    <!-- 项目商机详情抽屉 -->
    <opportunity-detail 
      v-model="oppDetailVisible" 
      :id="currentOppId"
      :sale-status-options="dictOptions.opportunityLevel"
      :project-level-options="dictOptions.opportunityLevel"
    />

    <!-- 年度入围（平台优选）详情抽屉 -->
    <platform-detail 
      v-model="annualDetailVisible" 
      :id="currentAnnualId"
      :options="{
        level: dictOptions.annualLevel,
        type: dictOptions.projectType,
        status: dictOptions.annualLevel
      }"
    />

    <!-- 联系人编辑抽屉 -->
    <el-drawer
      v-model="contactVisible"
      size="70%"
      direction="rtl"
      destroy-on-close
      :with-header="false"
      class="contact-edit-drawer"
    >
      <div class="drawer-header-compact" style="height: 40px; padding: 0 16px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; background: #fff;">
        <span style="font-size: 15px; font-weight: 600; color: #333;">{{ contactForm.id ? '编辑客户联系人' : '新建客户联系人' }}</span>
        <el-icon @click="contactVisible = false" style="cursor: pointer; font-size: 18px; color: #94a3b8;"><Close /></el-icon>
      </div>

      <div class="drawer-body-custom" v-loading="contactLoading" style="padding: 24px; overflow-y: auto; height: calc(100% - 120px);">
        <el-form :model="contactForm" :rules="contactRules" ref="contactFormRef" label-width="100px" label-position="right" class="no-bold-label">
          <div class="form-title-blue">基本信息</div>
          <div class="form-section-custom">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="姓名" prop="contactName">
                  <el-input v-model="contactForm.contactName" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系人类型" prop="roleId">
                  <el-radio-group v-model="contactForm.roleId">
                    <el-radio value="1">公司职员</el-radio>
                    <el-radio value="2">关系资源人</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="contactForm.gender">
                    <el-radio value="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="contactForm.age" type="number" placeholder="请输入年龄" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="籍贯" prop="nativePlace">
                  <el-input v-model="contactForm.nativePlace" placeholder="请输入籍贯" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="生日" prop="birthday">
                  <el-date-picker v-model="contactForm.birthday" type="date" placeholder="选择日期" style="width: 100%" value-format="YYYY-MM-DD" />
                </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="form-title-blue">办公信息</div>
          <div class="form-section-custom">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="在职状态" prop="status">
                  <el-radio-group v-model="contactForm.status">
                    <el-radio value="0">在职</el-radio>
                    <el-radio value="1">离职</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="contactForm.phone" placeholder="请输入手机号码" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="部门" 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 :gutter="20">
              <el-col :span="24">
                <el-form-item label="办公地址" prop="officeAreaArray">
                   <div style="display: flex; gap: 10px; width: 100%;">
                      <el-cascader
                        v-model="contactForm.officeAreaArray"
                        :options="areaOptions"
                        :props="{ label: 'areaName', value: 'id', children: 'children' }"
                        placeholder="请选择"
                        style="width: 250px"
                        clearable
                      />
                      <el-input v-model="contactForm.addressDetail" placeholder="请输入详细地址" style="flex: 1" />
                   </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="工作内容" prop="jobContent">
                  <el-input v-model="contactForm.jobContent" type="textarea" :rows="3" placeholder="请输入工作内容" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="form-title-blue">家庭信息</div>
          <div class="form-section-custom">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="家庭住址" prop="homeAreaArray">
                   <div style="display: flex; gap: 10px; width: 100%;">
                      <el-cascader
                        v-model="contactForm.homeAreaArray"
                        :options="areaOptions"
                        :props="{ label: 'areaName', value: 'id', children: 'children' }"
                        placeholder="请选择"
                        style="width: 250px"
                        clearable
                      />
                      <el-input v-model="contactForm.homeAddressDetail" placeholder="请输入详细地址" style="flex: 1" />
                   </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="家庭情况" prop="familyStatus">
                  <el-input v-model="contactForm.familyStatus" placeholder="请输入家庭情况" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="爱好" prop="hobby">
                  <el-input v-model="contactForm.hobby" placeholder="请输入爱好" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性格特征" prop="characterDesc">
                  <el-input v-model="contactForm.characterDesc" placeholder="请输入性格特征" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="是否抽烟" prop="isSmoke">
                  <el-radio-group v-model="contactForm.isSmoke">
                    <el-radio value="1">是</el-radio>
                    <el-radio value="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否喝酒" prop="isDrink">
                  <el-radio-group v-model="contactForm.isDrink">
                    <el-radio value="1">是</el-radio>
                    <el-radio value="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>

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

    <!-- 新建客户关怀弹窗 (Dialog) -->
    <el-dialog
      v-model="careVisible"
      title="新建客户关怀"
      width="700px"
      append-to-body
      destroy-on-close
    >
      <div class="care-dialog-body">
        <el-form ref="careRef" :model="careForm" :rules="careRules" label-width="100px">
          <!-- 只读展示区 -->
          <div class="info-section-static">
            <el-row>
              <el-col :span="24">
                <el-form-item label="客户名称：">
                  <span class="static-text">{{ customerData?.customerName }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="行业：">
                  <span class="static-text">{{ translateDict(customerData?.industryCategory, dictOptions.projectType) || customerData?.industryCategory || '' }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门：">
                  <span class="static-text">{{ customerData?.customerSalesInfoVo?.belongingDepartment || '' }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="业务员：">
                  <span class="static-text">{{ customerData?.customerSalesInfoVo?.salesPerson || '' }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人" prop="contactPerson">
                  <el-select v-model="careForm.contactPerson" placeholder="请选择" style="width: 100%" filterable @change="handleCareContactChange">
                    <el-option v-for="item in careContactOptions" :key="item.id" :label="item.contactName" :value="item.contactName" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 输入区 -->
          <div class="form-section-input">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="手机" prop="phone">
                  <el-input v-model="careForm.phone" placeholder="请输入手机" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="固定电话" prop="telephone">
                  <el-input v-model="careForm.telephone" placeholder="请输入固定电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="关怀类型" prop="concernType">
                  <el-select v-model="careForm.concernType" placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in careTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="金额" prop="amount">
                  <el-input v-model="careForm.amount" placeholder="请输入金额" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="需求时间" prop="requirementDate">
                  <el-date-picker v-model="careForm.requirementDate" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="附件">
                   <el-upload action="#" :auto-upload="false" multiple :file-list="careFileList">
                    <el-button type="primary" :icon="Upload">上传</el-button>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="礼品描述" prop="giftDesc">
                  <el-input v-model="careForm.giftDesc" type="textarea" :rows="3" placeholder="请输入内容" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="关怀理由" prop="concernArgument">
                  <el-input v-model="careForm.concernArgument" type="textarea" :rows="3" placeholder="请输入内容" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="careVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCareForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 客户关怀详情 -->
    <care-detail ref="careDetailRef" />
</template>

<script setup name="CustomerValidDetail">
import { ref, reactive, computed, onMounted, getCurrentInstance, toRefs } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Close, Edit, Plus, Search, UserFilled, Upload } from '@element-plus/icons-vue';
import { getCustomerInfo } from "@/api/customer/customerPool";
import { listTeamMember } from "@/api/customer/teamMember";
import { listOpportunity } from "@/api/saleManage/opportunity";
import { listProjectSelection } from "@/api/saleManage/projectSelection";
import { listCare, addCare } from "@/api/customer/crmCare";
import { listContact } from "@/api/customer/crmContact";
import { listFileInfo, delFileInfo, addFileInfo } from "@/api/file/info/index";
import { listByIds } from "@/api/system/oss";
import { getContactPerson, addContactPerson, updateContactPerson, delContactPerson } from "@/api/customer/contactPerson";
import { listProvinceWithCities } from "@/api/customer/addressArea";
import { getToken } from "@/utils/auth";
import { globalHeaders } from "@/utils/request";
import { useUserStore } from "@/store/modules/user";
import BusinessActivity from '../../common/businessActivity.vue';
import CustomerEdit from "./edit.vue";
import CareDetail from "../care/detail.vue";
import OpportunityDetail from "../../saleManage/opportunity/detail.vue";
import PlatformDetail from "../../saleManage/platformSelection/detail.vue";

const proxy = getCurrentInstance().proxy;
const { 
  care_type: careTypeOptions, 
  opportunity_level: opportunityLevelOptions, 
  annual_level: annualLevelOptions, 
  project_type: projectTypeOptions 
} = toRefs(reactive(proxy.useDict("care_type", "opportunity_level", "annual_level", "project_type")));
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const emit = defineEmits(['success']);

const loading = ref(false);
const visible = ref(false);
const customerData = ref(null);
const businessLicenseUrl = ref('');
const idCardFrontUrl = ref('');
const idCardBackUrl = ref('');
const teamMembers = ref([]);
const opportunityList = ref([]);
const annualList = ref([]);
const careList = ref([]);
const fileList = ref([]);
const activeMainTab = ref('profile');
const editRef = ref(null);
const careDetailRef = ref(null);

// 详情控制
const oppDetailVisible = ref(false);
const currentOppId = ref(null);
const annualDetailVisible = ref(false);
const currentAnnualId = ref(null);
const dictOptions = reactive({
  opportunityLevel: opportunityLevelOptions,
  annualLevel: annualLevelOptions,
  projectType: projectTypeOptions
});

// 客户联系人相关状态
const contactVisible = ref(false);
const contactLoading = ref(false);
const contactSubmitting = ref(false);
const areaOptions = ref([]);
const contactForm = reactive({
  id: undefined,
  customerId: undefined,
  contactName: '',
  roleId: '1',
  gender: '0',
  age: '',
  nativePlace: '',
  birthday: '',
  remark: '',
  status: '0',
  phone: '',
  deptName: '',
  roleName: '',
  officePhone: '',
  officeAreaArray: [],
  addressDetail: '',
  jobContent: '',
  homeAreaArray: [],
  homeAddressDetail: '',
  familyStatus: '',
  hobby: '',
  characterDesc: '',
  isSmoke: '0',
  isDrink: '0'
});

// 客户关怀新增相关状态
const careVisible = ref(false);
const careFileList = ref([]);
const careContactOptions = ref([]);
const careForm = reactive({
  customerId: undefined,
  customerName: '',
  profession: '',
  department: '',
  salesman: '',
  contactPerson: '',
  phone: '',
  telephone: '',
  concernType: '',
  amount: undefined,
  requirementDate: undefined,
  giftDesc: '',
  concernArgument: '',
  platformCode: 'crm',
  auditStatus: 0
});

const careRules = {
  contactPerson: [{ required: true, message: '请选择联系人', trigger: 'change' }],
  phone: [{ required: true, message: '请输入手机', trigger: 'blur' }],
  telephone: [{ required: true, message: '请输入固定电话', trigger: 'blur' }],
  concernType: [{ required: true, message: '请选择关怀类型', trigger: 'change' }],
  giftDesc: [{ required: true, message: '请输入礼品描述', trigger: 'blur' }],
  concernArgument: [{ required: true, message: '请输入关怀理由', trigger: 'blur' }]
};

const contactRules = reactive({
  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 uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload');
const uploadHeaders = ref(globalHeaders());

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

const provinceDisplay = computed(() => {
  if (customerData.value?.provinceName) return customerData.value.provinceName;
  if (customerData.value?.provincialCityCounty) {
    return customerData.value.provincialCityCounty.split('/')[0] || '';
  }
  return '';
});

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

const isReadOnly = ref(true);

const loadData = async (id) => {
  if (!id) return;
  loading.value = true;
  
  try {
    const res = await getCustomerInfo(id);
    customerData.value = res.data;
    // 加载所有相关数据
    refreshFileList();
    refreshOssUrls();
    refreshOpportunities();
    refreshAnnualList();
    refreshCareList();
  } catch (err) {
    proxy.$modal.msgError("获取客户详情失败");
  } finally {
    loading.value = false;
  }
};

const refreshOssUrls = () => {
  businessLicenseUrl.value = '';
  idCardFrontUrl.value = '';
  idCardBackUrl.value = '';

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

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

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

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

const refreshContacts = () => {
  if (!customerData.value?.id) return;
  loadData(customerData.value.id); // 主接口里包含了联系人列表
};

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

const refreshAnnualList = () => {
  const cNo = customerData.value?.customerNo || customerData.value?.customNo;
  if (!cNo) return;
  listProjectSelection({ customNo: cNo }).then(res => {
    annualList.value = res.rows || res.data || [];
  });
};

const refreshCareList = () => {
  if (!customerData.value?.customerName) return;
  listCare({ customerName: customerData.value.customerName }).then(res => {
    careList.value = res.rows || res.data || [];
  });
};

const refreshFileList = () => {
  if (!customerData.value?.customerNo) return;
  // 使用业务编号和业务类型过滤
  listFileInfo({ 
    objectNo: customerData.value.customerNo,
    dataType: 12 // 客户类型
  }).then(res => {
    fileList.value = res.rows || res.data || [];
  });
};

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    const file = res.data;
    // 保存文件关联信息
    const fileInfo = {
      name: file.originalName || file.fileName,
      originalName: file.originalName || file.fileName,
      path: file.url,
      url: file.url,
      size: file.size,
      type: (file.originalName || file.fileName || '').split('.').pop()?.toLowerCase(),
      extension: (file.originalName || file.fileName || '').split('.').pop()?.toLowerCase(),
      objectNo: customerData.value.customerNo,
      dataType: 12,
      uploadStatus: 1,
      isPublic: 1
    };
    
    addFileInfo(fileInfo).then(() => {
      proxy.$modal.msgSuccess("上传成功");
      refreshFileList();
    });
  } else {
    proxy.$modal.msgError(res.msg || "上传失败");
  }
};

const handleDownload = (row) => {
  const url = row.url || row.path;
  if (!url) return;
  window.open(url, '_blank');
};

const handleDeleteFile = (row) => {
  proxy.$modal.confirm(`确认删除附件"${row.name || row.fileName}"吗？`).then(() => {
    delFileInfo(row.id).then(() => {
      proxy.$modal.msgSuccess("删除成功");
      refreshFileList();
    });
  });
};

// 客户联系人方法
const handleAddContact = () => {
  resetContactForm();
  contactForm.customerId = customerData.value.id;
  contactForm.customerName = customerData.value.customerName || '';
  contactVisible.value = true;
};

const handleEditContact = (row) => {
  resetContactForm();
  contactVisible.value = true;
  contactLoading.value = true;
  getContactPerson(row.id).then(res => {
    Object.assign(contactForm, res.data);
    // 转换类型
    if (contactForm.roleId) contactForm.roleId = String(contactForm.roleId);
    if (contactForm.gender) contactForm.gender = String(contactForm.gender);
    if (contactForm.status) contactForm.status = String(contactForm.status);
    if (contactForm.isSmoke) contactForm.isSmoke = String(contactForm.isSmoke);
    if (contactForm.isDrink) contactForm.isDrink = String(contactForm.isDrink);
    // 区域反查逻辑 (适配代码转换)
    const findIdByCode = (code) => {
        if (!code) return null;
        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);
    };

    // 地区回显
    if (res.data.officeProvinceId || res.data.addressProvince) {
      const p = res.data.officeProvinceId || res.data.addressProvince;
      const c = res.data.officeCityId || res.data.addressCity;
      const a = res.data.officeAreaId || res.data.addressCounty;
      
      const officeArr = [];
      if (p) {
          const pid = /^\d+$/.test(p) && String(p).length < 5 ? p : findIdByCode(p);
          if (pid) officeArr.push(String(pid));
      }
      if (c) {
          const cid = /^\d+$/.test(c) && String(c).length < 7 ? c : findIdByCode(c);
          if (cid) officeArr.push(String(cid));
      }
      if (a) {
          const aid = /^\d+$/.test(a) && String(a).length < 9 ? a : findIdByCode(a);
          if (aid) officeArr.push(String(aid));
      }
      contactForm.officeAreaArray = officeArr;
    }
    
    if (res.data.homeProvinceId) {
      contactForm.homeAreaArray = [String(res.data.homeProvinceId), String(res.data.homeCityId), String(res.data.homeAreaId)].filter(i => i && i !== 'null');
    }
    contactLoading.value = false;
  });
};

const submitContact = () => {
  proxy.$refs.contactFormRef.validate(valid => {
    if (valid) {
      contactSubmitting.value = true;
      // 处理地区
      if (contactForm.officeAreaArray?.length >= 1) {
        // 获取选中的 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);
        };

        contactForm.officeProvinceId = contactForm.officeAreaArray[0];
        contactForm.officeCityId = contactForm.officeAreaArray[1];
        contactForm.officeAreaId = contactForm.officeAreaArray[2] || null;
        
        // 兼容新字段 (代码形式)
        contactForm.addressProvince = findCodeById(contactForm.officeAreaArray[0]);
        contactForm.addressCity = findCodeById(contactForm.officeAreaArray[1]);
        contactForm.addressCounty = findCodeById(contactForm.officeAreaArray[2]);
      }
      if (contactForm.homeAreaArray?.length >= 1) {
        contactForm.homeProvinceId = contactForm.homeAreaArray[0];
        contactForm.homeCityId = contactForm.homeAreaArray[1];
        contactForm.homeAreaId = contactForm.homeAreaArray[2] || null;
      }

      const action = contactForm.id ? updateContactPerson : addContactPerson;
      action(contactForm).then(() => {
        proxy.$modal.msgSuccess(contactForm.id ? "修改成功" : "新增成功");
        contactVisible.value = false;
        refreshContacts();
      }).finally(() => {
        contactSubmitting.value = false;
      });
    }
  });
};

const handleDeleteContact = (row) => {
  proxy.$modal.confirm(`确认删除联系人"${row.contactName}"吗？`).then(() => {
    delContactPerson(row.id).then(() => {
      proxy.$modal.msgSuccess("删除成功");
      refreshContacts();
    });
  });
};

const resetContactForm = () => {
  Object.assign(contactForm, {
    id: undefined,
    customerId: undefined,
    contactName: '',
    roleId: '1',
    gender: '0',
    age: '',
    nativePlace: '',
    birthday: '',
    remark: '',
    status: '0',
    phone: '',
    deptName: '',
    roleName: '',
    officePhone: '',
    officeAreaArray: [],
    addressDetail: '',
    jobContent: '',
    homeAreaArray: [],
    homeAddressDetail: '',
    familyStatus: '',
    hobby: '',
    characterDesc: '',
    isSmoke: '0',
    isDrink: '0'
  });
};

const formatMoney = (val) => {
  if (val === undefined || val === null || val === '') return '';
  const num = parseFloat(val);
  return isNaN(num) ? val : num.toFixed(2);
};

const handleBack = () => { 
  visible.value = false;
  // 只有在路由模式（通过 URL 直接访问）下才执行跳转
  if (route.query.id) {
    setTimeout(() => {
      router.push('/customer/valid');
    }, 300);
  }
};

const handleEdit = () => { 
  editRef.value.open(customerData.value.id);
};



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

onMounted(() => {
  const id = route.query.id;
  if (id) {
    loadData(id);
  }
  listProvinceWithCities().then(res => {
    const list = res.rows || [];
    if (list.length > 0) {
      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 handleAddCare = () => {
  Object.assign(careForm, {
    customerId: customerData.value.id,
    customerName: customerData.value.customerName,
    profession: customerData.value.industryCategory,
    department: customerData.value.customerSalesInfoVo?.belongingDepartment,
    salesman: customerData.value.customerSalesInfoVo?.salesPerson,
    contactPerson: '',
    phone: '',
    telephone: '',
    concernType: '',
    amount: undefined,
    requirementDate: undefined,
    giftDesc: '',
    concernArgument: ''
  });
  
  // 获取系统中所有的联系人列表
  listContact({ 
    pageSize: 50 
  }).then(res => {
    careContactOptions.value = res.rows || res.data || [];
  });
  
  careVisible.value = true;
};

const handleCareContactChange = (val) => {
  const contact = (careContactOptions.value || []).find(item => item.contactName === val);
  if (contact) {
    careForm.phone = contact.phone;
    careForm.telephone = contact.officePhone;
  }
};

const submitCareForm = () => {
  proxy.$refs.careRef.validate(valid => {
    if (valid) {
      addCare(careForm).then(() => {
        proxy.$modal.msgSuccess("新增成功");
        careVisible.value = false;
        refreshCareList();
      });
    }
  });
};

/** 查看关怀详情 */
const handleCareDetail = (row) => {
  careDetailRef.value.open(row.id);
};

/** 查看项目商机详情 */
const handleOpportunityDetail = (row) => {
  currentOppId.value = row.id;
  oppDetailVisible.value = true;
};

/** 查看年度入围详情 */
const handleAnnualDetail = (row) => {
  currentAnnualId.value = row.id;
  annualDetailVisible.value = true;
};

/** 字典翻译 */
function translateDict(value, options) {
  if (!options || !value) return value;
  const item = options.find(o => String(o.value) === String(value));
  return item ? item.label : value;
}

defineExpose({ open });
</script>

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

.detail-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.detail-header {
  height: 64px;
  background: #fff;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e2e8f0;
  flex-shrink: 0;

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    .customer-title {
      font-size: 18px;
      font-weight: 600;
      color: #1e293b;
    }

    .customer-type-text {
      font-size: 12px;
      color: #64748b;
      background: #f1f5f9;
      padding: 2px 8px;
      border-radius: 4px;
    }
  }

  .header-right {
    .close-icon {
      font-size: 20px;
      color: #94a3b8;
      cursor: pointer;
      transition: color 0.2s;
      &:hover { color: #409eff; }
    }
  }
}

.detail-body {
  flex: 1;
  display: flex;
  overflow: hidden;
  padding: 0;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.content-tabs {
  display: flex;
  padding: 0 24px;
  border-bottom: 1px solid #f1f5f9;
  gap: 32px;
  flex-shrink: 0;
  height: 56px;
  align-items: center;

  .tab-item {
    height: 56px;
    line-height: 56px;
    font-size: 14px;
    color: #64748b;
    cursor: pointer;
    position: relative;
    transition: all 0.2s;

    &:hover { color: #409eff; }

    &.active {
      color: #409eff;
      font-weight: 600;
      &::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 0;
        right: 0;
        height: 2px;
        background: #409eff;
      }
    }
  }
}

.tab-pane-container {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}

.pane-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

.detail-section {
  margin-bottom: 32px;
  &:last-child { margin-bottom: 0; }

  .section-title {
    font-size: 15px;
    font-weight: 600;
    color: #409eff;
    margin-bottom: 16px;
  }
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px 16px;
  padding: 4px 12px;

  .field-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    line-height: 20px;

    &.full-width {
      grid-column: span 3;
    }

    .field-label {
      font-size: 13px;
      color: #64748b;
      width: 100px;
      flex-shrink: 0;
      &::after { content: '：'; }
    }

    .field-value {
      font-size: 13px;
      color: #1e293b;
      flex: 1;
      word-break: break-all;
    }
  }
}

.sidebar-content {
  width: 450px;
  overflow: hidden;
  border-left: 1px solid #f1f5f9;

  /* 强制统一右侧组件的标签栏高度与对齐 */
  :deep(.el-tabs__header) {
    margin: 0;
    height: 56px;
    border-bottom: 1px solid #f1f5f9;
    .el-tabs__nav-wrap {
      height: 56px;
      &::after { height: 0; } /* 移除原有的全宽底线，使用外层统一底线 */
    }
    .el-tabs__item {
      height: 56px;
      line-height: 56px;
    }
  }
}

.image-preview {
  margin-top: 8px;
  .el-image {
    width: 120px;
    height: 80px;
    border-radius: 4px;
    border: 1px solid #e2e8f0;
  }
}

.custom-tab-table {
  :deep(.el-table__header) {
    th { background-color: #f8fafc; color: #475569; font-weight: 400; }
  }
}

/* 联系人编辑相关样式 */
.drawer-header-custom {
  height: 64px; display: flex; justify-content: space-between; align-items: center;
  padding: 0 24px; border-bottom: 1px solid #f1f5f9; background-color: #fff; width: 100%;
  .header-title { font-size: 16px; font-weight: 400; color: #1e293b; }
}

.drawer-body-custom { padding: 24px; }

.form-title-blue {
  font-size: 14px; color: #409eff; background-color: #f0f9ff; padding: 8px 16px;
  margin: 24px 0 16px; border-left: 4px solid #409eff; font-weight: 400;
}

.form-section-custom { 
  padding: 0 16px; 
  :deep(.el-form-item) { margin-bottom: 18px !important; }
}

.contact-edit-drawer {
  :deep(.el-drawer__header) { margin-bottom: 0; padding: 0; }
}

.empty-text {
  text-align: center; padding: 40px 0; color: #999; font-size: 13px;
}

/* 隐藏滚动条 */
.tab-pane-container, :deep(.el-drawer__body) {
  &::-webkit-scrollbar { display: none; width: 0; height: 0; }
  -ms-overflow-style: none;
  scrollbar-width: none;
}

:deep(*) { 
  text-decoration: none !important; 
  font-weight: 400 !important;
}

/* 客户关怀弹窗专用样式 */
.care-dialog-body {
  padding: 10px 20px;
}

.info-section-static {
  margin-bottom: 10px;
  .el-form-item { margin-bottom: 8px; }
}

.form-section-input {
  .el-form-item { margin-bottom: 18px; }
}

.static-text {
  font-size: 14px;
  color: #334155;
  .tip-text {
    font-size: 13px;
    color: #94a3b8;
    margin-left: 8px;
  }
}
</style>
