<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 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"><dict-tag :options="saleStatusOptions" :value="form.status" /></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 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" min-width="120" show-overflow-tooltip>
                  <template #default="scope">
                    {{ scope.row.position || scope.row.roleName }}
                  </template>
                </el-table-column>
                <el-table-column label="项目角色" align="center" width="120">
                  <template #default="scope">
                    {{ scope.row.projectRole || scope.row.role || '' }}
                  </template>
                </el-table-column>
                <el-table-column label="是否关键人" align="center" width="110">
                  <template #default="scope">
                    <span>{{ (scope.row.isKeyPerson || scope.row.keyPerson) ? '是' : '否' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="140" fixed="right">
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleEditContact(scope.row)">编辑</el-button>
                    <el-button 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 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 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 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">
              <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 :href="scope.row.url" :underline="false" target="_blank" type="primary" style="margin-right: 10px;">下载</el-link>
                    <el-link 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" 
            business-type="leads"
            :info-data="{
              ...form,
              industryName: findIndustryName(form.profession),
              profession: findIndustryName(form.profession),
              customerName: form.customerName
            }"
          />
        </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 
      title="编辑项目联系人" 
      v-model="editContactVisible" 
      size="80%" 
      append-to-body
      destroy-on-close
      class="edit-contact-drawer"
    >
      <el-form :model="editContactForm" ref="editContactRef" label-width="100px" size="default">
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="form-section-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="姓名" prop="contactName" required>
                <el-input v-model="editContactForm.contactName" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人类型" prop="roleId" required>
                <el-radio-group v-model="editContactForm.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" required>
                <el-radio-group v-model="editContactForm.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-number v-model="editContactForm.age" :min="0" :max="150" style="width:100%" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="籍贯" prop="nativePlace">
                <el-input v-model="editContactForm.nativePlace" placeholder="请输入籍贯" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker v-model="editContactForm.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="editContactForm.remark" type="textarea" :rows="3" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 办公信息 -->
        <div class="form-section">
          <div class="form-section-title">办公信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="在职状态" prop="status" required>
                <el-radio-group v-model="editContactForm.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" required>
                <el-input v-model="editContactForm.phone" placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="部门" prop="deptName" required>
                <el-input v-model="editContactForm.deptName" placeholder="请输入部门" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="职位" prop="roleName" required>
                <el-input v-model="editContactForm.roleName" placeholder="请输入职位" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="办公座机" prop="officePhone">
                <el-input v-model="editContactForm.officePhone" placeholder="请输入办公座机" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="办公地址" prop="addressDetail">
                <el-input v-model="editContactForm.addressDetail" placeholder="请输入详细办公地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="工作内容" prop="workContent">
                <el-input v-model="editContactForm.workContent" type="textarea" :rows="3" placeholder="请输入工作内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 项目决策 -->
        <div class="form-section">
          <div class="form-section-title">项目决策</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="项目角色" prop="projectRole">
                <el-select v-model="editContactForm.projectRole" placeholder="请选择" style="width:100%" clearable>
                  <el-option
                    v-for="dict in projectRoleOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否关键人" prop="isKeyPerson">
                <el-select v-model="editContactForm.isKeyPerson" placeholder="请选择" style="width:100%">
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="公关情况" prop="prStatus">
                <el-input v-model="editContactForm.prStatus" type="textarea" :rows="3" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 家庭信息 -->
        <div class="form-section">
          <div class="form-section-title">家庭信息</div>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="家庭住址" prop="homeAddress">
                <el-input v-model="editContactForm.homeAddress" placeholder="请输入详细家庭地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="家庭情况" prop="familyStatus">
                <el-input v-model="editContactForm.familyStatus" placeholder="请输入家庭情况" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="爱好" prop="hobby">
                <el-input v-model="editContactForm.hobby" placeholder="请输入爱好" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性格特征" prop="character">
                <el-input v-model="editContactForm.character" placeholder="请输入性格特征" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="是否抽烟" prop="isSmoking">
                <el-radio-group v-model="editContactForm.isSmoking">
                  <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="isDrinking">
                <el-radio-group v-model="editContactForm.isDrinking">
                  <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-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div style="flex: auto; text-align: right; padding: 10px 20px; border-top: 1px solid #f0f0f0;">
          <el-button type="primary" @click="submitEditContact">保 存</el-button>
          <el-button @click="editContactVisible = false">取 消</el-button>
        </div>
      </template>
    </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>
      <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, updateContact, delContact } from '@/api/customer/crmContact';
