<template>
  <el-drawer
    v-model="visible"
    direction="rtl"
    size="80%"
    :before-close="handleClose"
    class="project-detail-drawer"
    :with-header="false"
  >
    <!-- 顶部标题栏 -->
    <div class="detail-header">
      <span class="project-title">{{ modeTitle }}</span>
      <el-icon class="close-btn" @click="handleClose"><CloseIcon /></el-icon>
    </div>

    <!-- 模式 1: 详情展示模式 -->
    <template v-if="!isEdit">
      <!-- 项目进度步骤条 -->
      <div class="progress-section">
        <div class="section-label">项目进度</div>
        <div class="step-bar">
          <div class="step" v-for="(step, idx) in stepList" :key="idx"
               :class="{ active: (form.projectStatus || 0) === (idx + 1), finished: (form.projectStatus || 0) > (idx + 1) }"
               @click="handleStepClick(idx + 1)">
            <span class="step-text">{{ step }}</span>
          </div>
        </div>
        <div class="progress-link-row">
          <span class="progress-label">最新进度</span>
          <span class="progress-link" @click="showProgressDrawer = true">全部进度</span>
        </div>
      </div>

      <div class="detail-container">
        <!-- 左侧详情内容 -->
        <div class="detail-left">
          <el-tabs v-model="activeTab" class="custom-tabs">
            <el-tab-pane label="项目信息" name="info">
              <!-- 悬浮在右侧的编辑按钮 (原型图标准) -->
              <el-button type="primary" class="floating-edit-btn" @click="handleEdit">
                <el-icon style="margin-right: 4px;"><EditIcon /></el-icon> 编辑
              </el-button>
              <div class="info-block">
                <div class="block-header">
                  <div class="block-title">基本信息</div>
                </div>
                <div class="info-grid info-grid-2col">
                  <div class="info-item full-row">
                    <span class="label">项目名称</span>
                    <span class="value">{{ form.projectName || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">归属公司</span>
                    <span class="value">{{ companyName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">客户名称</span>
                    <span class="value">{{ form.customerName || '' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">行业</span>
                    <span class="value">{{ industryName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">部门</span>
                    <span class="value">{{ deptName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">项目负责人</span>
                    <span class="value">{{ leaderName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">项目状态</span>
                    <span class="value status-text">
                      <el-tag 
                        v-if="options.status.find(o => String(o.dictValue || o.value) === String(form.projectStatus))"
                        :class="['custom-status-tag', String(form.projectStatus) === '1' ? 'status-follow' : 'status-done']"
                        effect="plain"
                      >
                        {{ options.status.find(o => String(o.dictValue || o.value) === String(form.projectStatus))?.dictLabel || options.status.find(o => String(o.dictValue || o.value) === String(form.projectStatus))?.label }}
                      </el-tag>
                    </span>
                  </div>
                  <div class="info-item">
                    <span class="label">项目级别</span>
                    <span class="value grade-text">
                      {{ options.level.find(o => String(o.dictValue || o.value) === String(form.projectLevel))?.dictLabel || options.level.find(o => String(o.dictValue || o.value) === String(form.projectLevel))?.label }}
                    </span>
                  </div>
                  <div class="info-item left-only">
                    <span class="label">项目类型</span>
                    <span class="value">
                      {{ options.type.find(o => String(o.dictValue || o.value) === String(form.businessType))?.dictLabel || options.type.find(o => String(o.dictValue || o.value) === String(form.businessType))?.label }}
                    </span>
                  </div>
                </div>
              </div>

              <div class="info-block mt-24">
                <div class="block-header">
                  <div class="block-title">项目情况</div>
                </div>
                <div class="info-grid info-grid-3col">
                  <div class="info-item"><span class="label">登记日期</span><span class="value">{{ proxy.parseTime(form.createTime, '{y}-{m}-{d}') }}</span></div>
                  <div class="info-item"><span class="label">金额(万)</span><span class="value">{{ form.amount || '0.00' }}</span></div>
                  <div class="info-item"><span class="label">报名费</span><span class="value">{{ form.entryFee || '0.00' }}</span></div>
                  <div class="info-item"><span class="label">投标保证金</span><span class="value">{{ form.bidBond || '0.00' }}</span></div>
                  <div class="info-item"><span class="label">赢单率(%)</span><span class="value">{{ form.winningRate || '0' }}%</span></div>
                  <div class="info-item"><span class="label">报名截止时间</span><span class="value">{{ proxy.parseTime(form.signUpDeadline, '{y}-{m}-{d}') }}</span></div>
                  <div class="info-item"><span class="label">投标截止时间</span><span class="value">{{ proxy.parseTime(form.tenderDeadline, '{y}-{m}-{d}') }}</span></div>
                  <div class="info-item"><span class="label">标书汇编完成时间</span><span class="value">--</span></div>
                  <div class="info-item"><span class="label">服务期(年)</span><span class="value">{{ form.standardPeriod || '--' }}</span></div>
                  <div class="info-item"><span class="label">服务时间段</span><span class="value">{{ form.serviceTime || '--' }}</span></div>
                  <div class="info-item">
                    <span class="label">入围类型</span>
                    <span class="value">
                      {{ options.shortlisted.find(o => String(o.dictValue || o.value) === String(form.shortlistedType))?.dictLabel || options.shortlisted.find(o => String(o.dictValue || o.value) === String(form.shortlistedType))?.label }}
                    </span>
                  </div>
                  <div class="info-item">
                    <span class="label">物资类目</span>
                    <span class="value">
                       {{ options.profession.find(o => String(o.dictValue || o.value) === String(form.profession))?.dictLabel || options.profession.find(o => String(o.dictValue || o.value) === String(form.profession))?.label }}
                    </span>
                  </div>
                  <div class="info-item"><span class="label">招标代理机构</span><span class="value">{{ form.biddingAgency || '--' }}</span></div>
                  <div class="info-item"><span class="label">机构联系方式</span><span class="value">{{ form.agencyContact || '--' }}</span></div>
                  <div class="info-item empty-cell"></div>
                  <div class="info-item"><span class="label">标期类型</span><span class="value">{{ form.bidPeriodType === 1 ? '单项目入围' : '周期性框架' }}</span></div>
                  <div class="info-item"><span class="label">预计下次投标时间</span><span class="value">{{ proxy.parseTime(form.nextBiddingTime, '{y}-{m}-{d}') }}</span></div>
                  <div class="info-item"><span class="label">提前提醒天数</span><span class="value">{{ form.noticeAdvanceDays || '60' }}</span></div>
                  <div class="info-item full-row-3col">
                    <span class="label">招标链接</span>
                    <span class="value link-text" @click="handleOpenLink(form.biddingLink)">{{ form.biddingLink || '--' }}</span>
                  </div>
                  <div class="info-item full-row-3col">
                    <span class="label">入围要求</span>
                    <span class="value wrap-text">{{ form.condition || '' }}</span>
                  </div>
                  <div class="info-item full-row-3col">
                    <span class="label">项目描述</span>
                    <span class="value wrap-text">{{ form.projectDesc || '' }}</span>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <!-- 项目联系人 -->
            <el-tab-pane label="项目联系人" name="contact">
              <div class="tab-contact">
                <div style="display: flex; justify-content: flex-end; margin-bottom: 12px;">
                  <el-dropdown @command="handleContactCommand">
                    <el-button type="primary" size="small">
                      <el-icon style="margin-right: 4px;"><PlusIcon /></el-icon> 新建联系人
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="link">关联客户联系人</el-dropdown-item>
                        <el-dropdown-item command="create">新建联系人</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <el-table :data="(form.contactList || [])" border class="contact-table">
                  <el-table-column label="姓名" align="center" prop="name" min-width="100" show-overflow-tooltip />
                  <el-table-column label="性别" align="center" prop="gender" width="70">
                    <template #default="scope">{{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '--' }}</template>
                  </el-table-column>
                  <el-table-column label="部门" align="center" prop="deptName" min-width="100" show-overflow-tooltip />
                  <el-table-column label="职位" align="center" prop="position" min-width="100" show-overflow-tooltip />
                  <el-table-column label="项目角色" align="center" prop="roleName" min-width="100" show-overflow-tooltip />
                  <el-table-column label="是否关键人" align="center" prop="isKeyPerson" width="100">
                    <template #default="scope">{{ scope.row.isKeyPerson ? '是' : '否' }}</template>
                  </el-table-column>
                  <el-table-column label="手机号码" align="center" prop="phone" min-width="120" show-overflow-tooltip />
                  <el-table-column label="办公座机" align="center" prop="tel" min-width="130" show-overflow-tooltip />
                  <el-table-column label="操作" align="center" width="120">
                    <template #default="scope">
                      <el-button link type="primary" size="small">编辑</el-button>
                      <el-button link type="danger" size="small">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="!(form.contactList && form.contactList.length)" class="tab-empty">暂无数据</div>
              </div>
            </el-tab-pane>

            <!-- 结果分析 -->
            <el-tab-pane label="结果分析" name="analysis">
              <div class="tab-analysis">
                <div class="analysis-form">
                  <div class="form-field">
                    <div class="field-label">成交结果</div>
                    <el-radio-group v-model="form.resultType" size="small" style="margin-top: 4px;">
                      <el-radio :value="1">赢单</el-radio>
                      <el-radio :value="2">丢单</el-radio>
                    </el-radio-group>
                  </div>
                  <div class="form-field">
                    <div class="field-label">赢单总结</div>
                    <el-input
                      v-model="form.winSummary"
                      type="textarea"
                      placeholder="请输入赢单总结"
                      :rows="5"
                      resize="none"
                      maxlength="500"
                      show-word-limit
                    />
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 附件 -->
            <el-tab-pane label="附件" name="files">
              <div class="tab-files">
                <div style="display: flex; justify-content: flex-end; margin-bottom: 12px;">
                  <el-upload
                    multiple
                    :action="uploadFileUrl"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleUploadSuccess"
                  >
                    <el-button type="primary" :icon="UploadIcon" size="small">上传附件</el-button>
                  </el-upload>
                </div>
                <el-table :data="(form.fileList || [])" border class="file-table" empty-text="暂无附件">
                  <el-table-column label="文件名称" align="left" prop="fileName" min-width="200" show-overflow-tooltip />
                  <el-table-column label="文件类型" align="center" prop="fileType" width="100" />
                  <el-table-column label="上传时间" align="center" prop="uploadTime" width="160" />
                  <el-table-column label="操作" align="center" width="140">
                    <template #default="scope">
                      <el-button link type="primary" size="small" @click="handleDownloadFile(scope.row)">下载</el-button>
                      <el-button link type="danger" size="small" @click="handleDeleteFile(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>


          </el-tabs>
        </div>

        <!-- 右侧侧边栏内容 -->
        <div class="detail-right">
          <el-tabs v-model="activeSideTab" class="custom-tabs side-tabs">
            <el-tab-pane label="团队成员" name="team">
              <div class="side-content">
                <div class="team-header">
                  <span>团队成员 ({{ (form.memberList || []).length }})</span>
                  <el-icon class="add-icon" @click="handleAddMember"><PlusIcon /></el-icon>
                </div>
                <div class="search-box">
                  <el-input v-model="memberSearchKeyword" placeholder="请输入成员" :prefix-icon="SearchIcon" clearable />
                </div>
                <div class="team-list">
                  <div v-for="(m, i) in filteredMemberList" :key="i" class="team-item">
                    <el-avatar :size="36" class="user-avatar">{{ (m.memberName || m.staffName || m.realName || '').charAt(0) }}</el-avatar>
                    <div class="member-info">
                      <div class="info-top">
                        <span class="member-name">{{ m.memberName || m.staffName || m.realName }}{{ m.deptName ? '/' + m.deptName : '' }}</span>
                        <el-tag v-if="m.izManager === 1" size="small" type="success" effect="plain" class="leader-tag">负责人</el-tag>
                        <span class="role-desc">{{ m.roleName }}</span>
                        <span class="permission-desc">{{ m.permission }}</span>
                      </div>
                    </div>
                    <div class="member-actions">
                      <el-button link class="btn-edit" size="small" @click="handleEditMember(m)">编辑</el-button>
                      <el-button link class="btn-delete" size="small" @click="handleRemoveMember(m, i)">删除</el-button>
                    </div>
                  </div>
                  <div v-if="!filteredMemberList.length" class="empty-data">暂无团队成员</div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="跟进记录" name="records">
              <div class="side-content">
                <div class="record-header">
                  <el-button link type="primary" size="small" @click="handleAddRecord">
                    <el-icon><PlusIcon /></el-icon> 新建跟进记录
                  </el-button>
                  <div class="filter-item">
                    <span class="filter-label">拜访方式</span>
                    <el-select v-model="recordFilterType" placeholder="请选择" size="small" style="width: 100px" clearable>
                      <el-option v-for="item in options.visitType" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                  </div>
                </div>
                <div class="record-list custom-scroll">
                   <div v-if="!(form.followRecords && form.followRecords.length)" class="tab-empty">
                     <el-empty description="暂无跟进记录" :image-size="60" />
                   </div>
                   <div v-else class="timeline-container">
                     <div class="record-card-wrapper" v-for="(r, i) in form.followRecords" :key="i">
                       <!-- 时间轴点与时间 -->
                       <div class="timeline-header">
                         <div class="timeline-dot"></div>
                         <span class="timeline-time">{{ r.visitDate || r.createTime }}</span>
                       </div>
                       
                       <!-- 内容卡片 -->
                       <div class="record-card">
                         <div class="card-top">
                           <div class="user-info">
                             <el-avatar :size="32" class="user-avatar">{{ (r.visitorName || r.createBy || '').charAt(0) }}</el-avatar>
                             <div class="publish-info">
                               <span class="user-name">{{ r.visitorName || r.createBy }}</span>
                               <span class="publish-text">发布了条{{ options.visitType.find(o => String(o.dictValue) === String(r.visitType))?.dictLabel || '跟进' }}:</span>
                             </div>
                           </div>
                           <el-icon class="expand-icon"><ArrowDown /></el-icon>
                         </div>

                         <div class="card-content">
                           <div class="detail-row">
                             <span class="label">客户：</span>
                             <span class="value">{{ form.customerName }}</span>
                           </div>
                           <div class="detail-row">
                             <span class="label">拜访目的：</span>
                             <span class="value">{{ r.purpose || '--' }}</span>
                           </div>
                           <div class="detail-row">
                             <span class="label">跟进情况：</span>
                             <span class="value">{{ r.progress || r.content || '--' }}</span>
                           </div>
                           
                           <!-- 记录图片 -->
                           <div class="image-section" v-if="r.imageList && r.imageList.length">
                             <span class="label">记录图片：</span>
                             <div class="image-list">
                               <el-image 
                                 v-for="(img, idx) in r.imageList" 
                                 :key="idx"
                                 :src="img" 
                                 :preview-src-list="r.imageList"
                                 class="record-img"
                                 fit="cover"
                               />
                             </div>
                           </div>

                           <div class="update-time-row">
                             <span class="label">更新时间：</span>
                             <span class="value">{{ r.updateTime || r.visitDate || r.createTime }}</span>
                           </div>
                         </div>

                         <!-- 回复区域 -->
                         <div class="reply-section">
                           <el-input
                             v-model="r.replyContent"
                             type="textarea"
                             placeholder="请输入回复内容"
                             :rows="3"
                             resize="none"
                             class="reply-input"
                           />
                           <div class="reply-btn-row">
                             <el-button type="primary" size="small" class="reply-submit-btn" @click="handleReplySubmit(r)">
                               <el-icon style="margin-right: 4px;"><ChatLineSquare /></el-icon> 回复
                             </el-button>
                           </div>
                         </div>
                       </div>
                     </div>
                   </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="操作日志" name="logs">
              <div class="side-content">
                <div class="log-list">
                  <div class="log-item" v-for="(log, i) in (form.operationLogs || [])" :key="i">
                    <span class="log-time">{{ log.createTime }}</span>
                    <span class="log-user">{{ log.operator }}</span>
                    <span class="log-action">{{ formatLogAction(log) }}</span>
                    <span class="log-target" style="margin-left: 4px;">{{ translateDetails(log.actionDetails) }}<template v-if="formatLogTarget(log)">:</template>{{ formatLogTarget(log) }}</span>
                  </div>
                  <div v-if="!(form.operationLogs && form.operationLogs.length)" class="tab-empty">
                     <el-empty description="暂无日志" :image-size="60" />
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="管理信息" name="manage">
              <div class="side-content manage-info-container">
                <div class="manage-info-grid">
                  <div class="manage-item">
                    <span class="label">创建人</span>
                    <span class="value">{{ form.createByName || form.createBy || '--' }}</span>
                  </div>
                  <div class="manage-item">
                    <span class="label">创建日期</span>
                    <span class="value">{{ proxy.parseTime(form.createTime, '{y}-{m}-{d}') }}</span>
                  </div>
                  <div class="manage-item">
                    <span class="label">修改日期</span>
                    <span class="value">{{ proxy.parseTime(form.updateTime, '{y}-{m}-{d}') }}</span>
                  </div>
                  <div class="manage-item">
                    <span class="label">最后修改人</span>
                    <span class="value">{{ form.updateByName || form.updateBy || '--' }}</span>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </template>

    <!-- 模式 2: 表单编辑模式 -->
    <template v-else>
      <div class="edit-form-container">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="0">
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="form-section-header">
              <span class="section-title">基本信息</span>
            </div>
            <div class="form-grid form-grid-3col">
              <el-form-item prop="companyNo">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>归属公司</span>
                  <el-select v-model="form.companyNo" placeholder="请选择" size="small">
                    <el-option v-for="item in options.company" :key="item.companyCode || item.id" :label="item.companyName" :value="String(item.companyCode || item.id)" />
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item prop="customerName">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>客户名称</span>
                  <el-select 
                    v-model="form.customerName" 
                    placeholder="请输入关键词搜索客户" 
                    size="small" 
                    filterable 
                    remote 
                    :remote-method="remoteLoadCustomers" 
                    :loading="customerLoading"
                    clearable
                  >
                    <el-option 
                      v-for="item in options.customer" 
                      :key="item.id || item.customerNo" 
                      :label="item.customerName || item.customName" 
                      :value="item.customerName || item.customName" 
                    />
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item prop="businessType">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>项目类型</span>
                  <el-select v-model="form.businessType" placeholder="请选择" size="small">
                    <el-option v-for="item in options.type" :key="item.dictValue" :label="item.dictLabel" :value="String(item.dictValue)" />
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item prop="projectLevel">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>项目类别</span>
                  <el-select v-model="form.projectLevel" placeholder="请选择" size="small">
                    <el-option v-for="item in options.level" :key="item.dictValue" :label="item.dictLabel" :value="String(item.dictValue)" />
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item prop="leader">
                <div class="form-item">
                  <span class="field-label">项目负责人</span>
                  <el-select v-model="form.leader" placeholder="请选择" size="small">
                    <el-option v-for="item in options.user" :key="item.staffId || item.userId" :label="item.staffName || item.nickName" :value="String(item.staffId || item.userId)" />
                  </el-select>
                </div>
              </el-form-item>
              <div></div>
              <el-form-item prop="projectName" class="form-full-row">
                <div class="form-item form-full-item">
                  <span class="field-label"><span class="required-star">*</span>项目名称</span>
                  <el-input v-model="form.projectName" placeholder="请输入" size="small" />
                </div>
              </el-form-item>
            </div>
          </div>

          <!-- 项目情况 -->
          <div class="form-section">
            <div class="form-section-header">
              <span class="section-title">项目情况</span>
            </div>
            <div class="form-grid form-grid-3col">
              <!-- 第1行：金额 / 报名费 / 投标保证金 -->
              <el-form-item prop="amount">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>金额(万)</span>
                  <el-input v-model="form.amount" placeholder="请输入" size="small">
                    <template #append>万</template>
                  </el-input>
                </div>
              </el-form-item>
              <el-form-item prop="entryFee">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>报名费</span>
                  <el-input v-model="form.entryFee" placeholder="请输入" size="small" />
                </div>
              </el-form-item>
              <el-form-item prop="bidBond">
                <div class="form-item">
                  <span class="field-label">投标保证金</span>
                  <el-input v-model="form.bidBond" placeholder="请输入" size="small" />
                </div>
              </el-form-item>
              <!-- 第2行：赢单率 / 报名截止时间 / 投标截止时间 -->
              <el-form-item prop="winningRate">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>赢单率(%)</span>
                  <el-input v-model="form.winningRate" placeholder="请输入" size="small">
                    <template #append>%</template>
                  </el-input>
                </div>
              </el-form-item>
              <el-form-item prop="signUpDeadline">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>报名截止时间</span>
                  <el-date-picker v-model="form.signUpDeadline" type="date" placeholder="请选择" size="small" value-format="YYYY-MM-DD" />
                </div>
              </el-form-item>
              <el-form-item prop="tenderDeadline">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>投标截止时间</span>
                  <el-date-picker v-model="form.tenderDeadline" type="date" placeholder="请选择" size="small" value-format="YYYY-MM-DD" />
                </div>
              </el-form-item>
              <!-- 第3行：服务期 / 服务时间段 / 入围类型 -->
              <el-form-item prop="standardPeriod">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>服务期(年)</span>
                  <el-input v-model="form.standardPeriod" placeholder="请输入" size="small">
                    <template #append>年</template>
                  </el-input>
                </div>
              </el-form-item>
              <el-form-item prop="serviceTime">
                <div class="form-item">
                  <span class="field-label">服务时间段</span>
                  <el-input v-model="form.serviceTime" placeholder="请输入" size="small" />
                </div>
              </el-form-item>
              <el-form-item prop="shortlistedType">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>入围类型</span>
                  <el-select v-model="form.shortlistedType" placeholder="请选择" size="small">
                    <el-option v-for="item in options.shortlisted" :key="item.dictValue" :label="item.dictLabel" :value="String(item.dictValue)" />
                  </el-select>
                </div>
              </el-form-item>
              <!-- 第4行：物资类目 / 招标代理机构 / 代理机构联系方式 -->
              <el-form-item prop="profession">
                <div class="form-item">
                  <span class="field-label"><span class="required-star">*</span>物资类目</span>
                  <el-select v-model="form.profession" placeholder="请选择" size="small">
                    <el-option v-for="item in options.profession" :key="item.dictValue" :label="item.dictLabel" :value="String(item.dictValue)" />
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item prop="biddingAgency">
                <div class="form-item">
                  <span class="field-label">招标代理机构</span>
                  <el-input v-model="form.biddingAgency" placeholder="请输入" size="small" />
                </div>
              </el-form-item>
              <el-form-item prop="agencyContact">
                <div class="form-item">
                  <span class="field-label">代理机构联系方式</span>
                  <el-input v-model="form.agencyContact" placeholder="请输入" size="small" />
                </div>
              </el-form-item>
              <!-- 第5行：标期类型（整行） -->
              <el-form-item prop="bidPeriodType" class="form-full-row">
                <div class="form-item form-full-item">
                  <span class="field-label"><span class="required-star">*</span>标期类型</span>
                  <div style="display:flex;gap:24px;">
                    <el-radio-group v-model="form.bidPeriodType" size="small">
                      <el-radio :value="1">单项目入围</el-radio>
                      <el-radio :value="2">周期性框架</el-radio>
                    </el-radio-group>
                  </div>
                </div>
              </el-form-item>
              <!-- 第6行：招标链接 -->
              <el-form-item prop="biddingLink" class="form-full-row" v-if="form.bidPeriodType === 2">
                <div class="form-item form-full-item">
                  <span class="field-label">招标链接</span>
                  <el-input v-model="form.biddingLink" placeholder="请输入/粘贴链接" size="small" />
                </div>
              </el-form-item>
              <!-- 第7行：入围要求 -->
              <el-form-item prop="condition" class="form-full-row">
                <div class="form-item form-full-item form-item-vertical">
                  <span class="field-label"><span class="required-star">*</span>入围要求</span>
                  <el-input v-model="form.condition" type="textarea" placeholder="请输入" :rows="4" maxlength="500" show-word-limit resize="none" />
                </div>
              </el-form-item>
              <!-- 第8行：项目描述 -->
              <el-form-item prop="projectDesc" class="form-full-row">
                <div class="form-item form-full-item form-item-vertical">
                  <span class="field-label">项目描述</span>
                  <el-input v-model="form.projectDesc" type="textarea" placeholder="请输入" :rows="4" maxlength="500" show-word-limit resize="none" />
                </div>
              </el-form-item>
            </div>
          </div>

          <!-- 附件 -->
          <div class="form-section">
            <div class="form-section-header">
              <span class="section-title">附件</span>
              <el-upload
                :action="uploadFileUrl"
                :headers="headers"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
                multiple
              >
                <span class="upload-link"><el-icon><UploadIcon /></el-icon> 上传附件</span>
              </el-upload>
            </div>
            <el-table :data="(form.fileList || [])" class="attachment-table" empty-text="暂无附件" border>
              <el-table-column label="文件名称" align="left" prop="fileName" show-overflow-tooltip />
              <el-table-column label="文件类型" align="center" prop="fileType" width="100" />
              <el-table-column label="上传时间" align="center" prop="uploadTime" width="160" />
              <el-table-column label="操作" align="center" width="120">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click="handleDownloadFile(scope.row)">下载</el-button>
                  <el-button link type="danger" size="small" @click="handleDeleteFile(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>

        <div class="edit-drawer-footer">
          <el-button size="small" @click="handleCancelEdit">取消</el-button>
          <el-button type="primary" size="small" @click="submitForm">保存</el-button>
        </div>
      </div>
    </template>
  </el-drawer>

  <!-- 查看进度抽屉 -->
  <el-drawer
    v-model="showProgressDrawer"
    direction="rtl"
    size="480px"
    :with-header="false"
    class="progress-drawer"
    :close-on-click-modal="true"
  >
    <div class="progress-drawer-header">
      <span class="progress-drawer-title">查看进度</span>
      <el-icon class="progress-close-btn" @click="handleProgressClose"><CloseIcon /></el-icon>
    </div>
    <div class="progress-drawer-body">
      <div class="progress-input-wrapper">
        <el-input
          v-model="progressContent"
          type="textarea"
          placeholder="请输入进度描述"
          :maxlength="500"
          show-word-limit
          resize="none"
          :autosize="{ minRows: 6, maxRows: 6 }"
        />
      </div>
      <div class="publish-btn-row">
        <el-button type="primary" class="publish-btn" style="background-color: #409eff; border-color: #409eff;" @click="handlePublishProgress" :loading="progressLoading">
          <el-icon style="margin-right: 4px;"><PlusIcon /></el-icon> 发布
        </el-button>
      </div>
      <div class="record-list" v-loading="recordLoading">
        <div
          v-for="item in progressRecordList"
          :key="item.id"
          class="record-item"
        >
          <div class="record-header">
            <span class="record-user">{{ item.createByName || item.createBy || '' }}</span>
            <span class="record-time">{{ item.createTime || '' }}</span>
          </div>
          <div class="record-content">{{ item.followUpCondition || item.content || '' }}</div>
        </div>
        <el-empty v-if="!recordLoading && (!progressRecordList || progressRecordList.length === 0)" description="暂无进度记录" :image-size="60" />
        <div class="pagination-wrapper" v-if="progressTotal > 0">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="progressTotal"
            v-model:current-page="progressQueryParams.pageNum"
            v-model:page-size="progressQueryParams.pageSize"
            @current-change="loadProgressRecordList"
          />
        </div>
      </div>
    </div>
  </el-drawer>

  <!-- 关联客户联系人弹窗 -->
  <el-dialog v-model="linkContactVisible" title="关联客户联系人" width="900px" append-to-body>
    <el-table :data="customerContactList" border @selection-change="handleContactSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="联系人" align="center" prop="name" />
      <el-table-column label="部门" align="center" prop="dept" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="职位" align="center" prop="job" />
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="办公电话" align="center" prop="tel" />
    </el-table>
    <template #footer>
      <el-button @click="linkContactVisible = false">取消</el-button>
      <el-button type="primary" @click="submitLinkContact">确认</el-button>
    </template>
  </el-dialog>

  <!-- 新建项目联系人弹窗 -->
  <el-dialog v-model="addContactVisible" title="新建项目联系人" width="1000px" append-to-body>
    <el-form :model="contactForm" label-width="100px" size="small">
      <div class="form-section-header" style="margin-top: 0">
        <span class="section-title">基本信息</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="姓名" required><el-input v-model="contactForm.name" placeholder="请输入" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人类型">
            <el-radio-group v-model="contactForm.type">
              <el-radio label="1">公司职员</el-radio>
              <el-radio label="2">关系资源人</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别">
            <el-radio-group v-model="contactForm.gender">
              <el-radio label="1">男</el-radio>
              <el-radio label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年龄" required><el-input v-model="contactForm.age" placeholder="请输入" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="籍贯"><el-input v-model="contactForm.hometown" placeholder="请输入" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生日"><el-date-picker v-model="contactForm.birthday" type="date" placeholder="请选择" style="width: 100%" /></el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="描述"><el-input v-model="contactForm.description" type="textarea" placeholder="请输入" /></el-form-item>
        </el-col>
      </el-row>

      <div class="form-section-header">
        <span class="section-title">办公信息</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="在职状态">
            <el-radio-group v-model="contactForm.status">
              <el-radio label="1">在职</el-radio>
              <el-radio label="2">离职</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号码" required><el-input v-model="contactForm.phone" placeholder="请输入" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门" required><el-input v-model="contactForm.dept" placeholder="请输入" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职位"><el-input v-model="contactForm.job" placeholder="请输入" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="办公座机"><el-input v-model="contactForm.tel" placeholder="请输入" /></el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="办公地址">
            <div style="display: flex; gap: 10px; width: 100%">
              <el-select v-model="contactForm.area" placeholder="请选择" style="width: 200px" />
              <el-input v-model="contactForm.address" placeholder="请输入详细地址" style="flex: 1" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工作内容"><el-input v-model="contactForm.workContent" type="textarea" placeholder="请输入" /></el-form-item>
        </el-col>
      </el-row>

      <div class="form-section-header">
        <span class="section-title">项目决策</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="项目角色"><el-select v-model="contactForm.role" placeholder="请选择" style="width: 100%" /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否关键人"><el-select v-model="contactForm.isKey" placeholder="请选择" style="width: 100%" /></el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="公关情况"><el-input v-model="contactForm.prStatus" type="textarea" placeholder="请输入" /></el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="addContactVisible = false">取消</el-button>
      <el-button type="primary" @click="submitAddContact">保存</el-button>
    </template>
  </el-dialog>

  <!-- 添加团队成员弹窗 -->
  <el-dialog v-model="addMemberVisible" title="添加团队成员" width="460px" append-to-body class="member-dialog">
    <el-form :model="memberForm" label-width="100px">
      <el-form-item label="添加人员：" required>
        <el-select v-model="memberForm.userId" placeholder="请选择" filterable style="width: 100%">
          <el-option v-for="item in options.user" :key="item.userId || item.staffId" :label="item.nickName || item.staffName" :value="String(item.userId || item.staffId)" />
        </el-select>
      </el-form-item>
      <el-form-item label="成员角色：">
        <el-select v-model="memberForm.roleName" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in options.teamRole" :key="item.dictValue" :label="item.dictLabel" :value="item.dictLabel" />
        </el-select>
      </el-form-item>
      <el-form-item label="权限：">
        <el-radio-group v-model="memberForm.permission">
          <el-radio v-for="dict in options.permission" :key="dict.dictValue" :value="parseInt(dict.dictValue)">{{ dict.dictLabel }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitAddMember" style="padding: 8px 24px;">确 认</el-button>
        <el-button @click="addMemberVisible = false" style="padding: 8px 24px;">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑团队成员弹窗 -->
  <el-dialog v-model="editMemberVisible" title="编辑团队成员" width="460px" append-to-body class="member-dialog">
    <el-form :model="memberEditForm" label-width="100px">
      <el-form-item label="人员姓名：">
        <span>{{ memberEditForm.memberName || memberEditForm.staffName || memberEditForm.realName || memberEditForm.name }}{{ memberEditForm.deptName ? '/' + memberEditForm.deptName : '' }}</span>
      </el-form-item>
      <el-form-item label="成员角色：">
        <el-select v-model="memberEditForm.roleName" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in options.teamRole" :key="item.dictValue" :label="item.dictLabel" :value="item.dictLabel" />
        </el-select>
      </el-form-item>
      <el-form-item label="权限：">
        <el-radio-group v-model="memberEditForm.permission">
          <el-radio v-for="dict in options.permission" :key="dict.dictValue" :value="parseInt(dict.dictValue)">{{ dict.dictLabel }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitEditMember" style="padding: 8px 24px;">确 认</el-button>
        <el-button @click="editMemberVisible = false" style="padding: 8px 24px;">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 完善后的跟进记录弹窗 -->
  <el-dialog title="跟进记录" v-model="addRecordVisible" width="700px" append-to-body class="member-dialog">
    <el-form :model="recordForm" :rules="recordRules" ref="recordFormRef" label-width="100px">
      <el-form-item label="客户：">
        <span style="color: #333; font-weight: 500;">{{ form.customerName }}</span>
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="拜访人：" prop="visitor">
            <el-select v-model="recordForm.visitor" placeholder="请选择" style="width: 100%" filterable>
              <el-option v-for="item in (form.memberList || [])" :key="item.staffId || item.userId || item.id" :label="item.memberName || item.staffName || item.realName || item.name" :value="String(item.staffId || item.userId)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="随访人：">
            <el-select v-model="recordForm.accompanyPerson" placeholder="请选择" style="width: 100%" filterable clearable>
              <el-option v-for="item in options.user" :key="item.staffId || item.userId" :label="item.staffName || item.nickName" :value="String(item.staffId || item.userId)" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="拜访方式：" prop="visitType">
            <el-select v-model="recordForm.visitType" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in options.visitType" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拜访时间：" prop="visitDate">
            <el-date-picker v-model="recordForm.visitDate" type="datetime" placeholder="请选择" style="width: 100%" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="下次拜访时间：" class="label-nowrap">
        <el-date-picker v-model="recordForm.nextVisitDate" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
      </el-form-item>

      <el-form-item label="拜访目的：" prop="purpose">
        <el-input v-model="recordForm.purpose" type="textarea" :rows="3" placeholder="请输入内容" />
      </el-form-item>

      <el-form-item label="跟进情况：" prop="progress">
        <el-input v-model="recordForm.progress" type="textarea" :rows="3" placeholder="请输入内容" />
      </el-form-item>

      <el-form-item label="记录图片：">
        <el-upload
          :action="uploadFileUrl"
          :headers="headers"
          list-type="picture-card"
          v-model:file-list="recordImages"
          :on-success="handleRecordImgSuccess"
        >
          <el-icon><PlusIcon /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitAddRecord">确认</el-button>
        <el-button @click="addRecordVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted, getCurrentInstance } from 'vue';
import { useUserStore } from "@/store/modules/user";
import { listCompanyOption, listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listCommonDict } from "@/api/customer/customerDict";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { selectStaffOptionList } from "@/api/system/comStaff/index";
import { 
  Upload as UploadIcon, 
  Close as CloseIcon, 
  Edit as EditIcon, 
  Plus as PlusIcon, 
  Search as SearchIcon, 
  Delete as DeleteIcon, 
  Download as DownloadIcon 
} from '@element-plus/icons-vue';
import { globalHeaders } from '@/utils/request';
import { listByIds } from "@/api/system/oss/index";
import { publishProjectProgress, updateProjectSelection, getProjectSelection } from '@/api/saleManage/projectSelection/index';
import { listTeamMember, addTeamMember, updateTeamMember, delTeamMember } from "@/api/saleManage/opportunity/teamMember";
import { listOperationLog } from '@/api/customer/operationLog';
import { listContactPerson, addContactPerson } from "@/api/customer/contactPerson";
import { addRecord, listRecord } from "@/api/visit/record";
import { deptTreeSelect } from "@/api/system/user";

const props = defineProps({ modelValue: { type: Boolean, default: false }, data: Object, title: String });
const emit = defineEmits(['update:modelValue', 'submit']);

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const visible = ref(false);
const activeTab = ref('info');
const activeSideTab = ref('team');
const form = ref({});
const formRef = ref(null);
const options = ref({ 
  company: [], 
  customer: [], 
  user: [], 
  level: [], 
  type: [], 
  shortlisted: [], 
  profession: [],
  status: [],        // 项目状态字典
  industryList: [],   // 行业分类数据
  teamRole: [],       // 团队成员角色字典
  permission: [],     // 团队成员权限字典
  visitType: [],       // 拜访方式字典
  dept: []            // 部门数据
});
const recordFormRef = ref(null);
const recordImages = ref([]);
const isEdit = ref(false);
const customerLoading = ref(false);

// 查看进度相关
const showProgressDrawer = ref(false);
const progressContent = ref('');
const progressLoading = ref(false);
const recordLoading = ref(false);
const progressRecordList = ref([]);
const progressTotal = ref(0);
const progressQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  objectNo: undefined
});

// 联系人弹窗相关
const linkContactVisible = ref(false);
const addContactVisible = ref(false);
const customerContactList = ref([]);
const selectedContacts = ref([]);
const contactForm = ref({
  gender: '1',
  type: '1',
  status: '1'
});

// 成员搜索与过滤
const memberSearchKeyword = ref('');
const addMemberVisible = ref(false);
const editMemberVisible = ref(false);
const memberForm = ref({
  userId: undefined,
  roleName: undefined,
  permission: 0 // 默认仅查看(0)
});
const memberEditForm = ref({
  name: '',
  roleName: '',
  permission: 0
});

// 跟进记录
const addRecordVisible = ref(false);
const recordForm = ref({
  visitor: undefined,
  accompanyPerson: undefined,
  visitType: undefined,
  visitDate: '',
  nextVisitDate: '',
  purpose: '',
  progress: '',
  recordPicture: ''
});

const recordRules = {
  visitor: [{ required: true, message: "请选择拜访人", trigger: "change" }],
  visitType: [{ required: true, message: "请选择拜访方式", trigger: "change" }],
  visitDate: [{ required: true, message: "请选择拜访时间", trigger: "change" }],
  purpose: [{ required: true, message: "请输入拜访目的", trigger: "blur" }],
  progress: [{ required: true, message: "请输入跟进情况", trigger: "blur" }],
};

const filteredMemberList = computed(() => {
  const list = (form.value.memberList || []);
  if (!memberSearchKeyword.value) return list;
  return list.filter(m => 
    (m.name && m.name.includes(memberSearchKeyword.value)) || 
    (m.deptName && m.deptName.includes(memberSearchKeyword.value)) ||
    (m.roleName && m.roleName.includes(memberSearchKeyword.value))
  );
});

// 跟进记录过滤
const recordFilterType = ref(null);
watch(() => recordFilterType.value, () => {
  fetchFollowRecords();
});

// 上传相关
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload');
const headers = ref(globalHeaders());

// 步骤条数据
const stepList = ['获取信息', '正式立项', '竞价/投标', '项目跟进', '结案'];

const rules = {
  companyNo: [{ required: true, message: "请选择归属公司", trigger: "change" }],
  customerName: [{ required: true, message: "请选择客户名称", trigger: "change" }],
  projectLevel: [{ required: true, message: "请选择项目级别", trigger: "change" }],
  businessType: [{ required: true, message: "请选择项目类型", trigger: "change" }],
  projectName: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
  entryFee: [{ required: true, message: "请输入报名费", trigger: "blur" }],
  winningRate: [{ required: true, message: "请输入赢单率", trigger: "blur" }],
  signUpDeadline: [{ required: true, message: "请选择报名截止时间", trigger: "change" }],
  tenderDeadline: [{ required: true, message: "请选择投标截止时间", trigger: "change" }],
  standardPeriod: [{ required: true, message: "请输入服务期", trigger: "blur" }],
  shortlistedType: [{ required: true, message: "请选择入围类型", trigger: "change" }],
  profession: [{ required: true, message: "请选择物资类目", trigger: "change" }],
  bidPeriodType: [{ required: true, message: "请选择标期类型", trigger: "change" }],
  condition: [{ required: true, message: "请输入入围要求", trigger: "blur" }],
};

// 模式名称显示
const modeTitle = computed(() => {
  if (!form.value.id) return '新增年度入围项目';
  return isEdit.value ? '修改年度入围项目' : form.value.projectName;
});


// 数据匹配
const companyName = computed(() => {
  const target = options.value.company.find(c => String(c.companyCode || c.id) === String(form.value.companyNo));
  return target?.companyName || target?.name || form.value.companyNo || '--';
});
const projectLevelName = computed(() => options.value.level.find(o => String(o.dictValue) === String(form.value.projectLevel))?.dictLabel || form.value.projectLevel || '--');
const projectTypeName = computed(() => options.value.type.find(o => String(o.dictValue) === String(form.value.businessType))?.dictLabel || form.value.businessType || '--');
const shortlistedTypeName = computed(() => options.value.shortlisted.find(o => String(o.dictValue) === String(form.value.shortlistedType))?.dictLabel || form.value.shortlistedType || '--');
const projectStatusName = computed(() => options.value.status.find(o => String(o.dictValue) === String(form.value.projectStatus))?.dictLabel || form.value.projectStatus || '--');
const leaderName = computed(() => {
  const target = options.value.user.find(u => String(u.staffId || u.userId) === String(form.value.leader));
  return target?.staffName || target?.nickName || form.value.leaderName || form.value.leader || '--';
});
const professionName = computed(() => {
  const val = String(form.value.profession || '');
  if (!val) return '--';
  const p = options.value.profession.find(item =>
    String(item.id) === val ||
    String(item.industryCategoryId) === val ||
    String(item.industryId) === val ||
    String(item.dictValue) === val
  );
  return p?.industryCategoryName || p?.name || p?.categoryName || p?.dictLabel || '--';
});
const deptName = computed(() => {
  const val = String(form.value.deptNo || '');
  if (!val) return '--';
  const target = (options.value.dept || []).find(o => String(o.value) === val);
  return target?.label || val;
});

/** 行业名称（使用行业分类数据，与列表页一致） */
const industryName = computed(() => {
  const val = String(form.value.profession || '');
  if (!val) return '--';
  // 使用行业分类数据（与列表页 index.vue 一致）
  const list = (options.value.industryList || []);
  const p = list.find(i => String(i.id) === val || String(i.industryCategoryId) === val);
  if (p?.industryCategoryName) return p.industryCategoryName;
  // fallback: 尝试物资类目字典数据
  const d = options.value.profession.find(o => String(o.dictValue) === val);
  return d?.dictLabel || '--';
});

watch(() => props.modelValue, (val) => {
  visible.value = val;
  if (val) {
    form.value = { ...props.data };
    // 兼容字段
    if (!form.value.customerName && form.value.customName) {
      form.value.customerName = form.value.customName;
    }
    
    if (!form.value.id) {
      isEdit.value = true;
    } else {
      isEdit.value = false;
      fetchTeamMembers();
      fetchOperationLogs();
      fetchFollowRecords();
    }
  }
});

// 监听 data 变化，确保在不打开详情抽屉的情况下（如点击进度按钮），内部数据也能同步
watch(() => props.data, (newVal) => {
  if (newVal) {
    form.value = { ...newVal };
    if (!form.value.customerName && form.value.customName) {
      form.value.customerName = form.value.customName;
    }
  }
}, { deep: true });

/** 加载项目团队成员 */
const fetchTeamMembers = async () => {
  if (!form.value.id) return;
  try {
    const res = await listTeamMember(form.value.id);
    // 直接使用后端返回的原始数据，不做映射
    form.value.memberList = res.data || [];
  } catch (err) {
    console.error('加载团队成员失败:', err);
  }
};

/** 刷新项目详情（包含跟进记录） */
const refreshDetail = async () => {
  if (!form.value.id) return;
  try {
    const res = await getProjectSelection(form.value.id);
    form.value = res.data;
    // 辅助字段兼容
    if (!form.value.customerName && form.value.customName) {
      form.value.customerName = form.value.customName;
    }
    // 同时刷新团队成员、操作日志、跟进记录
    fetchTeamMembers();
    fetchOperationLogs();
    fetchFollowRecords();
  } catch (err) {
    console.error('刷新详情失败:', err);
  }
};

/** 加载跟进记录 */
const fetchFollowRecords = async () => {
  if (!form.value.id) return;
  try {
    const params = {
      objectNo: form.value.id,
      dataType: 2,
      pageSize: 50 // 加大加载量，确保显示完整
    };
    if (recordFilterType.value) {
      params.visitType = recordFilterType.value;
    }
    const res = await listRecord(params);
    const records = res.rows || res.data || [];
    
    // 处理图片 URL
    for (const r of records) {
      if (r.recordPicture && !r.imageList) {
        const ids = r.recordPicture.split(',');
        try {
          const ossRes = await listByIds(ids.join(','));
          r.imageList = (ossRes.data || []).map(img => img.url);
        } catch (e) {
          r.imageList = [];
        }
      }
      // 初始化回复内容
      r.replyContent = '';
    }
    
    form.value.followRecords = records;
  } catch (err) {
    console.error('加载跟进记录失败:', err);
  }
};

/** 提交回复 */
const handleReplySubmit = async (record) => {
  if (!record.replyContent?.trim()) {
    proxy.$modal.msgWarning("请输入回复内容");
    return;
  }
  try {
    await publishProjectProgress({
      objectNo: String(form.value.id),
      followUpCondition: record.replyContent.trim(),
      dataType: '2',
      parentId: record.id // 假设接口支持 parentId 作为回复
    });
    proxy.$modal.msgSuccess("回复成功");
    record.replyContent = '';
    fetchFollowRecords(); // 刷新列表
  } catch (err) {
    console.error('回复失败:', err);
  }
};

/** 加载操作日志 */
const fetchOperationLogs = async () => {
  if (!form.value.id) return;
  try {
    const res = await listOperationLog({ 
      objectNo: form.value.id,
      dataType: 2 // 年度入围项目
    });
    form.value.operationLogs = res.rows || res.data || [];
  } catch (err) {
    console.error('加载日志失败:', err);
  }
};

/** 翻译详情字段名 */
const translateDetails = (details) => {
  if (!details) return '';
  if (details.includes('projectStatus') || details.includes('年度入围')) {
    return '年度入围(项目)';
  }
  return details;
};

/** 格式化日志描述 - 模仿商机详情逻辑 */
const formatLogAction = (log) => {
  let details = log.actionDetails || '';
  
  // 完美兼容历史：一律按原型图格式化进度变更的 action 文本
  if (details.includes('projectStatus') || details.includes('年度入围')) {
    if (log.actionType === 2) {
      return '编辑了 年度入围';
    } else if (log.actionType === 1) {
      return '添加了 年度入围';
    }
  }

  // 处理常见的字段名
  const fieldMap = {
    'projectName': '项目名称',
    'projectStatus': '项目进度',
    'projectLevel': '项目类别',
    'businessType': '项目类型',
    'amount': '金额',
    'customerName': '客户名称',
    'companyNo': '归属公司'
  };
  
  Object.keys(fieldMap).forEach(key => {
    if (details.includes(key)) {
      details = details.replace(key, fieldMap[key]);
    }
  });

  // 处理进度值的映射 (动态字典获取，不使用硬编码)
  if (options.value && options.value.status) {
    options.value.status.forEach((item) => {
      const val = String(item.dictValue || item.value);
      const label = item.dictLabel || item.label;
      const reg = new RegExp(`(?<=[:\\s])${val}(?=[\\s]|$)`, 'g');
      if (details.includes(val)) {
        details = details.replace(reg, label);
      }
    });
  }

  return `${getLogActionText(log.actionType)} ${details}`;
};

/** 格式化日志目标对象 - 兼容老数据隐藏项目名称 */
const formatLogTarget = (log) => {
  if (!log.targetObject) return '';

  let details = log.actionDetails || '';
  // 完美兼容历史：强制转换 target 文本以对齐原型
  if (details.includes('projectStatus') || (details.includes('年度入围') && log.actionType === 2)) {
    let stepName = log.targetObject;
    
    if (log.targetObject === form.value.projectName) {
      const match = details.match(/\d/);
      if (match && options.value && options.value.status) {
        const val = match[0];
        const dict = options.value.status.find(o => String(o.dictValue || o.value) === String(val));
        stepName = dict ? (dict.dictLabel || dict.label) : '';
      } else {
        stepName = '';
      }
    } else if (stepName.includes('进度状态变更')) {
      const parts = stepName.split(',');
      if (parts.length > 1 && /^\d+$/.test(parts[1]) && options.value && options.value.status) {
        const val = parts[1];
        const dict = options.value.status.find(o => String(o.dictValue || o.value) === String(val));
        if (dict) {
          return `进度状态变更,${dict.dictLabel || dict.label}`;
        }
      }
      return stepName;
    }
    
    if (stepName) {
      return `进度状态变更,${stepName}`;
    }
    return '';
  }

  return log.targetObject;
};

/** 获取日志动作文本 */
const getLogActionText = (actionType) => {
  const map = {
    1: '添加了',
    2: '编辑了',
    3: '删除了',
    4: '认领了',
    5: '转移了',
    6: '分析了'
  };
  return map[actionType] || '操作了';
};

const handleClose = () => { 
  visible.value = false; 
  emit('update:modelValue', false); 
};

/** 开启编辑模式 */
const handleEdit = () => {
  isEdit.value = true;
};

/** 取消编辑 */
const handleCancelEdit = () => {
  if (!form.value.id) {
    handleClose();
  } else {
    isEdit.value = false;
    form.value = { ...props.data };
  }
};

/** 提交表单 */
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emit('submit', form.value);
    }
  });
};

/** 打开外部链接 */
const handleOpenLink = (url) => {
  if (url && (url.startsWith('http') || url.startsWith('https'))) {
    window.open(url, '_blank');
  }
};

/** 打开进度弹窗 */
const openProgressDrawer = (id) => {
  showProgressDrawer.value = true;
  const targetId = id || form.value.id;
  if (targetId) {
    progressQueryParams.objectNo = String(targetId);
    progressQueryParams.pageNum = 1;
    loadProgressRecordList();
  }
};

/** 加载进度记录列表 */
const loadProgressRecordList = async () => {
  if (!progressQueryParams.objectNo) return;
  recordLoading.value = true;
  try {
    const res = await listRecord(progressQueryParams);
    progressRecordList.value = res.rows || [];
    progressTotal.value = res.total || 0;
  } catch (err) {
    console.error('加载进度记录失败:', err);
  } finally {
    recordLoading.value = false;
  }
};

/** 关闭进度弹窗 */
const handleProgressClose = () => {
  showProgressDrawer.value = false;
  progressContent.value = '';
  progressRecordList.value = [];
  progressTotal.value = 0;
};

/** 状态及详情模式下的静默更新 */
const syncProjectData = async () => {
  if (form.value.id) {
    try {
      await updateProjectSelection(form.value);
      proxy.$modal.msgSuccess('操作成功');
      fetchOperationLogs(); // 刷新日志
    } catch (err) {
      console.error('同步失败:', err);
    }
  }
};

/** 处理上传成功 */
const handleUploadSuccess = (res, file) => {
  if (res.code === 200) {
    if (!form.value.fileList) form.value.fileList = [];
    const item = res.data;
    const name = item.originalName || item.fileName || file.name;
    const getExt = (n) => {
      const parts = n.split('.');
      return parts.length > 1 ? parts[parts.length - 1].toUpperCase() : '文件';
    };
    
    // 格式化文件大小
    const formatSize = (bytes) => {
      if (!bytes) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    form.value.fileList.push({
      ossId: item.ossId,
      fileName: name,
      fileType: getExt(name),
      fileSize: formatSize(file.size),
      fileUrl: item.url,
      url: item.url,
      uploadTime: proxy.parseTime(new Date()),
      uploader: userStore.nickname || userStore.name || '当前用户'
    });
    
    if (!isEdit.value) {
      syncProjectData();
    } else {
      proxy.$modal.msgSuccess("操作成功");
    }
  } else {
    proxy.$modal.msgError(res.msg || '操作失败');
  }
};

/** 处理附件下载 */
const handleDownloadFile = (row) => {
  if (row.ossId) {
    proxy.$download.oss(row.ossId);
  } else if (row.fileUrl || row.url) {
    window.open(row.fileUrl || row.url, '_blank');
  }
};

/** 处理附件删除 */
const handleDeleteFile = (index) => {
  form.value.fileList.splice(index, 1);
  if (!isEdit.value) syncProjectData();
};

/** 处理进度点击 */
const handleStepClick = async (clickedStatus) => {
  const oldStatus = form.value.projectStatus || 0;
  if (oldStatus === clickedStatus) return;
  const newStatus = clickedStatus;
  form.value.projectStatus = newStatus;
  if (form.value.id) {
    try {
      await updateProjectSelection({ ...form.value, projectStatus: newStatus });
      proxy.$modal.msgSuccess('操作成功');
      fetchOperationLogs(); // 刷新操作日志，确保进度变更被记录并显示
    } catch (err) {
      form.value.projectStatus = oldStatus;
      proxy.$modal.msgError('操作失败');
    }
  }
};

/** 发布进度 */
const handlePublishProgress = async () => {
  if (!progressContent.value.trim()) return;
  progressLoading.value = true;
  try {
    await addRecord({
      objectNo: String(form.value.id),
      followUpCondition: progressContent.value.trim(),
      dataType: '2'
    });
    proxy.$modal.msgSuccess('操作成功');
    progressContent.value = '';
    progressQueryParams.pageNum = 1;
    loadProgressRecordList();
  } catch (err) {
    console.error('进度发布失败:', err);
  } finally {
    progressLoading.value = false;
  }
};

/** 联系人下拉指令处理 */
const handleContactCommand = async (command) => {
  if (command === 'link') {
    linkContactVisible.value = true;
    try {
      const res = await listContactPerson({ customerId: form.value.customerId });
      customerContactList.value = res.rows || res.data || [];
    } catch (err) {
      console.error('获取联系人失败:', err);
    }
  } else if (command === 'create') {
    contactForm.value = { gender: '1', type: '1', status: '1' };
    addContactVisible.value = true;
  }
};

/** 确认关联联系人 */
const submitLinkContact = async () => {
  if (!selectedContacts.value.length) return;
  if (!form.value.contactList) form.value.contactList = [];
  const newContacts = selectedContacts.value.map(c => ({
    contactId: c.id,
    name: c.name,
    dept: c.dept,
    job: c.job,
    phone: c.phone,
    tel: c.tel,
    customerName: c.customerName
  }));
  form.value.contactList.push(...newContacts);
  linkContactVisible.value = false;
  if (!isEdit.value) await syncProjectData();
};

/** 提交新建联系人 */
const submitAddContact = async () => {
  try {
    const contactData = { ...contactForm.value, customerId: form.value.customerId };
    const res = await addContactPerson(contactData);
    const newContactId = res.data?.id || res.id;
    if (!form.value.contactList) form.value.contactList = [];
    form.value.contactList.push({ 
      ...contactForm.value, 
      contactId: newContactId,
    });
    addContactVisible.value = false;
    proxy.$modal.msgSuccess("操作成功");
    if (!isEdit.value) await syncProjectData();
  } catch (err) {
    console.error('新建联系人失败:', err);
  }
};

/** 侧边栏操作处理 */
const handleAddMember = () => {
  memberForm.value = {
    userId: undefined,
    roleName: undefined,
    permission: 0
  };
  addMemberVisible.value = true;
};

const handleEditMember = (member) => {
  memberEditForm.value = { ...member };
  editMemberVisible.value = true;
};

/** 提交添加成员 */
const submitAddMember = async () => {
  if (!memberForm.value.userId) {
    proxy.$modal.msgError("请选择添加人员");
    return;
  }
  
  const user = options.value.user.find(u => String(u.userId || u.staffId) === String(memberForm.value.userId));
  if (!user) return;

  if (form.value.id) {
    // 详情模式：直接调接口存入数据表
    try {
      await addTeamMember({
        staffId: memberForm.value.userId,
        realName: user.nickName || user.staffName,
        roleName: memberForm.value.roleName,
        roleCode: options.value.teamRole.find(r => r.dictLabel === memberForm.value.roleName)?.dictValue,
        updateAccredit: Number(memberForm.value.permission),
        izManager: memberForm.value.roleName === '业务负责人' ? 1 : 0, // 核心负责人标识
        objectNo: form.value.id,
        dataType: 2,
        platformCode: 'crm'
      });
      proxy.$modal.msgSuccess("操作成功");
      addMemberVisible.value = false;
      fetchTeamMembers();
      fetchOperationLogs(); // 刷新日志记录成员变动
    } catch (err) {
      console.error('添加成员失败:', err);
    }
  } else {
    // 新增模式：先存入本地列表，随主表一同提交
    const newMember = {
      userId: memberForm.value.userId,
      name: user.nickName || user.staffName,
      roleName: memberForm.value.roleName,
      permission: memberForm.value.permission,
      isLeader: memberForm.value.roleName === '业务负责人'
    };
    if (!form.value.memberList) form.value.memberList = [];
    form.value.memberList.push(newMember);
    addMemberVisible.value = false;
    proxy.$modal.msgSuccess("操作成功");
  }
};

/** 提交编辑成员 */
const submitEditMember = async () => {
  if (memberEditForm.value.id) {
    // 调接口更新数据表
    try {
      await updateTeamMember({
        id: memberEditForm.value.id,
        staffId: memberEditForm.value.userId,
        roleName: memberEditForm.value.roleName,
        roleCode: options.value.teamRole.find(r => r.dictLabel === memberEditForm.value.roleName)?.dictValue,
        updateAccredit: Number(memberEditForm.value.permission),
        izManager: memberEditForm.value.roleName === '业务负责人' ? 1 : 0,
        objectNo: form.value.id,
        dataType: 2,
        platformCode: 'crm'
      });
      proxy.$modal.msgSuccess("操作成功");
      editMemberVisible.value = false;
      fetchTeamMembers();
      fetchOperationLogs(); // 刷新日志记录成员变动
    } catch (err) {
      console.error('更新成员失败:', err);
    }
  } else {
    // 更新本地列表
    const index = form.value.memberList.findIndex(m => m.userId === memberEditForm.value.userId && m.name === memberEditForm.value.name);
    if (index > -1) {
      form.value.memberList[index] = { ...memberEditForm.value };
      editMemberVisible.value = false;
      proxy.$modal.msgSuccess("操作成功");
    }
  }
};

/** 移除成员 */
const handleRemoveMember = (member, index) => {
  proxy?.$modal.confirm('确认要移除该团队成员吗？').then(async () => {
    if (member.id) {
      // 调接口从数据表移除
      try {
        await delTeamMember(member.id);
        proxy.$modal.msgSuccess("操作成功");
        fetchTeamMembers();
      } catch (err) {
        console.error('移除成员失败:', err);
      }
    } else {
      // 从本地列表移除
      form.value.memberList.splice(index, 1);
      if (!isEdit.value) syncProjectData();
    }
  });
};
const handleAddRecord = () => {
  recordForm.value = {
    visitor: undefined, // 响应用户要求，不设置默认值
    accompanyPerson: undefined,
    visitType: undefined,
    visitDate: proxy.parseTime(new Date()),
    nextVisitDate: '',
    purpose: '',
    progress: '',
    recordPicture: ''
  };
  recordImages.value = [];
  addRecordVisible.value = true;
};

/** 记录图片上传成功 */
const handleRecordImgSuccess = (res) => {
  if (res.code === 200) {
    const urls = recordImages.value.map(f => f.url || f.response?.data?.url).filter(Boolean);
    recordForm.value.recordPicture = urls.join(',');
  }
};

/** 提交跟进记录 */
const submitAddRecord = async () => {
  recordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          ...recordForm.value,
          projectId: form.value.id,
          projectName: form.value.projectName,
          customerName: form.value.customerName,
          customerNo: form.value.customerId,
          objectNo: form.value.id,
          dataType: 2 // 表示年度入围项目
        };
        await addRecord(data);
        proxy.$modal.msgSuccess("操作成功");
        addRecordVisible.value = false;
        // 刷新详情以加载最新记录
        refreshDetail();
      } catch (err) {
        console.error('新建跟进记录失败:', err);
      }
    }
  });
};



// 暴露方法给父组件调用
defineExpose({ openProgressDrawer });

onMounted(() => {
  // 完全对齐 index.vue 的数据加载方式
  listCommonDict('XMJB0001').then(r => options.value.level = r.data);
  listCommonDict('L0001').then(r => options.value.type = r.data);
  listCommonDict('R0001').then(r => options.value.shortlisted = r.data);
  listCommonDict('ZBPL0001').then(r => options.value.profession = r.data);
  listCommonDict('J0001').then(r => options.value.status = r.data);
  // 成员角色字典
  listCommonDict('T0001').then(r => options.value.teamRole = r.data);
  // 拜访方式字典
  listCommonDict('visit_type').then(r => options.value.visitType = r.data || []);
  // 成员权限字典
  listCommonDict('team_permission').then(r => options.value.permission = r.data || []);
  // 行业分类数据（与列表页一致，用于显示行业名称）
  listIndustryCategory().then(r => { options.value.industryList = r.data; });
  listCompanyOption().then(r => options.value.company = r.data);
  remoteLoadCustomers(); // 默认加载前 500 条客户
  selectStaffOptionList().then(r => options.value.user = r.data);
  // 加载部门数据并打平
  deptTreeSelect().then(res => {
    const flatList = (list) => {
      let arr = [];
      for (const item of list || []) {
        arr.push({ label: item.label, value: String(item.id) });
        if (item.children?.length) arr.push(...flatList(item.children));
      }
      return arr;
    };
    options.value.dept = flatList(res.data);
  });
});

/** 远程加载客户信息 */
const remoteLoadCustomers = (query) => {
  customerLoading.value = true;
  // 增加对空查询的处理，默认加载前500条数据，搜索时检索匹配项
  const params = {
    customerName: query || undefined,
    pageSize: query ? 50 : 500
  };
  listCustomerInfo(params).then(res => {
    options.value.customer = res.rows || res.data || [];
    customerLoading.value = false;
  }).catch(err => {
    console.error('加载客户数据失败:', err);
    customerLoading.value = false;
  });
};
</script>

<style scoped lang="scss">
.custom-status-tag {
  border-radius: 4px;
  border-width: 1px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-weight: 500;
  
  &.status-follow {
    background-color: #fff7e8;
    border-color: #ffe4ba;
    color: #ff7d00; // 橙色文字
  }
  
  &.status-done {
    background-color: #e8ffea;
    border-color: #aff0b5;
    color: #00b42a; // 绿色文字
  }
}
/* 强制重置 el-drawer 的内部 body 样式，方便 flex 布局 */
:deep(.el-drawer) {
  top: 0 !important;
  padding: 0 !important;
}
:deep(.el-drawer__header) {
  display: none !important;
}
:deep(.el-drawer__body) {
  padding: 0 !important;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* ===== 顶部标题栏 ===== */
.detail-header {
  height: 48px;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: none; // 移除边框以实现无缝衔接
  background-color: var(--el-bg-color);

  .project-title {
    font-size: 25px;
    color: var(--el-text-color-primary);
    line-height: 48px;
  }
  .close-btn {
    font-size: 16px;
    color: var(--el-text-color-placeholder);
    cursor: pointer;
    transition: color 0.2s;
    &:hover { color: var(--el-color-danger); }
  }
}

/* ===== 项目进度区 - 高颜值优化版 ===== */
.progress-section {
  padding: 16px 24px 4px; // 减小垂直间距
  flex-shrink: 0;
  border-bottom: 1px solid #f2f3f5; // 增加浅色底边分隔

  .section-label {
    font-size: 14px;
    font-weight: 600;
    color: #409eff;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 14px;
      background: #409eff;
      border-radius: 2px;
      margin-right: 8px;
    }
  }

  /* 步骤条主体 */
  .step-bar {
    display: flex;
    align-items: center;
    margin: 8px 0 16px;
    height: 30px;
    width: 100%;

    .step {
      flex: 1;
      height: 100%;
      position: relative;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f2f3f5;
      margin-right: 4px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      
      /* 核心：倒序 z-index */
      &:nth-child(1) { z-index: 5; }
      &:nth-child(2) { z-index: 4; }
      &:nth-child(3) { z-index: 3; }
      &:nth-child(4) { z-index: 2; }
      &:nth-child(5) { z-index: 1; }

      .step-text {
        font-size: 12px;
        color: #86909c;
        z-index: 10;
        white-space: nowrap;
        font-weight: 500;
        transition: color 0.3s;
      }

      /* 箭头尖端形状 - 优化路径 */
      &::after {
        content: "";
        position: absolute;
        top: 0;
        right: -15px;
        width: 30px;
        height: 30px;
        background: inherit;
        transform: scale(0.707) rotate(45deg);
        z-index: 5;
        border-right: 2px solid #fff;
        border-top: 2px solid #fff;
        border-radius: 0 4px 0 0;
        transition: all 0.3s;
      }

      /* 第一个步骤 */
      &:first-child {
        border-radius: 4px 0 0 4px;
        padding-left: 10px;
      }

      /* 最后一个步骤 */
      &:last-child {
        border-radius: 0 4px 4px 0;
        padding-right: 10px;
        margin-right: 0;
        &::after { display: none; }
      }

      /* 选中态：使用更有活力的渐变绿 */
      &.active {
        background: linear-gradient(90deg, #2bc48d, #3bd9a0) !important;
        .step-text { color: #ffffff !important; font-weight: normal; }
        &::after { 
          background: #3bd9a0 !important;
        }
      }

      /* 已完成态：使用稳重的浅蓝绿 */
      &.finished {
        background-color: #2bc48d;
        opacity: 0.8;
        .step-text { color: #ffffff !important; }
        &::after { 
          background-color: #2bc48d !important;
        }
      }

      /* 悬停效果 */
      &:hover:not(.active):not(.finished) {
        background-color: #e5e6eb;
        .step-text { color: #2bc48d; }
        &::after { background-color: #e5e6eb; }
      }
    }
  }

  /* 最新进度行 */
  .progress-link-row {
    margin-top: 2px;
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    gap: 8px;

    .progress-label { color: var(--el-text-color-secondary); }
    .progress-link {
      color: var(--el-color-primary);
      cursor: pointer;
    }
  }
}

/* 详情主容器 */
.detail-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  background-color: #fff;
  border-top: 1px solid #f2f3f5;

  .detail-left {
    flex: 7;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    padding: 0 24px;
    border-right: 1px solid #f2f3f5;
  }

  .detail-right {
    flex: 3;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding: 0 20px;
  }
}

/* 严格还原的原型图 Tab 样式 */
.custom-tabs {
  height: 100%;
  :deep(.el-tabs__header) {
    margin-bottom: 0;
    border-bottom: 1px solid #f2f3f5;
  }
  :deep(.el-tabs__item) {
    font-size: 14px;
    color: #1d2129 !important; // 非激活文字为黑色
    padding: 0 16px !important;
    height: 48px;
    line-height: 48px;
    font-weight: 400;
    background: transparent !important;
    &.is-active { 
      color: #f53f3f !important; // 激活文字为红色
      font-weight: normal;
    }
    &:hover { color: #f53f3f !important; }
  }
  :deep(.el-tabs__content) {
    padding-top: 16px;
  }
  :deep(.el-tabs__active-bar) {
    background-color: #f53f3f !important; // 红色动态横线
    height: 3px;
    border-radius: 2px;
  }
  .el-tabs__nav-wrap::after {
    display: none;
  }
}

/* 详情信息块 */
.info-block {
  padding-bottom: 16px;
  position: relative;
  .block-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    .block-title {
      font-size: 15px;
      font-weight: normal;
      color: #409eff;
      position: relative;
      display: flex;
      align-items: center;
    }
  }
}

.floating-edit-btn {
  position: absolute;
  top: -44px;
  right: 0;
  background-color: #165dff;
  border: none;
  border-radius: 4px;
  height: 30px;
  padding: 0 14px;
  font-size: 13px;
  z-index: 10;
}

/* 信息网格 */
.info-grid {
  display: grid;
  gap: 8px 40px;
  margin-bottom: 8px;
  
  /* 2列布局 - 基本信息: label + value | label + value */
  &.info-grid-2col {
    grid-template-columns: auto 1fr auto 1fr;
  }
  
  /* 3列布局 - 项目情况: label + value | label + value | label + value */
  &.info-grid-3col {
    grid-template-columns: auto 1fr auto 1fr auto 1fr;
  }

  .info-item {
    display: contents;
    
    .label { 
      color: var(--el-text-color-secondary); 
      min-width: 80px;
      text-align: left;
      padding-right: 12px;
      line-height: 24px;
      white-space: nowrap;
      font-size: 12px;
    }
    .value { 
      color: var(--el-text-color-primary); 
      line-height: 24px;
      min-width: 120px;
      word-break: break-all;
      font-size: 12px;
    }
    .status-text { color: var(--el-text-color-primary); }
    .grade-text { font-weight: normal; color: var(--el-text-color-primary); }
    .link-text { color: var(--el-color-primary); cursor: pointer; }
    .wrap-text { white-space: pre-wrap; line-height: 1.6; }
  }
  
  /* 基本信息区 - 项目名称独占整行 */
  > .info-item.full-row {
    display: flex;
    grid-column: 1 / -1;
    .label { min-width: 80px; text-align: left; font-size: 12px; line-height: 28px; }
    .value { flex: 1; font-size: 16px; line-height: 28px; color: var(--el-text-color-primary); }
  }
  
  /* 基本信息区 - 项目类型独占左侧(右侧空) */
  > .info-item.left-only {
    display: contents;
    .label { grid-column: 1; text-align: left; font-size: 12px; }
    .value { grid-column: 2; font-size: 12px; }
  }
  
  /* 项目情况区 - 独占整行 (招标链接/入围要求/项目描述) */
  > .info-item.full-row-3col {
    display: flex;
    grid-column: 1 / -1;
    .label { min-width: 80px; text-align: left; font-size: 12px; line-height: 24px; }
    .value { flex: 1; font-size: 12px; line-height: 24px; }
  }
  
  /* 占位空白单元格 */
  > .info-item.empty-cell {
    display: contents;
    &::before, &::after { content: ''; }
  }
}

/* 侧边栏内容 */
.member-list {
  .member-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    border-radius: 6px;
    transition: background-color 0.2s;
    
    &:hover { background-color: #f7f8fa; }

    .member-info {
      display: flex;
      align-items: center;
      flex: 1;
      .member-avatar { 
        margin-right: 16px; 
        background-color: #f2f3f5;
        color: #fff;
        border: none;
        :deep(.el-icon) { font-size: 24px; }
      }
      .member-detail {
        .member-main-info {
          display: flex;
          align-items: center;
          gap: 20px; // 调大间距以匹配图片
          .member-name { font-size: 14px; color: #1d2129; }
          .leader-tag { 
            height: 18px; 
            line-height: 16px; 
            padding: 0 4px; 
            color: #00b42a; 
            border: 1px solid #00b42a; 
            background-color: transparent; 
            font-size: 12px;
            border-radius: 2px;
          }
          .sub-info {
            font-size: 13px;
            color: #86909c;
          }
        }
      }
    }
    
    .member-ops {
      display: flex;
      gap: 16px;
      .op-btn {
        font-size: 13px;
        cursor: pointer;
        &.edit { color: #fa8c16; } // 橙色
        &.delete { color: #86909c; } // 灰色
        &:hover { opacity: 0.7; }
      }
    }
  }
}

/* 跟进记录与日志共有样式 */
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  .filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
    .filter-label { font-size: 12px; color: #86909c; }
  }
}

.log-list {
  padding-top: 8px;
  .log-item {
    padding: 10px 0;
    border-bottom: none;
    font-size: 13px;
    line-height: 1.6;
    color: #4e5969;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .log-time { 
      width: 100%;
      font-size: 12px; 
      color: #86909c; 
      margin-bottom: 4px; 
    }
    
    .log-user { 
      color: #409eff; 
      font-weight: normal; 
      margin-right: 8px;
      cursor: default;
    }

    .log-action { 
      color: #86909c; 
      margin-right: 4px; 
    }

    .log-target { 
      color: #409eff;
      font-weight: 400;
    }
  }
}

.record-list {
  .log-item {
    padding: 12px 0;
    border-bottom: 1px dashed #f2f3f5;
    &:last-child { border-bottom: none; }
    .log-time { font-size: 12px; color: #c9cdd4; margin-bottom: 4px; }
    .log-content { font-size: 13px; color: #1d2129; line-height: 1.5; }
  }
}

/* 管理信息布局 */
.manage-info-container {
  padding: 16px 4px;
}
.manage-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px 16px;
  
  .manage-item {
    display: flex;
    flex-direction: column;
    gap: 6px;
    .label { font-size: 13px; color: #86909c; }
    .value { font-size: 14px; color: #1d2129; font-weight: normal; }
  }
}

/* 侧边栏基础布局 */
.side-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-top: 8px;
  .member-count {
    font-size: 14px;
    font-weight: normal;
    color: #1d2129;
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .add-icon { cursor: pointer; color: #86909c; font-size: 16px; &:hover { color: #165dff; } }
  }
  .search-box {
    margin: 8px 0 16px;
    :deep(.el-input__wrapper) {
      background-color: #fff;
      box-shadow: none;
      border: 1px solid #e5e6eb;
      height: 32px;
      border-radius: 2px;
      &:hover { border-color: #c9cdd4; }
      &.is-focus { border-color: #f53f3f; }
    }
  }
}

/* ===== 编辑表单模式 - 精确还原原型图 ===== */
.edit-form-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  overflow: hidden;

  .el-form {
    flex: 1;
    overflow-y: auto;
    padding: 20px 24px;
    &::-webkit-scrollbar { width: 4px; }
    &::-webkit-scrollbar-thumb { background-color: #e5e6eb; border-radius: 2px; }
  }
}

/* 区块标题 */
.form-section { margin-bottom: 24px; }
.form-section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  background-color: #f0f7ff;
  height: 34px;
  padding: 0 12px;
  position: relative;

  .section-title {
    font-size: 14px;
    font-weight: normal;
    color: #409eff;
    padding-left: 8px;
  }
  .upload-link {
    font-size: 13px;
    color: var(--el-color-primary);
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 4px;
    &:hover { opacity: 0.8; }
  }
}

/* 表单网格 - 3列布局 */
.form-grid {
  padding: 0 12px;
  &.form-grid-3col {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px 32px;
  }

  /* 每个表单项 */
  > .el-form-item {
    margin-bottom: 18px;
  }
}

/* 单个表单字段容器 */
.form-item {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;

  .field-label {
    white-space: nowrap;
    font-size: 13px;
    color: var(--el-text-color-placeholder);
    min-width: fit-content;
    text-align: right;
    line-height: 32px;
    .required-star { color: var(--el-color-danger); margin-right: 2px; }
  }

  /* 输入框/选择器自适应宽度 */
  :deep(.el-input),
  :deep(.el-select) { flex: 1; }
  :deep(.el-input__wrapper) {
    background-color: var(--el-bg-color) !important;
    box-shadow: none !important;
    border: 1px solid var(--el-border-color-light) !important;
    border-radius: 2px;
    transition: all 0.2s;
    padding: 0 10px;
    &:hover { border-color: var(--el-border-color) !important; }
    &.is-focus { 
      border-color: var(--el-color-primary) !important;
    }
  }
  
  :deep(.el-input__inner) {
    color: var(--el-text-color-primary);
    height: 30px;
    font-size: 13px;
    &::placeholder {
      color: var(--el-text-color-placeholder);
    }
  }

  /* 针对 append 样式的优化 */
  :deep(.el-input-group__append) {
    background-color: var(--el-fill-color-light);
    color: var(--el-text-color-placeholder);
    padding: 0 10px;
    border: 1px solid var(--el-border-color-light);
    border-left: none;
    font-size: 12px;
  }

  :deep(.el-textarea__inner) {
    background-color: var(--el-bg-color);
    box-shadow: none !important;
    border: 1px solid var(--el-border-color-light) !important;
    border-radius: 2px;
    padding: 6px 10px;
    color: var(--el-text-color-primary);
    font-size: 13px;
    &::placeholder { color: var(--el-text-color-placeholder); }
    &:hover { border-color: var(--el-border-color) !important; }
    &:focus { border-color: var(--el-color-primary) !important; }
  }
  :deep(.el-select) {
    --el-border-color: var(--el-border-color-light);
    --el-hover-border-color: var(--el-border-color);
    --el-input-text-color: var(--el-text-color-primary);
    --el-input-placeholder-color: var(--el-text-color-placeholder);
    :deep(.el-input__suffix-inner) {
      .el-icon { font-size: 12px; color: var(--el-border-color-light) !important; }
    }
  }
  :deep(.el-date-editor.el-input) { width: 100%; }
}

/* 整行字段（项目名称、标期类型等）*/
.form-full-row { grid-column: span 3; }
.form-full-item {
  display: flex;
  align-items: center;
  gap: 12px;
}
.form-item-vertical {
  align-items: flex-start !important;
  .field-label { line-height: 34px; }
  :deep(.el-textarea) { flex: 1; }
  :deep(.el-input__count) { bottom: 2px; right: 10px; }
}

/* 底部按钮栏 */
.edit-drawer-footer {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  padding: 16px 24px;
  background-color: #fff;
  border-top: 1px solid #e5e6eb;
  .el-button {
    height: 32px;
    padding: 0 20px;
    font-size: 14px;
    border-radius: 2px;
    
    &.el-button--primary {
      background-color: #165dff;
      border-color: #165dff;
      &:hover { background-color: #4080ff; border-color: #4080ff; }
    }
  }
}

/* 附件表格 */
.attachment-table {
  width: 100%;
  :deep(th.el-table__cell) { background-color: #f8fafc !important; font-size: 13px; font-weight: normal; color: #4e5969; }
  :deep(td.el-table__cell) { font-size: 13px; }
}

.mt-24 { margin-top: 24px; }

/* ===== Tab页面通用样式 ===== */
.tab-contact, .tab-analysis, .tab-files, .tab-quotes {
  height: 100%;
}

.tab-empty {
  text-align: center;
  padding: 60px 0;
  color: #c9cdd4;
  font-size: 13px;
}

/* ===== 项目联系人 ===== */
.tab-contact {
  .add-contact-btn {
    border-radius: 4px;
  }
  .contact-table {
    :deep(th.el-table__cell) { background-color: #f8fafc !important; color: #475569; font-weight: normal; font-size: 13px; }
    :deep(td.el-table__cell) { font-size: 13px; }
    :deep(.el-table__empty-text) { display: none; }
  }
}

/* ===== 结果分析 ===== */
.tab-analysis {
  .analysis-form {
    padding: 4px 0;
    .form-field {
      margin-bottom: 24px;
      &:last-child { margin-bottom: 0; }
      .field-label {
        font-size: 13px;
        color: var(--el-text-color-placeholder);
        margin-bottom: 8px;
        line-height: 1.5;
      }
      :deep(.el-radio-group) {
        .el-radio { color: var(--el-text-color-regular); font-size: 13px; margin-right: 28px; }
      }
      :deep(.el-textarea__inner) {
        border-radius: 4px;
        box-shadow: 0 0 0 1px var(--el-border-color-light) inset;
        padding: 8px 12px;
        font-size: 13px;
        line-height: 22px;
        color: var(--el-text-color-regular);
        &::placeholder { color: var(--el-text-color-placeholder); }
        &:hover { box-shadow: 0 0 0 1px var(--el-border-color) inset; }
        &:focus { box-shadow: 0 0 0 1px var(--el-color-primary) inset; }
      }
      :deep(.el-input__count) {
        bottom: 6px;
        right: 10px;
        font-size: 12px;
        color: #86909c;
        background: transparent;
      }
    }
  }
}

/* ===== 附件 ===== */
.tab-files {
  .file-table {
    :deep(th.el-table__cell) { background-color: #f8fafc !important; color: #475569; font-weight: normal; font-size: 13px; }
    :deep(td.el-table__cell) { font-size: 13px; }
    :deep(.el-table__empty-text) { display: none; }
  }
}



/* ===== 查看进度抽屉 - 精确还原原型图 ===== */
.progress-drawer {
  :deep(.el-drawer__body) {
    padding: 0 !important;
    display: flex;
    flex-direction: column;
  }
}

.progress-drawer-header {
  height: 48px;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #e5e6eb;
  background-color: #fff;

  .progress-drawer-title {
    font-size: 15px;
    font-weight: normal;
    color: var(--el-text-color-primary);
  }
  .progress-close-btn {
    font-size: 16px;
    color: var(--el-text-color-placeholder);
    cursor: pointer;
    transition: color 0.2s;
    &:hover { color: var(--el-color-danger); }
  }
}

.progress-drawer-body {
  padding: 24px 20px;
  flex: 1;

  .progress-input-wrapper {
    :deep(.el-textarea__inner) {
      border-radius: 4px;
      box-shadow: 0 0 0 1px #c9cdd4 inset;
      padding: 8px 12px;
      font-size: 13px;
      line-height: 22px;
      color: #4e5969;
      &::placeholder { color: #c9cdd4; }
      &:hover { box-shadow: 0 0 0 1px #86909c inset; }
      &:focus { box-shadow: 0 0 0 1px #165dff inset; }
    }
    :deep(.el-input__count) {
      bottom: 6px;
      right: 10px;
      font-size: 12px;
      color: #86909c;
      background: transparent;
    }
  }

  .publish-btn-row {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }

  .publish-btn {
    border-radius: 4px;
    height: 32px;
    padding: 0 20px;
    font-size: 13px;
  }

  .record-list {
    margin-top: 24px;

    .record-item {
      background: #fff;
      border-radius: 4px;
      padding: 14px 18px;
      margin-bottom: 12px;

      .record-header {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 8px;

        .record-user {
          font-size: 14px;
          color: #333;
        }

        .record-time {
          font-size: 13px;
          color: #999;
        }
      }

      .record-content {
        font-size: 14px;
        color: #606266;
        line-height: 1.6;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 16px;
    }
  }
}

/* 团队成员及跟进记录弹窗优化 */
:deep(.member-dialog) {
  border-radius: 8px;
  overflow: hidden;
  .el-dialog__header {
    margin-right: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #f2f3f5;
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #1d2129;
    }
  }
  .el-dialog__body {
    padding: 24px 24px 8px;
  }
  .el-dialog__footer {
    padding: 16px 24px 20px;
    border-top: none;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    .el-button {
      padding: 8px 18px;
      height: 32px;
      font-size: 13px;
      border-radius: 4px;
      &--primary {
        background-color: #165dff;
        border-color: #165dff;
      }
    }
  }

  .el-form-item {
    margin-bottom: 20px;
    &:last-child { margin-bottom: 0; }
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    .el-form-item__label {
      color: #4e5969;
      font-weight: 400;
      font-size: 13px;
      line-height: 32px;
      margin-bottom: 0;
      display: flex;
      align-items: center;
      white-space: nowrap;
      flex-shrink: 0;
    }
    .el-form-item__content {
      flex: 1;
      margin-left: 0 !important;
      line-height: normal;
      min-width: 0;
    }
  }
}
.label-nowrap :deep(.el-form-item__label) { 
  white-space: nowrap !important;
  display: block;
}
/* 团队成员区域 */
.team-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
  
  .add-icon {
    cursor: pointer;
    color: #86909C;
    font-size: 20px;
    &:hover {
      color: #00B881;
    }
  }
}

.search-box {
  margin-bottom: 20px;
  :deep(.el-input__wrapper) {
    background-color: #fff;
    box-shadow: 0 0 0 1px #E5E6EB inset;
    border-radius: 2px;
    height: 32px;
    
    &.is-focus {
      box-shadow: 0 0 0 1px #00B881 inset;
    }

    .el-input__inner {
      font-size: 13px;
      &::placeholder {
        color: #C9CDD4;
      }
    }
  }
}

.team-list {
  display: flex;
  flex-direction: column;
  
  .team-item {
    display: flex;
    align-items: center;
    background: transparent;
    padding: 12px 0;
    transition: all 0.2s;
    border-bottom: 1px solid #f2f3f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .member-info {
      flex: 1;
      margin-left: 12px;
      display: flex;
      flex-direction: column;
      
      .info-top {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 8px;
        
        .member-name {
          font-size: 14px;
          font-weight: 500;
          color: #1d2129;
        }
        
        .leader-tag {
          font-size: 12px;
          height: 20px;
          line-height: 18px;
          padding: 0 6px;
          color: #00B42A;
          background-color: #fff;
          border: 1px solid #00B42A;
          border-radius: 2px;
          margin-right: 4px;
        }
        
        .role-desc, .permission-desc {
          font-size: 12px;
          color: #86909C;
        }
      }
    }
    
    .member-actions {
      display: flex;
      gap: 12px;
      .el-button {
        padding: 0;
        font-size: 12px;
        &.btn-edit { 
          color: #FF7D00; 
        }
        &.btn-delete { 
          color: #86909C; 
        }
        
        &:hover { opacity: 0.8; }
      }
    }
  }
}

.empty-data {
  text-align: center;
  color: #86909C;
  padding: 30px 0;
  font-size: 13px;
}
/* 全局覆盖标签字体 */
:deep(.el-form-item__label),
:deep(.el-drawer__header) {
  font-weight: normal !important;
}
</style>
