<template>
  <el-drawer
    v-model="visible"
    direction="rtl"
    size="85%"
    :close-on-click-modal="false"
    :with-header="false"
    class="detail-drawer"
  >
    <div class="detail-container">
      <!-- 自定义头部 -->
      <div class="detail-header">
        <div class="header-left">
          <span class="title">{{ detailData.projectName }}</span>
        </div>
        <div class="header-right">
          <el-icon class="close-icon" @click="visible = false"><Close /></el-icon>
        </div>
      </div>
      <!-- 顶部进度条区域 -->
      <div class="top-progress">
        <div class="section-title">项目进度</div>
        <div class="chevron-steps">
          <div 
            v-for="(step, index) in steps" 
            :key="index" 
            class="chevron-step"
            :class="{ 
              'is-active': currentStepIndex === index,
              'is-completed': currentStepIndex > index,
            }"
            @click="handleStepClick(index)"
          >
            <span class="step-text">{{ step }}</span>
          </div>
        </div>
      </div>

      <!-- 下部分栏区域 -->
      <div class="main-content">
        <!-- 左侧面板 -->
        <div class="left-panel">
          <el-tabs v-model="leftActiveTab" class="custom-tabs">
            <el-tab-pane label="项目信息" name="info">
              <div class="info-block">
                <div class="info-header">
                  <span class="title">基本信息</span>
                  <el-button v-if="!isReadOnly" type="primary" class="edit-btn" @click="$emit('edit', detailData)" size="default">
                    <el-icon style="margin-right: 4px;"><Edit /></el-icon>编辑
                  </el-button>
                </div>
                <el-descriptions :column="3" class="custom-desc">
                  <el-descriptions-item label="项目名称" :span="3">{{ detailData.projectName }}</el-descriptions-item>
                  
                  <el-descriptions-item label="归属公司">{{ findCompanyName(detailData.companyNo || detailData.CompanyNo) }}</el-descriptions-item>
                  <el-descriptions-item label="客户名称" :span="2">{{ detailData.customerName || detailData.customName }}</el-descriptions-item>
                  
                  <el-descriptions-item label="行业">{{ findIndustryLabel() }}</el-descriptions-item>
                  <el-descriptions-item label="部门">{{ findLeaderDeptName(detailData.leader) }}</el-descriptions-item>
                  <el-descriptions-item label="负责人">{{ detailData.leaderName || detailData.leader }}</el-descriptions-item>
                  
                  <el-descriptions-item label="项目状态">{{ getStatusLabel(detailData.projectStatus) }}</el-descriptions-item>
                  <el-descriptions-item label="项目级别">{{ getLevelLabel(detailData.projectLevel) }}</el-descriptions-item>
                  <el-descriptions-item label="项目类型">{{ getTypeLabel(detailData.businessType) }}</el-descriptions-item>
                  <el-descriptions-item label="产品支持">{{ detailData.productSupportName || findUserName(detailData.productSupport) }}</el-descriptions-item>
                </el-descriptions>
              </div>

              <div class="info-block" style="margin-top: 20px;">
                <div class="info-header">
                  <span class="title">项目情况</span>
                </div>
                <el-descriptions :column="3" class="custom-desc">
                  <el-descriptions-item label="登记日期">{{ proxy.parseTime(detailData.createTime, '{y}-{m}-{d}') }}</el-descriptions-item>
                  <el-descriptions-item label="金额(万)">{{ detailData.amount != null ? Number(detailData.amount).toFixed(2) : '' }}</el-descriptions-item>
                  <el-descriptions-item label="报名费">{{ detailData.entryFee }}</el-descriptions-item>
                  
                  <el-descriptions-item label="投标保证金">{{ detailData.bidBond }}</el-descriptions-item>
                  <el-descriptions-item label="赢单率(%)">{{ detailData.winningRate }}%</el-descriptions-item>
                  <el-descriptions-item label="报名截止时间">{{ proxy.parseTime(detailData.signUpDeadline, '{y}-{m}-{d}') }}</el-descriptions-item>
                  
                  <el-descriptions-item label="投标截止时间">{{ proxy.parseTime(detailData.tenderDeadline, '{y}-{m}-{d}') }}</el-descriptions-item>
                  <el-descriptions-item label="服务期(年)">{{ detailData.standardPeriod }}</el-descriptions-item>
                  <el-descriptions-item label="服务时间段">{{ detailData.serviceTime }}</el-descriptions-item>
 
                  <el-descriptions-item label="入围类型">{{ getShortlistedLabel(detailData.shortlistedType) }}</el-descriptions-item>
                  <el-descriptions-item label="物资类目">{{ findProfessionLabel(detailData.profession) }}</el-descriptions-item>
                  <el-descriptions-item label="标期类型">{{ detailData.bidPeriodType === 1 ? '单项目入围' : '周期性框架' }}</el-descriptions-item>
 
                  <el-descriptions-item label="招标链接" :span="3">
                    <template v-if="detailData.biddingLink || detailData.BiddingLink">
                      <el-link :href="detailData.biddingLink || detailData.BiddingLink" target="_blank" :underline="false" style="color: #1D2129;">
                        {{ detailData.biddingLink || detailData.BiddingLink }}
                      </el-link>
                    </template>
                    <span v-else></span>
                  </el-descriptions-item>
                  
                  <el-descriptions-item label="入围要求" :span="3">{{ detailData.condition }}</el-descriptions-item>
                  <el-descriptions-item label="项目描述" :span="3">{{ detailData.projectDesc }}</el-descriptions-item>
                </el-descriptions>
              </div>
            </el-tab-pane>

            <el-tab-pane label="项目联系人" name="contact">
               <div class="tab-toolbar">
                 <el-dropdown v-if="!isReadOnly" @command="handleContactCommand">
                   <el-button type="primary">
                     <el-icon style="margin-right: 4px;"><Plus /></el-icon>新建联系人<el-icon class="el-icon--right"><arrow-down /></el-icon>
                   </el-button>
                   <template #dropdown>
                     <el-dropdown-menu>
                       <el-dropdown-item command="associate">关联客户联系人</el-dropdown-item>
                       <el-dropdown-item command="new">新建联系人</el-dropdown-item>
                     </el-dropdown-menu>
                   </template>
                 </el-dropdown>
               </div>
                <el-table :data="contactList" border class="contact-table" style="width: 100%" v-loading="contactLoading">
                  <el-table-column label="姓名" align="center" width="100">
                    <template #default="scope">
                      <el-link type="primary" :underline="false" @click="handleEditContact(scope.row)">
                        {{ scope.row.contactName || scope.row.name }}
                      </el-link>
                    </template>
                  </el-table-column>
                  <el-table-column label="性别" align="center" width="80">
                    <template #default="scope">
                      {{ scope.row.gender === '0' || scope.row.sex === '0' ? '男' : scope.row.gender === '1' || scope.row.sex === '1' ? '女' : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="部门" align="center">
                    <template #default="scope">
                      {{ scope.row.deptName || scope.row.department }}
                    </template>
                  </el-table-column>
                  <el-table-column label="职位" align="center" prop="position" />
                  <el-table-column label="项目角色" align="center">
                    <template #default="scope">
                      {{ scope.row.projectRole || scope.row.role }}
                    </template>
                  </el-table-column>
                  <el-table-column label="是否关键人" align="center" width="100">
                    <template #default="scope">
                      <span>{{ (scope.row.isKeyPerson === 1 || scope.row.keyPerson === 1) ? '是' : '否' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="120" fixed="right">
                    <template #default="scope">
                      <el-button v-if="!isReadOnly" link type="primary" size="small" @click="handleEditContact(scope.row)">编辑</el-button>
                      <el-button v-if="!isReadOnly" link type="danger" size="small" @click="handleDeleteContact(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                  <template #empty><span class="empty-text">暂无数据</span></template>
                </el-table>
            </el-tab-pane>

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

            <el-tab-pane label="附件" name="attachment">
               <div v-if="!isReadOnly" class="tab-toolbar">
                 <el-upload
                   :action="uploadFileUrl"
                   :headers="headers"
                   :on-success="handleUploadSuccess"
                   :show-file-list="false"
                   multiple
                 >
                   <el-button type="primary" icon="Upload">上传附件</el-button>
                 </el-upload>
               </div>
               <el-table :data="detailFileList" border class="custom-table" style="width: 100%">
                 <el-table-column label="文件名称" align="center" prop="name" show-overflow-tooltip />
                 <el-table-column label="上传时间" align="center" prop="uploadTime" width="160" />
                 <el-table-column label="操作" align="center" width="120">
                    <template #default="scope">
                      <el-link :href="scope.row.url" :underline="false" target="_blank" type="primary" style="margin-right: 10px;">下载</el-link>
                      <el-link v-if="!isReadOnly" type="danger" :underline="false" @click="handleDeleteFile(scope.row)">删除</el-link>
                    </template>
                 </el-table-column>
                 <template #empty><span class="empty-text">暂无数据</span></template>
               </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 右侧面板：通用业务活动组件 -->
        <div class="right-panel">
          <BusinessActivity 
            v-if="detailData.id"
            ref="businessActivityRef"
            :businessId="detailData.id" 
            :dataType="3"
            :infoData="{
              ...detailData,
              customerName: detailData.customerName || detailData.customName,
              deptName: findLeaderDeptName(detailData.leader),
              department: findLeaderDeptName(detailData.leader),
              industryName: findIndustryLabel(),
              profession: findIndustryLabel()
            }" 
            businessType="projectSelection"
            @success="getList"
            @update-readonly="val => isReadOnly = val"
          />
        </div>
      </div>
    </div>
  </el-drawer>
<el-drawer v-model="projectContactDrawerOpen" direction="rtl" size="80%" destroy-on-close :with-header="false" append-to-body>
      <div class="drawer-header-compact" style="height: 40px; padding: 0 16px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; background: #fff;">
        <span style="font-size: 15px; font-weight: 600; color: #333;">{{ projectContactForm.id ? '编辑项目联系人' : '新建项目联系人' }}</span>
        <el-icon @click="projectContactDrawerOpen = false" style="cursor: pointer; font-size: 18px; color: #94a3b8;"><Close /></el-icon>
      </div>
      <div class="drawer-body-custom" style="padding: 20px; overflow-y: auto; height: calc(100% - 110px);">
        <el-form :model="projectContactForm" :rules="projectContactRules" ref="projectContactFormRef" label-width="100px" label-position="right" class="no-bold-label">
          <!-- 基本信息 -->
          <div class="form-section-group">
            <div class="section-group-title-bar">基本信息</div>
            <div class="section-group-content">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="姓名" prop="contactName"><el-input v-model="projectContactForm.contactName" placeholder="请输入" /></el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="联系人类型" prop="type">
                    <el-radio-group v-model="projectContactForm.type">
                      <el-radio value="1">公司职员</el-radio>
                      <el-radio value="2">关系资源人</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="projectContactForm.gender">
                      <el-radio value="0">男</el-radio><el-radio value="1">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="年龄" prop="age"><el-input v-model="projectContactForm.age" placeholder="请输入" /></el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="籍贯" prop="nativePlace"><el-input v-model="projectContactForm.nativePlace" placeholder="请输入" /></el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="生日" prop="birthday">
                    <el-date-picker v-model="projectContactForm.birthday" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="描述" prop="remark"><el-input v-model="projectContactForm.remark" type="textarea" :rows="3" placeholder="请输入" /></el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

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

          <!-- 家庭信息 -->
          <div class="form-section-group">
            <div class="section-group-title-bar">家庭信息</div>
            <div class="section-group-content">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="家庭住址" prop="homeAddressDetail">
                    <div style="display: flex; gap: 10px;">
                      <el-cascader
                        v-model="projectContactForm.homeRegion"
                        :options="areaOptions"
                        :props="{ label: 'areaName', value: 'id', children: 'children' }"
                        placeholder="请选择省/市/区"
                        style="width: 200px"
                        clearable
                      />
                      <el-input v-model="projectContactForm.homeAddressDetail" placeholder="请输入详细地址" style="flex: 1" />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="家庭情况" prop="familyStatus"><el-input v-model="projectContactForm.familyStatus" placeholder="请输入" /></el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="爱好" prop="hobby"><el-input v-model="projectContactForm.hobby" placeholder="请输入" /></el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="性格特征" prop="characterTrait"><el-input v-model="projectContactForm.characterTrait" placeholder="请输入" /></el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="是否抽烟" prop="isSmoke">
                    <el-radio-group v-model="projectContactForm.isSmoke">
                      <el-radio value="1">是</el-radio><el-radio value="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否喝酒" prop="isDrink">
                    <el-radio-group v-model="projectContactForm.isDrink">
                      <el-radio value="1">是</el-radio><el-radio value="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form>
      </div>
      <div class="drawer-footer-standard" style="padding: 15px 20px; border-top: 1px solid #f0f0f0; text-align: right;">
        <el-button @click="projectContactDrawerOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitProjectContact" :loading="contactSubmitting">确 定</el-button>
      </div>
    </el-drawer>

    <el-dialog title="关联客户联系人" v-model="associateVisible" width="1000px" append-to-body>
      <el-table :data="associateList" v-loading="associateLoading" border @selection-change="handleSelectionChange" max-height="400px">
        <el-table-column type="selection" width="55" />
        <el-table-column label="联系人" align="center" prop="contactName" width="120" />
        <el-table-column label="部门" align="center" prop="deptName" width="130" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="180" show-overflow-tooltip />
        <el-table-column label="职位" align="center" prop="position" width="110" />
        <el-table-column label="手机号码" align="center" prop="phone" width="120" />
        <el-table-column label="办公电话" align="center" prop="officePhone" width="120" />
      </el-table>
      <template #footer>
        <div class="dialog-footer" style="padding-top: 10px;">
          <el-button type="primary" @click="confirmAssociate" :disabled="selectedContacts.length === 0">确 认</el-button>
          <el-button @click="associateVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

</template>

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

const props = defineProps({
  modelValue: Boolean,
  projectLevelOptions: Array,
  companyOptions: Array,
  userOptions: Array,
  projectTypeOptions: Array,
  shortlistedTypeOptions: Array,
  statusOptions: Array,
  professionOptions: Array,
  deptOptions: Array
});

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

const steps = ['入围跟进', '标前磋商', '立项公示', '应标投标', '结案'];
const currentStepIndex = computed(() => {
  const status = detailData.value.projectStatus;
  if (!status || status === '0') return -1;
  return parseInt(status) - 1;
});

const visible = ref(false);
const isReadOnly = ref(true);
const detailData = ref({});
const leftActiveTab = ref('info');
const businessActivityRef = ref(null);
const proxy = getCurrentInstance().proxy;
const { 
  LXRJE0001: projectRoleOptions,
  deal_result: resultOptions
} = toRefs(reactive(proxy.useDict("LXRJE0001", "deal_result")));

// 附件管理
const detailFileList = ref([]);
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload');
const headers = ref(globalHeaders());

// 状态同步
watch(() => props.modelValue, (val) => { visible.value = val; });
watch(() => visible.value, (val) => { emit('update:modelValue', val); });

watch(() => detailData.value.fileNo, async (val) => {
  if (val) {
    try {
      const res = await listByIds(val);
      detailFileList.value = (res.data || []).map(item => ({
        name: item.originalName || item.fileName || '',
        url: item.url,
        ossId: item.ossId,
        uploadTime: item.createTime
      }));
    } catch (e) {}
  } else {
    detailFileList.value = [];
  }
}, { immediate: true });

const open = async (row) => {
  visible.value = true;
  leftActiveTab.value = 'info';
  detailData.value = { ...row };
  
  loadDicts();
  if (row.id) {
    try {
      const res = await getProjectSelection(row.id);
      const serverData = res.data || res;
      detailData.value = { 
        ...detailData.value, 
        ...serverData,
        biddingLink: serverData.biddingLink || serverData.BiddingLink || detailData.value.biddingLink,
        companyName: serverData.companyName || detailData.value.companyName,
        deptName: serverData.deptName || serverData.departmentName || detailData.value.deptName || row.deptName,
        industryName: serverData.industryName || detailData.value.industryName || row.industryName
      };
      fetchContactList(row.id);
      loadAnalysisData();
      
      // 动态补全行业信息 (如果仍然缺失)
      if (!detailData.value.industryName && (detailData.value.customNo || detailData.value.customerNo)) {
        getCustomerInfo(detailData.value.customNo || detailData.value.customerNo).then(cRes => {
          const cData = cRes.data || cRes;
          const industryId = cData.industryCategoryId || cData.industryId;
          const industryName = cData.industryName || props.professionOptions?.find(o => String(o.id) === String(industryId))?.industryCategoryName;
          if (industryName) {
            detailData.value = { ...detailData.value, industryName: industryName };
          }
          // 如果部门还是空的，尝试从客户那看看（虽然可能性小，但也算个来源）
          if (!detailData.value.deptName && (cData.deptName || cData.departmentName)) {
            detailData.value = { ...detailData.value, deptName: cData.deptName || cData.departmentName };
          }
        }).catch(() => {});
      }
    } catch (error) {}
  }
};

// --- 项目联系人逻辑 ---
const contactList = ref([]);
const contactLoading = ref(false);
const contactSubmitting = ref(false);
const projectContactDrawerOpen = ref(false);
const projectContactFormRef = ref(null);
const projectContactForm = reactive({
  id: undefined, customerId: undefined, contactName: '', type: '1', gender: '0', age: '', nativePlace: '', birthday: '', remark: '',
  jobStatus: '1', phone: '', deptName: '', position: '', officePhone: '', officeRegion: [], provincialCityCounty: '', addressDetail: '', jobContent: '',
  projectRole: null, isKeyPerson: 0, prStatus: '', familyStatus: '', hobby: '', characterTrait: '', isSmoke: '0', isDrink: '0',
  homeRegion: [], homeAddressDetail: ''
});
const projectContactRules = {
  contactName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
  deptName: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  phone: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
  ],
  officePhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位座机号码', trigger: 'blur' }
  ]
};
const areaOptions = ref([]);
const associateVisible = ref(false);
const associateLoading = ref(false);
const associateList = ref([]);
const selectedContacts = ref([]);

const loadDicts = () => {
  if (areaOptions.value.length === 0) {
    listProvinceWithCities().then(res => {
      const list = res.rows || [];
      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 fetchContactList = async (id) => {
  if (!id) return;
  contactLoading.value = true;
  try {
    const res = await listContact({ platformCode: String(id) });
    contactList.value = res.rows || [];
  } catch (e) {} finally { contactLoading.value = false; }
};

const handleContactCommand = (command) => {
  if (command === 'associate') { handleAssociate(); } 
  else if (command === 'new') { handleNewProjectContact(); }
};

const handleAssociate = () => {
  if (!detailData.value.customNo && !detailData.value.companyNo) {
    return ElMessage.warning("缺少客户信息，无法关联联系人");
  }
  associateVisible.value = true;
  associateLoading.value = true;
  listContact({ customNo: detailData.value.customNo || detailData.value.companyNo }).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 confirmAssociate = async () => {
  if (selectedContacts.value.length === 0) return;
  try {
    const promises = selectedContacts.value.map(contact => {
      return updateContact({ ...contact, platformCode: String(detailData.value.id) });
    });
    await Promise.all(promises);
    ElMessage.success('关联成功');
    associateVisible.value = false;
    fetchContactList(detailData.value.id);
  } catch (e) {}
};

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

const handleEditContact = (row) => {
  const contactId = row.contactId || row.id;
  if (!contactId) return;
  proxy.$modal.loading("加载中...");
  getContact(contactId).then(res => {
    const data = res.data || {};
    Object.assign(projectContactForm, {
      id: data.id,
      customerId: data.customerId,
      contactName: data.contactName,
      type: String(data.type || '1'),
      gender: String(data.gender || '0'),
      age: data.age,
      nativePlace: data.nativePlace,
      birthday: data.birthday,
      remark: data.remark,
      jobStatus: String(data.jobStatus || '1'),
      phone: data.phone,
      deptName: data.deptName,
      position: data.position,
      officePhone: data.officePhone,
      addressDetail: data.addressDetail,
      jobContent: data.jobContent,
      projectRole: data.projectRole !== null && data.projectRole !== undefined ? Number(data.projectRole) : null,
      isKeyPerson: data.isKeyPerson !== null && data.isKeyPerson !== undefined ? Number(data.isKeyPerson) : 0,
      prStatus: data.prStatus,
      familyStatus: data.familyStatus,
      hobby: data.hobby,
      characterTrait: data.characterTrait,
      isSmoke: String(data.isSmoke || '0'),
      isDrink: String(data.isDrink || '0'),
      officeRegion: (data.addressProvince && data.addressCity && data.addressCounty) ? [data.addressProvince, data.addressCity, data.addressCounty] : [],
      homeRegion: (data.homeProvinceId && data.homeCityId && data.homeAreaId) 
        ? [data.homeProvinceId, data.homeCityId, data.homeAreaId] : [],
      homeAddressDetail: data.homeAddressDetail
    });
    projectContactDrawerOpen.value = true;
  }).finally(() => {
    proxy.$modal.closeLoading();
  });
};

const submitProjectContact = () => {
  projectContactFormRef.value.validate(async (valid) => {
    if (valid) {
      contactSubmitting.value = true;
      try {
        const payload = { 
          ...projectContactForm, 
          roleId: projectContactForm.type === '1' ? 1 : 2,
          // 关联客户信息
          customerId: detailData.value.customerId || detailData.value.realCustomerId || projectContactForm.customerId,
          platformCode: 'crm',
          customerName: detailData.value.customerName || '',
          customerNo: detailData.value.companyNo || detailData.value.customNo || '',
          projectNo: detailData.value.projectNo || '',
          // age 字段转换
          age: projectContactForm.age ? parseInt(projectContactForm.age, 10) : null,
          // 地址处理
          addressProvince: projectContactForm.officeRegion?.[0] ? String(projectContactForm.officeRegion[0]) : null,
          addressCity: projectContactForm.officeRegion?.[1] ? String(projectContactForm.officeRegion[1]) : null,
          addressCounty: projectContactForm.officeRegion?.[2] ? String(projectContactForm.officeRegion[2]) : null,
          // 转换家庭地址编码
          homeProvinceId: projectContactForm.homeRegion?.[0] || null,
          homeCityId: projectContactForm.homeRegion?.[1] || null,
          homeAreaId: projectContactForm.homeRegion?.[2] || null
        };
        if (projectContactForm.id) { await updateContact(payload); } 
        else { await addContact(payload); }
        ElMessage.success('保存成功');
        projectContactDrawerOpen.value = false;
        fetchContactList(detailData.value.id);
      } catch (e) {} finally { contactSubmitting.value = false; }
    }
  });
};

const handleDeleteContact = (row) => {
  ElMessageBox.confirm(`确认删除联系人「${row.name || row.contactName}」吗？`, '提示', { type: 'warning' }).then(async () => {
    await delContact(row.id);
    ElMessage.success('操作成功');
    fetchContactList(detailData.value.id);
  });
};

// --- 结果分析逻辑 ---
const analysisForm = reactive({ id: undefined, resultType: undefined, summary: '', loseReason: '', fileNo: '' });
const analysisFileList = ref([]);

const loadAnalysisData = async () => {
  if (!detailData.value.projectNo) return;
  try {
    const res = await getSalesResultAnalyzeByObjectNo(detailData.value.projectNo);
    if (res.data) {
      Object.assign(analysisForm, {
        id: res.data.id, resultType: res.data.dealResult ? String(res.data.dealResult) : undefined,
        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 
        }));
      }
    }
  } catch (e) {}
};

const handleSaveAnalysis = async () => {
  const ossIds = analysisFileList.value.map(f => f.ossId).join(',');
  const payload = {
    id: analysisForm.id,
    objectNo: detailData.value.projectNo,
    dataType: 3, // 3代表项目精选/年度入围
    dealResult: analysisForm.resultType === 'win' ? 1 : 2,
    winSumUp: analysisForm.summary,
    loseReason: analysisForm.loseReason,
    fileNo: ossIds
  };
  try {
    if (analysisForm.id) { await updateSalesResultAnalyze(payload); } 
    else { await addSalesResultAnalyze(payload); }
    ElMessage.success("保存成功");
    loadAnalysisData();
    emit('success');
  } catch (e) {}
};

const handleAnalysisUploadSuccess = (res) => {
  if (res.code === 200) {
    analysisFileList.value.push({ 
      name: res.data.originalName || res.data.fileName || '', 
      url: res.data.url, 
      ossId: res.data.ossId 
    });
    ElMessage.success("上传成功");
  }
};

const handleAnalysisDeleteFile = (index) => { analysisFileList.value.splice(index, 1); };
const downloadFile = (file) => { if (file.url) window.open(file.url, '_blank'); };

const handleUploadSuccess = async (res) => {
  if (res.code === 200) {
    const ossId = res.data.ossId;
    const currentFileNos = detailData.value.fileNo ? detailData.value.fileNo.split(',') : [];
    currentFileNos.push(ossId);
    const newFileNo = currentFileNos.join(',');
    
    try {
      await updateProjectSelection({ id: detailData.value.id, fileNo: newFileNo });
      detailData.value.fileNo = newFileNo;
      ElMessage.success('上传成功');
    } catch (e) {}
  }
};

const handleDeleteFile = (row) => {
  ElMessageBox.confirm(`确认删除附件「${row.name}」吗？`, '提示', { type: 'warning' }).then(async () => {
    const currentFileNos = detailData.value.fileNo ? detailData.value.fileNo.split(',') : [];
    const newFileNo = currentFileNos.filter(id => String(id) !== String(row.ossId)).join(',');
    
    try {
      proxy.$modal.loading("正在删除...");
      await updateProjectSelection({ id: detailData.value.id, fileNo: newFileNo });
      detailData.value.fileNo = newFileNo;
      ElMessage.success('删除成功');
    } catch (e) {
    } finally {
      proxy.$modal.closeLoading();
    }
  });
};

const handleStepClick = async (index) => {
  if (isReadOnly.value) return;
  const targetStatus = String(index + 1);
  const isCancel = targetStatus === String(detailData.value.projectStatus);
  
  try {
    proxy.$modal.loading("正在处理...");
    const finalStatus = isCancel ? String(index) : targetStatus;
    await updateProjectSelection({
      id: detailData.value.id,
      projectStatus: finalStatus
    });
    detailData.value.projectStatus = finalStatus;
    ElMessage.success('操作成功');
    if (businessActivityRef.value) {
      businessActivityRef.value.fetchDynamicData();
    }
    emit('success');
  } catch (error) {
  } finally {
    proxy.$modal.closeLoading();
  }
};

const getStatusLabel = (val) => props.statusOptions?.find(o => String(o.value) === String(val))?.label || val;
const getLevelLabel = (val) => props.projectLevelOptions?.find(o => String(o.value) === String(val))?.label || val;
const getTypeLabel = (val) => props.projectTypeOptions?.find(o => String(o.value) === String(val))?.label || val;
const getShortlistedLabel = (val) => props.shortlistedTypeOptions?.find(o => String(o.value) === String(val))?.label || val;
const findProfessionLabel = (val) => {
  if (!val) return '';
  return props.professionOptions?.find(o => String(o.id || o.value || o.dictValue) === String(val))?.label || val;
};
const findIndustryLabel = () => {
  return detailData.value.industryName || 
         props.professionOptions?.find(o => String(o.id) === String(detailData.value.industryId || detailData.value.industry || detailData.value.profession))?.industryCategoryName || 
         '';
};
const findLeaderDeptName = (val) => {
  const leaderId = val || detailData.value.leader;
  // 优先从人员选项中匹配部门
  const user = props.userOptions?.find(u => String(u.staffId || u.userId || u.id) === String(leaderId));
  const userDept = user ? (user.deptName || user.departmentName) : null;
  // 如果人员档案没带部门，则显示项目数据中存储的部门名称
  return userDept || detailData.value.deptName || '';
};

const findCompanyName = (val) => {
  const value = val || detailData.value.companyNo || detailData.value.CompanyNo;
  if (!value) return detailData.value.companyName || '';
  
  // 广泛匹配：deptId (add页面用), companyCode (edit页面用), id (常规)
  const company = props.companyOptions?.find(o => 
    String(o.companyCode) === String(value) || 
    String(o.deptId) === String(value) || 
    String(o.id) === String(value)
  );
  
  return company ? (company.companyName || company.deptName || company.name) : (detailData.value.companyName || value);
};

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

const getList = () => { emit('success'); };

defineExpose({ open });
</script>

<style lang="scss" scoped>
.detail-drawer {
  :deep(.el-drawer__body) { padding: 0 !important; background-color: #fff; }
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #f0f2f5;
  background-color: #fff;
  .header-left {
    .title {
      font-size: 16px;
      font-weight: normal;
      color: #333;
    }
  }
  .header-right {
    .close-icon {
      cursor: pointer;
      font-size: 18px;
      color: #909399;
      transition: color 0.3s;
      &:hover {
        color: #409eff;
      }
    }
  }
}

.detail-container { height: 100%; display: flex; flex-direction: column; }

.top-progress {
  padding: 5px 20px 12px; background-color: #fff; border-bottom: 1px solid #f5f5f5;
  .main-title { font-size: 16px; font-weight: normal; color: #303133; line-height: 40px; } 
  .chevron-steps {
    display: flex; align-items: center; gap: 0; padding: 2px 0;
    .chevron-step {
      flex: 1; height: 32px; display: flex; align-items: center; justify-content: center; background-color: #F2F3F5; color: #86909C; font-size: 13px; position: relative; cursor: pointer; transition: all 0.3s;
      margin-right: -10px; // 负边距实现重叠
      clip-path: polygon(calc(100% - 10px) 0%, 100% 50%, calc(100% - 10px) 100%, 0% 100%, 10px 50%, 0% 0%);
      
      &:first-child { 
        border-radius: 4px 0 0 4px; 
        clip-path: polygon(calc(100% - 10px) 0%, 100% 50%, calc(100% - 10px) 100%, 0% 100%, 0% 0%); 
      }
      &:last-child { 
        border-radius: 0 4px 4px 0; 
        margin-right: 0;
        clip-path: polygon(100% 0%, 100% 100%, 0% 100%, 10px 50%, 0% 0%); 
      }
      
      &.is-active { background-color: #00B881; color: #fff; z-index: 2; font-weight: 500 !important; }
      &.is-completed { background-color: #E6F8F3; color: #00B881; z-index: 1; }
      &:hover:not(.is-active) { background-color: #E5E6EB; z-index: 3; }
    }
  }
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  .left-panel {
    flex: 1;
    background: #fff;
    border-right: 1px solid #f0f0f0;
    padding: 0 20px 15px;
    overflow-y: auto;
    // 隐藏滚动条
    &::-webkit-scrollbar { display: none; }
    scrollbar-width: none;
    -ms-overflow-style: none;
  }
  .right-panel {
    width: 450px;
    background: #fff;
    overflow-y: auto;
    // 隐藏滚动条
    &::-webkit-scrollbar { display: none; }
    scrollbar-width: none;
    -ms-overflow-style: none;
    
    :deep(.activity-container) {
      .el-tabs__header {
        margin-top: 0;
        margin-bottom: 0;
        height: 48px;
        .el-tabs__nav-wrap {
          height: 100%;
          display: flex;
          align-items: center;
        }
      }
    }
  }
}

.info-block {
  .info-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; .title { font-size: 15px; font-weight: normal !important; color: #409eff; padding-left: 0; } }
}

.custom-tabs {
  :deep(.el-tabs__header) { margin-bottom: 15px; height: 48px; border-bottom: 1px solid #f2f2f2; }
  :deep(.el-tabs__nav-wrap::after) { height: 0; }
  :deep(.el-tabs__nav-wrap) { height: 100%; display: flex; align-items: center; }
  :deep(.el-tabs__item) { font-size: 14px; font-weight: normal !important; height: 48px; line-height: 48px; }
}

.tab-toolbar { margin-bottom: 15px; display: flex; justify-content: flex-end; }

.analysis-section {
  padding: 10px;
  .analysis-form {
    .analysis-row { display: flex; align-items: center; margin-bottom: 20px; .form-label { width: 80px; color: #4E5969; font-weight: normal !important; } }
    .summary-title { font-size: 14px; color: #4E5969; margin-bottom: 10px; font-weight: normal !important; }
    .summary-textarea-wrap { margin-bottom: 20px; }
    .attachment-section-title { font-size: 14px; color: #4E5969; margin-bottom: 10px; font-weight: normal !important; }
    .upload-area { margin-bottom: 10px; }
  }
}

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

:deep(.el-radio__label) {
  font-weight: normal !important;
}

:deep(.el-table th) {
  font-weight: normal !important;
}

.section-group-title-bar {
  font-size: 14px; color: #409eff; padding: 8px 15px; background-color: #F8F9FA; margin-bottom: 20px; border-radius: 4px;
}
.form-section-group { margin-bottom: 30px; }



.custom-desc {
  margin-top: 15px;
  :deep(.el-descriptions__label) { 
    color: #86909C; 
    font-weight: normal !important; 
    min-width: 90px; 
    padding-bottom: 12px !important;
    text-align: left;
    &:after {
      content: '：';
    }
  }
  :deep(.el-descriptions__content) { 
    color: #1D2129; 
    font-weight: normal !important;
    padding-bottom: 12px !important;
    padding-right: 20px;
  }
}

</style>