import { getContactPerson } from "@/api/customer/contactPerson";
import { getSalesResultAnalyzeByObjectNo, addSalesResultAnalyze, updateSalesResultAnalyze } from '@/api/saleManage/leads/salesResultAnalyze';
import { listByIds } from '@/api/system/oss/index';
import { globalHeaders } from '@/utils/request';
import BusinessActivity from '../../common/businessActivity.vue';
import { Close, Edit, Plus, Upload, CircleCheck, ArrowDown } from '@element-plus/icons-vue';

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

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

const visible = ref(props.modelValue);
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 editContactVisible = ref(false);
const editContactLoading = ref(false);
const editContactForm = ref({});
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) => {
  emit('update:modelValue', val);
});

watch(() => [props.id, visible.value], ([newId, isVisible]) => {
  if (isVisible) {
    // 加载字典
    loadDicts();
    // 优先使用列表传入的基础数据，实现秒开体验
    if (props.infoData && Object.keys(props.infoData).length > 0) {
      form.value = { ...props.infoData };
    }
    if (newId) {
      getDetail(newId);
    }
  }
}, { immediate: true });

const loadDicts = () => {
};

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;
      loadProjectContacts();
      loadAnalysisData();
      loadOssFiles();
    } else {
      proxy.$modal.msgWarning("未获取到详情数据");
    }
  }).catch(err => {
    console.error('获取详情失败:', err);
  }).finally(() => {
    loading.value = false;
  });
};

const loadProjectContacts = () => {
  if (!form.value.id) return;
  contactLoading.value = true;
  listContact({ platformCode: String(form.value.id) }).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 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') {
    proxy.$modal.msgInfo("新建联系人功能开发中...");
  }
};

// 打开关联联系人弹窗
const openAssociateDialog = () => {
  if (!form.value.customerName) {
    proxy.$modal.msgWarning("当前线索未绑定客户，无法关联联系人");
    return;
  }
  associateVisible.value = true;
  associateLoading.value = true;
  // 根据客户名称查询联系人 (注意：后端参数名为 customName)
  listContact({ customName: form.value.customerName }).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("正在关联...");
    // 遍历选中的联系人，更新其 platformCode 为当前线索 ID
    const promises = selectedContacts.value.map(contact => {
      return updateContact({
        ...contact,
        platformCode: String(form.value.id)
      });
    });
    
    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.contactId || row.id;
  if (!contactId) return;
  contactDetailVisible.value = true;
  contactDetailLoading.value = true;
  getContactPerson(contactId).then(res => {
    contactForm.value = res.data || {};
  }).finally(() => {
    contactDetailLoading.value = false;
  });
};

const handleEditContact = (row) => {
  const contactId = row.contactId || row.id;
  if (!contactId) return;
  editContactLoading.value = true;
  getContactPerson(contactId).then(res => {
    editContactForm.value = res.data || {};
    // 确保单选框的值是字符串，以便正确匹配 radio
    if (editContactForm.value.roleId) editContactForm.value.roleId = String(editContactForm.value.roleId);
    if (editContactForm.value.gender) editContactForm.value.gender = String(editContactForm.value.gender);
    if (editContactForm.value.status) editContactForm.value.status = String(editContactForm.value.status);
    if (editContactForm.value.isSmoking) editContactForm.value.isSmoking = String(editContactForm.value.isSmoking);
    if (editContactForm.value.isDrinking) editContactForm.value.isDrinking = String(editContactForm.value.isDrinking);
    editContactVisible.value = true;
  }).finally(() => {
    editContactLoading.value = false;
  });
};

const submitEditContact = () => {
  proxy.$refs.editContactRef.validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在保存...");
      updateContact(editContactForm.value).then(() => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("修改成功");
        editContactVisible.value = false;
        loadProjectContacts();
      }).catch(() => {
        proxy.$modal.closeLoading();
      });
    }
  });
};

const handleDeleteContact = (row) => {
  proxy.$modal.confirm('确认要删除该联系人与本项目的关联吗？').then(() => {
    // 这里其实是取消关联，将 platformCode 置空
    return updateContact({ ...row, platformCode: '' });
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    loadProjectContacts();
  });
};

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();
    }
  });
};
</script>

<style scoped lang="scss">
.detail-wrapper { height: 100%; display: flex; flex-direction: column; background: #f5f7fa; }
.detail-header { 
  height: 45px; 
  padding: 0 20px; 
  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: 45px; } 
  .close-btn { cursor: pointer; font-size: 18px; color: #909399; line-height: 45px; &: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; }

.left-tabs { 
  display: flex; 
  padding: 0; // 移除容器边距
  border-bottom: 1px solid #f0f0f0; 
  height: 56px; 
  box-sizing: border-box;
  background: #fff;
  .left-tab-item { 
    padding: 0 15px; 
    height: 56px;
    line-height: 56px;
    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: 500;
    color: #409eff;
    margin-bottom: 12px;
    padding-left: 8px;
    border-left: 3px solid #409eff;
  }
}
: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>
