<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" label-width="100px">
        <!-- 第一行 -->
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="所属公司" prop="companyNo">
              <el-select v-model="queryParams.companyNo" placeholder="请选择" style="width: 100%" clearable>
                 <el-option
                   v-for="item in companyOptions"
                   :key="item.companyCode"
                   :label="item.companyName"
                   :value="item.companyCode"
                 />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="负责人" prop="leader">
              <el-select v-model="queryParams.leader" placeholder="请选择" style="width: 100%" clearable>
                <el-option
                  v-for="item in userOptions"
                  :key="item.staffId"
                  :label="item.staffName"
                  :value="item.staffId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="24" style="margin-top: 10px;">
          <el-col :span="6">
            <el-form-item label="部门" prop="deptNo">
              <el-tree-select v-model="queryParams.deptNo" :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                placeholder="请选择所属部门" style="width: 100%" clearable filterable check-strictly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品支持" prop="productSupport">
              <el-select v-model="queryParams.productSupport" placeholder="请选择" style="width: 100%" clearable>
                 <el-option
                   v-for="item in userOptions"
                   :key="item.staffId"
                   :label="item.staffName"
                   :value="item.staffId"
                 />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" style="width: 100%" clearable placeholder="请选择">
                 <el-option
                   v-for="item in saleStatusOptions"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value"
                 />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="时间查询类型" prop="timeType">
              <el-select v-model="queryParams.timeType" style="width: 100%" clearable placeholder="请选择">
                 <el-option
                   v-for="item in timeQueryTypeOptions"
                   :key="item.id"
                   :label="item.dictLabel"
                   :value="item.dictValue"
                 />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="24" style="margin-top: 10px;">
          <el-col :span="6">
            <el-form-item label="时间范围" prop="dateRange">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="To" start-placeholder="开始时间" end-placeholder="结束时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <div class="search-btns" style="padding-left: 10px;">
              <el-button type="default" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" @click="handleAdd" class="btn-new">新增</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <div class="summary-stripe">
      <span class="stripe-title">销售线索信息列表</span>
      <span class="stripe-total">金额总计<span class="red-text">{{ totalAmount.toFixed(2) }}</span> (万)</span>
      <div class="stripe-actions">
        <el-button type="primary" size="small" :disabled="multipleSelection.length === 0" icon="Switch" @click="handleTransfer">转移给他人</el-button>
        <el-button type="primary" size="small" :disabled="multipleSelection.length === 0" icon="Link" @click="handleBatchClaim">批量认领</el-button>
      </div>
    </div>

    <el-card shadow="never" class="table-card">
      <el-table ref="leadsTable" v-loading="loading" :data="leadsList" border class="standard-table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" fixed />
        <el-table-column label="项目名称" align="center" prop="projectName" min-width="180" show-overflow-tooltip fixed />

        <el-table-column label="采购内容" align="center" prop="purchaseContent" min-width="150" show-overflow-tooltip />
        <el-table-column label="所属公司" align="center" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ companyOptions.find(i => i.companyCode === scope.row.companyNo)?.companyName || scope.row.companyNo }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="200" show-overflow-tooltip />
        <el-table-column label="行业" align="center" width="150">
          <template #default="scope">
            {{ industryOptions.find(i => i.id == scope.row.profession)?.industryCategoryName || scope.row.profession }}
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" min-width="150">
          <template #default="scope">
            {{ findDeptName(scope.row.deptNo) || scope.row.deptNo }}
          </template>
        </el-table-column>
        <el-table-column label="金额(万)" align="center" prop="projectBudget" width="100" sortable>
          <template #default="scope">
            <span>{{ Number(scope.row.projectBudget || 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="赢单率" align="center" prop="winRate" width="100" sortable>
          <template #default="scope">
            <span>{{ scope.row.winRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="项目级别" align="center" width="120">
          <template #default="scope">
            {{ findProjectLevelName(scope.row.projectLevel) }}
          </template>
        </el-table-column>
        <el-table-column label="项目负责人" align="center" prop="leaderName" width="120" />
        <el-table-column label="产品支持" align="center" prop="productSupport" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="120" sortable>
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="立项时间" align="center" prop="expectedCompletionTime" width="130" sortable>
          <template #default="scope">
            <span>{{ parseTime(scope.row.expectedCompletionTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="截止时间" align="center" prop="publicBiddingDeadline" width="130" sortable>
          <template #default="scope">
            <span>{{ parseTime(scope.row.publicBiddingDeadline, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="saleStatusOptions" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" @click="handleClaim(scope.row)">认领</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 弹窗1：转移他人 -->
    <el-dialog title="是否将选中的项目线索转移其他负责人？" v-model="transferVisible" width="550px" append-to-body>
      <el-form label-width="100px" style="padding: 20px 0;">
        <el-form-item label="新负责人：" required>
          <el-select v-model="transferForm.newOwner" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in userOptions"
              :key="item.staffId"
              :label="item.staffName"
              :value="item.staffId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="transferForm.keepAsMember">保留【负责人】为销售机会团队成员</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTransfer">确认</el-button>
          <el-button @click="transferVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 弹窗2：批量认领 -->
    <el-dialog title="您正在认领销售线索，请分配销售线索认领信息" v-model="claimVisible" width="550px" append-to-body>
      <el-form label-width="110px" style="padding: 20px 0;">
        <el-form-item label="项目负责人：" required>
          <el-select v-model="claimForm.newManager" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in userOptions"
              :key="item.staffId"
              :label="item.staffName"
              :value="item.staffId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="保留已有项目负责人：" label-width="160px" required class="label-nowrap">
           <el-radio-group v-model="claimForm.keepOldManager">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
           </el-radio-group>
        </el-form-item>
        <div class="claim-tip">
          <el-icon><InfoFilled /></el-icon> 销售线索认领后将转到项目商机。
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitClaim">确认</el-button>
          <el-button @click="claimVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 关联客户联系人弹窗 -->
    <el-dialog title="关联客户联系人" v-model="associateContactVisible" width="900px" append-to-body destroy-on-close>
      <el-table
        v-loading="associateLoading"
        :data="customerContactList"
        @selection-change="handleAssociateSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="联系人" align="center" prop="name" />
        <el-table-column label="部门" align="center" prop="deptName" />
        <el-table-column label="客户名称" align="center" prop="customerName" show-overflow-tooltip />
        <el-table-column label="职位" align="center" prop="position" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" width="120" />
        <el-table-column label="办公电话" align="center" prop="officePhone" width="120" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssociateContact">确 认</el-button>
          <el-button @click="associateContactVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 新建项目联系人抽屉 -->
    <el-drawer v-model="projectContactDrawerOpen" size="70%" direction="rtl" destroy-on-close :with-header="false" class="project-contact-drawer">
      <div class="drawer-header-standard">
        <span class="header-title-text">新建项目联系人</span>
        <el-icon class="close-btn" @click="projectContactDrawerOpen = false"><Close /></el-icon>
      </div>

      <div class="drawer-body-standard">
        <el-form :model="projectContactForm" :rules="projectContactRules" ref="projectContactFormRef" label-width="100px" label-position="right">
          <div class="section-title">基本信息</div>
          <el-row :gutter="32">
            <el-col :span="8">
              <el-form-item label="姓名" prop="name" required>
                <el-input v-model="projectContactForm.name" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人类型" prop="contactType" required>
                <el-radio-group v-model="projectContactForm.contactType">
                  <el-radio value="公司职员">公司职员</el-radio>
                  <el-radio value="关系资源人">关系资源人</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别" prop="sex" required>
                <el-radio-group v-model="projectContactForm.sex">
                  <el-radio value="男">男</el-radio>
                  <el-radio value="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="8">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="projectContactForm.age" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="籍贯" prop="nativePlace">
                <el-input v-model="projectContactForm.nativePlace" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker v-model="projectContactForm.birthday" type="date" placeholder="选择日期" style="width: 100%" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="描述" prop="description">
                <el-input v-model="projectContactForm.description" type="textarea" :rows="3" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="section-title">办公信息</div>
          <el-row :gutter="32">
            <el-col :span="8">
              <el-form-item label="在职状态" prop="status" required>
                <el-radio-group v-model="projectContactForm.status">
                  <el-radio value="在职">在职</el-radio>
                  <el-radio value="离职">离职</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码" prop="phonenumber" required>
                <el-input v-model="projectContactForm.phonenumber" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="部门" prop="deptName" required>
                <el-input v-model="projectContactForm.deptName" placeholder="请输入部门" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="8">
              <el-form-item label="职位" prop="position" required>
                <el-input v-model="projectContactForm.position" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="办公座机" prop="officePhone">
                <el-input v-model="projectContactForm.officePhone" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="16">
              <el-form-item label="办公地址" prop="provinceCity">
                <div style="display: flex; gap: 12px; width: 100%;">
                  <el-cascader
                    v-model="projectContactForm.provinceCity"
                    :options="provinceCityOptions"
                    :props="{ value: 'areaName', label: 'areaName', children: 'children', checkStrictly: true }"
                    placeholder="请选择"
                    style="flex: 0 0 200px;"
                    clearable
                  />
                  <el-input v-model="projectContactForm.addressDetail" placeholder="请输入" style="flex: 1;" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="工作内容" prop="jobContent">
                <el-input v-model="projectContactForm.jobContent" type="textarea" :rows="3" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="section-title">项目决策</div>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="项目角色" prop="projectRole">
                <el-select v-model="projectContactForm.projectRole" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="item in projectRoleOptions"
                    :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="isKeyPerson">
                <el-select v-model="projectContactForm.isKeyPerson" placeholder="请选择" style="width: 100%">
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="公关情况" prop="prCondition">
                <el-input v-model="projectContactForm.prCondition" type="textarea" :rows="3" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="drawer-footer-standard">
        <el-button type="primary" @click="submitProjectContact" class="btn-save">保 存</el-button>
        <el-button @click="projectContactDrawerOpen = false" class="btn-cancel">取 消</el-button>
      </div>
    </el-drawer>

    <!-- 销售线索新增/编辑抽屉 -->
    <el-drawer
      v-model="drawerOpen"
      :title="drawerTitle"
      size="70%"
      class="leads-drawer"
      :with-header="false"
    >
      <div class="drawer-header">
        <div class="header-title">
          <span class="main-title">销售线索</span>
          <span class="sub-title">(3个月以上出结果或金额不明确的项目信息，计入：销售线索)</span>
        </div>
        <el-button link icon="Close" @click="cancelForm" class="close-btn"></el-button>
      </div>

      <div class="drawer-content">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" label-position="left">
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-title">基本信息</div>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="归属公司" prop="companyNo">
                  <el-select v-model="form.companyNo" placeholder="请选择" filterable style="width: 100%" clearable>
                    <el-option
                      v-for="item in companyOptions"
                      :key="'c_' + item.companyCode"
                      :label="item.companyName"
                      :value="item.companyCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户名称" prop="customerNo">
                  <el-select v-model="form.customerNo" placeholder="请选择" filterable style="width: 100%" @change="handleCustomerChange">
                    <el-option
                      v-for="item in customerOptions"
                      :key="item.customerNo"
                      :label="item.customerName"
                      :value="item.customerNo"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="项目负责人" prop="leader">
                  <el-select v-model="form.leader" placeholder="请选择" filterable style="width: 100%" @change="handleLeaderChange">
                    <el-option
                      v-for="item in userOptions"
                      :key="item.staffId"
                      :label="item.staffName"
                      :value="item.staffId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectName" required>
                  <el-input v-model="form.projectName" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="金额(万)" prop="projectBudget" required>
                  <el-input v-model="form.projectBudget" placeholder="请输入" type="number">
                     <template #append>万</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="赢单率(%)" prop="winRate" required>
                  <el-input v-model="form.winRate" placeholder="请输入" type="number">
                     <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="立项时间" prop="expectedCompletionTime" required>
                  <el-date-picker v-model="form.expectedCompletionTime" type="date" placeholder="请选择" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="成交时间" prop="approvalDate">
                  <el-date-picker v-model="form.approvalDate" type="date" placeholder="请选择" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="营销活动" prop="marketingActivityName">
                  <el-select v-model="form.marketingActivityName" placeholder="请选择" style="width: 100%" clearable>
                     <el-option label="" value="" disabled />
                   </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 项目信息 -->
          <div class="form-section">
            <div class="section-title">项目信息</div>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="项目级别" prop="projectLevel">
                  <el-select v-model="form.projectLevel" placeholder="请选择" style="width: 100%" clearable filterable>
                     <el-option
                       v-for="item in projectLevelOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"
                     />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目区域" prop="projectArea" required>
                  <el-input v-model="form.projectArea" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="采购方式" prop="procurementMethod">
                  <el-select v-model="form.procurementMethod" placeholder="请选择" style="width: 100%" clearable filterable>
                     <el-option
                       v-for="item in procurementMethodOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"
                     />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="信息来源" prop="infoSource">
                  <el-select v-model="form.infoSource" placeholder="请选择" style="width: 100%" clearable filterable>
                     <el-option
                       v-for="item in infoSourceOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"
                     />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="24">
                <el-form-item label="采购内容" prop="purchaseContent" required>
                  <el-input v-model="form.purchaseContent" type="textarea" :rows="3" placeholder="请输入采购内容" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="24">
                <el-form-item label="项目描述" prop="projectDescription" required>
                  <el-input v-model="form.projectDescription" type="textarea" :rows="3" placeholder="请输入项目描述" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="24">
                <el-form-item label="竞争对手" prop="competitor">
                  <el-input v-model="form.competitor" type="textarea" :rows="2" placeholder="请输入竞争对手" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 附件 -->
          <div class="form-section">
            <div class="section-title attachment-header">
              <span>附件</span>
              <el-upload
                :action="uploadFileUrl"
                :headers="headers"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
                multiple
                class="upload-btn"
              >
                <el-button link type="primary" icon="Upload">上传附件</el-button>
              </el-upload>
            </div>
            <el-table :data="fileList" border class="at-table">
               <el-table-column label="文件名称" prop="name" show-overflow-tooltip />
               <el-table-column label="文件类型" prop="type" width="120" align="center" />
               <el-table-column label="上传时间" prop="uploadTime" width="180" align="center" />
               <el-table-column label="操作" width="100" align="center">
                  <template #default="scope">
                    <el-button link type="danger" @click="handleDeleteFile(scope.$index)">删除</el-button>
                  </template>
               </el-table-column>
               <template #empty>
                 <div class="empty-text">暂无数据</div>
               </template>
            </el-table>
          </div>
        </el-form>
      </div>

      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancelForm">取消</el-button>
      </div>
    </el-drawer>

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

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

            <!-- 基本信息 Tab -->
            <div v-show="activeLeftTab === 'info'" class="tab-content">
              <div class="info-section">
                <div class="section-header">
                  <span class="section-label">基本信息</span>
                  <el-button type="primary" size="small" @click="handleEditFromDetail"><el-icon style="margin-right:4px;vertical-align:-2px;"><Edit /></el-icon>编 辑</el-button>
                </div>
                <div class="info-row-item">
                  <span class="info-label">项目名称</span>
                  <span class="info-value">{{ detailData.projectName }}</span>
                </div>
                <div class="info-grid">
                  <div class="info-item"><span class="info-label">归属公司</span><span class="info-value">{{ findCompanyName(detailData.companyNo) }}</span></div>
                  <div class="info-item"><span class="info-label">客户名称</span><span class="info-value">{{ detailData.customerName }}</span></div>
                  <div class="info-item"></div> <!-- 占位 -->
                </div>
                <div class="info-grid">
                  <div class="info-item"><span class="info-label">行业</span><span class="info-value">{{ findIndustryName(detailData.profession) }}</span></div>
                  <div class="info-item"><span class="info-label">部门</span><span class="info-value">{{ findDeptName(detailData.deptNo) }}</span></div>
                  <div class="info-item"><span class="info-label">营销活动</span><span class="info-value">{{ detailData.marketingActivityName }}</span></div>
                </div>
                <div class="info-grid">
                  <div class="info-item"><span class="info-label">金额(万)</span><span class="info-value">{{ Number(detailData.projectBudget || 0).toFixed(2) }}</span></div>
                  <div class="info-item"><span class="info-label">赢单率(%)</span><span class="info-value">{{ detailData.winRate ? detailData.winRate + '%' : '' }}</span></div>
                  <div class="info-item"><span class="info-label">立项时间</span><span class="info-value">{{ parseTime(detailData.expectedCompletionTime, '{y}-{m}-{d}') }}</span></div>
                </div>
                <div class="info-grid">
                  <div class="info-item"><span class="info-label">成单时间</span><span class="info-value">{{ parseTime(detailData.approvalDate, '{y}-{m}-{d}') }}</span></div>
                  <div class="info-item"><span class="info-label">项目状态</span><span class="info-value"><dict-tag :options="saleStatusOptions" :value="detailData.status" /></span></div>
                  <div class="info-item"></div> <!-- 占位 -->
                </div>
              </div>

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

            <!-- 项目联系人 Tab -->
            <div v-show="activeLeftTab === 'contact'" class="tab-content">
              <div class="contact-section">
                <div class="contact-header">
                  <el-dropdown trigger="hover" @command="handleContactCommand">
                    <el-button type="primary" size="small" icon="Plus">
                      新建联系人 <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="associate">关联客户联系人</el-dropdown-item>
                        <el-dropdown-item command="create">新建联系人</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <el-table :data="contactList" border class="contact-table" v-loading="contactLoading">
                  <el-table-column label="姓名" align="center" prop="name" min-width="100" />
                  <el-table-column label="性别" align="center" prop="sex" width="80">
                    <template #default="scope">
                      {{ scope.row.sex === '0' ? '男' : scope.row.sex === '1' ? '女' : (scope.row.sex || '') }}
                    </template>
                  </el-table-column>
                  <el-table-column label="部门" align="center" prop="department" width="120" />
                  <el-table-column label="职位" align="center" prop="position" min-width="120" show-overflow-tooltip />
                  <el-table-column label="项目角色" align="center" prop="projectRole" width="120" />
                  <el-table-column label="是否关键人" align="center" prop="isKeyPerson" width="110">
                    <template #default="scope">
                      <span>{{ scope.row.isKeyPerson ? '是' : '否' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="140" fixed="right">
                    <template #default="scope">
                      <el-button link type="primary" size="small">编辑</el-button>
                      <el-button link type="danger" size="small">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-empty v-if="!contactLoading && (!contactList || contactList.length === 0)" description="暂无数据" :image-size="60" />
              </div>
            </div>

            <!-- 结算分析 Tab -->
            <div v-show="activeLeftTab === 'analysis'" class="tab-content">
              <div class="analysis-section">
                <div class="analysis-form">
                  <!-- 成交结果 -->
                  <div class="analysis-row">
                    <span class="form-label">成交结果</span>
                    <el-radio-group v-model="analysisForm.resultType" class="result-radio">
                      <el-radio value="win">赢单</el-radio>
                      <el-radio value="lose">丢单</el-radio>
                    </el-radio-group>
                    <div style="flex:1"></div>
                    <el-button type="primary" icon="CircleCheck" @click="handleSaveAnalysis">保 存</el-button>
                  </div>

                  <!-- 赢单总结 -->
                  <template v-if="analysisForm.resultType === 'win'">
                    <div class="analysis-row">
                      <span class="form-label">赢单总结</span>
                    </div>
                    <div class="summary-textarea-wrap">
                      <el-input v-model="analysisForm.summary" type="textarea" :rows="4" placeholder="请输入赢单总结" />
                    </div>
                  </template>

                  <!-- 丢单原因 -->
                  <template v-else>
                    <div class="analysis-row">
                      <span class="form-label">丢单原因</span>
                    </div>
                    <div class="summary-textarea-wrap">
                      <el-input v-model="analysisForm.loseReason" type="textarea" :rows="4" placeholder="请输入丢单原因" />
                    </div>
                  </template>

                  <!-- 附件 -->
                  <div class="analysis-row" style="margin-top: 20px;">
                    <span class="form-label">附件</span>
                  </div>
                  <div class="upload-area">
                    <el-upload
                      :action="uploadFileUrl"
                      :headers="headers"
                      :on-success="handleAnalysisUploadSuccess"
                      :show-file-list="false"
                      multiple
                    >
                      <el-button type="primary" icon="Upload">上 传</el-button>
                    </el-upload>
                  </div>

                  <!-- 附件列表展示 -->
                  <div v-if="analysisFileList.length > 0" class="analysis-file-list" style="margin-top:10px;">
                    <el-table :data="analysisFileList" border size="small">
                      <el-table-column label="文件名称" prop="name" show-overflow-tooltip />
                      <el-table-column label="文件类型" prop="type" width="80" align="center" />
                      <el-table-column label="操作" width="100" align="center">
                         <template #default="scope">
                            <el-button link type="danger" @click="handleAnalysisDeleteFile(scope.$index)">删除</el-button>
                         </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </div>

            <!-- 附件 Tab -->
            <div v-show="activeLeftTab === 'attachment'" class="tab-content">
              <div class="attachment-section">
                <el-table :data="detailFileList" border class="attach-table">
                  <el-table-column label="文件名称" prop="name" show-overflow-tooltip />
                  <el-table-column label="文件类型" prop="type" width="120" align="center" />
                  <el-table-column label="上传时间" prop="uploadTime" width="170" align="center" />
                  <el-table-column label="操作" width="120" align="center">
                    <template #default="scope">
                      <el-link :href="scope.row.url" :underline="false" target="_blank" type="primary">下载</el-link>
                    </template>
                  </el-table-column>
                  <template #empty>
                    <div class="empty-text">暂无数据</div>
                  </template>
                </el-table>
              </div>
            </div>

            <!-- 报价单 Tab -->
            <div v-show="activeLeftTab === 'quote'" class="tab-content">
              <div class="quote-section">
                <div v-if="selectedQuote || quoteList.length === 0" class="quote-detail-wrapper">
                  <el-table :data="quoteItemList" border class="quote-item-table" v-loading="quoteItemLoading">
                    <el-table-column label="产品图片" width="100" align="center">
                      <template #default="scope">
                        <el-image v-if="scope.row.productImage"
                                  :src="scope.row.productImage" :preview-src-list="[scope.row.productImage]"
                                  style="width: 50px; height: 50px; border-radius: 4px; object-fit: cover;" fit="cover" preview-teleported />
                        <span v-else class="no-image"></span>
                      </template>
                    </el-table-column>
                    <el-table-column label="产品编号" prop="productCode" width="120" align="center" show-overflow-tooltip />
                    <el-table-column label="产品名称" prop="productName" min-width="150" show-overflow-tooltip />
                    <el-table-column label="单位" prop="unit" width="80" align="center" />
                    <el-table-column label="规格" prop="specification" width="120" align="center" show-overflow-tooltip />
                    <el-table-column label="数量" prop="quantity" width="80" align="center" />
                    <el-table-column label="平台售价" prop="platformPrice" width="110" align="center" />
                    <el-table-column label="最低售价" prop="minPrice" width="110" align="center" />
                    <el-table-column label="报价" width="150" align="center">
                      <template #default="scope">
                        <el-input v-model="scope.row.quotePrice" placeholder="请输入报价" size="small" @input="calcGrossMargin(scope.row)" />
                      </template>
                    </el-table-column>
                    <el-table-column label="毛利率" width="100" align="center">
                      <template #default="scope">
                        <span :class="{ 'margin-low': Number(scope.row.grossMargin) < 10 && scope.row.grossMargin !== undefined }">
                          {{ scope.row.grossMargin !== undefined ? scope.row.grossMargin + '%' : '' }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120" align="center" fixed="right">
                      <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleSaveQuoteItem(scope.row)">保存</el-button>
                        <el-button link type="info" size="small" @click="handleDeleteQuoteItem(scope.row)" style="color: #94a3b8;">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                
              </div>
            </div>
          </div>

          <!-- 右侧侧边栏 -->
          <div class="detail-right">
            <!-- 顶部标签页 (红线样式) -->
            <div class="right-tabs">
              <div
                v-for="tab in [{k:'team',n:'团队成员'},{k:'followup',n:'跟进记录'},{k:'log',n:'操作日志'},{k:'manage',n:'管理信息'}]"
                :key="tab.k"
                :class="['right-tab-item', { active: activeRightTab === tab.k }]"
                @click="activeRightTab = tab.k"
              >{{ tab.n }}</div>
            </div>

            <div class="right-tab-content scroll-y">
              <!-- 团队成员 Tab -->
              <div v-show="activeRightTab === 'team'">
                <div class="team-header">
                  <span class="team-title">团队成员 ({{ teamMembers.length }})</span>
                  <el-icon class="add-icon" @click="handleAddMember"><Plus /></el-icon>
                </div>
                <div class="team-search">
                  <el-input v-model="memberSearchKeyword" placeholder="请输入成员" prefix-icon="Search" size="small" clearable />
                </div>
                <div class="team-list">
                  <div v-for="(member, idx) in filteredTeamMembers" :key="idx" class="team-item">
                    <div class="member-avatar">
                      <el-avatar :size="36" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                    </div>
                    <div class="member-info">
                      <div class="info-top">
                        <span class="member-name">{{ member.memberName || member.staffName || member.realName }}{{ member.deptName ? '/' + member.deptName : '' }}</span>
                        <el-tag v-if="member.izManager === 1" size="small" type="success" effect="plain" class="leader-tag">负责人</el-tag>
                        <span class="role-desc">{{ member.roleName }}</span>
                        <span class="permission-desc">{{ member.permission }}</span>
                      </div>
                    </div>
                    <div class="member-actions">
                      <el-button link class="btn-edit" size="small" @click="handleMemberEdit(member)">编辑</el-button>
                      <el-button link class="btn-delete" size="small" @click="handleRemoveMember(member)">删除</el-button>
                    </div>
                  </div>
                </div>
                <el-empty v-if="!filteredTeamMembers || filteredTeamMembers.length === 0" description="暂无团队成员" :image-size="60" />
              </div>

              <!-- 跟进记录 Tab -->
              <div v-show="activeRightTab === 'followup'">
                <div class="followup-actions">
                  <el-button type="primary" link icon="Plus" @click="handleNewFollowup">新建跟进记录</el-button>
                  <div class="filter-item">
                    <span class="filter-label">拜访方式</span>
                    <el-select v-model="followupQuery.visitType" placeholder="请选择" size="small" style="width: 100px" @change="loadFollowupList">
                      <el-option v-for="dict in visitTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                  </div>
                </div>

                <div class="followup-list" v-loading="followupLoading">
                  <div v-if="followupList && followupList.length > 0">
                    <div v-for="(record, idx) in followupList" :key="idx" class="followup-item">
                      <div class="followup-header">
                        <span class="visitor-name">{{ record.visitor || record.createByName || findUserName(record.createBy) }}</span>
                        <span class="visit-time">{{ parseTime(record.callDate || record.createTime, '{y}-{m}-{d}') }}</span>
                        <el-tag size="small" type="success" effect="plain">{{ findVisitTypeName(record.callTypeCode) }}</el-tag>
                      </div>
                      <div class="followup-body">
                        <div class="content-row">
                          <span class="label">拜访目的：</span>
                          <div class="content-text">{{ record.callAim || '-' }}</div>
                        </div>
                        <div class="content-row">
                          <span class="label">跟进情况：</span>
                          <div class="content-text">{{ record.followUpCondition || '-' }}</div>
                        </div>
                        <!-- 图片展示 -->
                        <div v-if="record.recordPicture" class="content-row no-label">
                          <div class="followup-images">
                            <el-image
                              v-for="(img, i) in record.recordPicture.split(',')"
                              :key="i"
                              :src="img.startsWith('http') ? img : (imgUrlPrefix + img)"
                              :preview-src-list="record.recordPicture.split(',').map(url => url.startsWith('http') ? url : (imgUrlPrefix + url))"
                              fit="cover"
                              class="follow-img"
                              preview-teleported
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <el-empty v-else description="暂无记录" :image-size="60" />
                </div>
              </div>

              <!-- 操作日志 -->
              <div v-show="activeRightTab === 'log'">
                 <div class="log-list" v-loading="logLoading">
                    <div v-for="(log, index) in logList" :key="index" class="log-item">
                       <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="logList.length === 0 && !logLoading" class="empty-data" style="margin-top: 50px;">
                       <el-empty description="暂无操作日志" :image-size="60" />
                    </div>
                 </div>
              </div>

              <!-- 管理信息 -->
              <div v-show="activeRightTab === 'manage'" class="manage-info">
                 <div class="manage-grid" style="grid-template-columns: 1fr 1fr; gap: 15px 20px;">
                    <div class="manage-item"><span class="manage-label">创建人</span><span class="manage-value">{{ detailData.createByName || findUserName(detailData.createBy) }}</span></div>
                    <div class="manage-item"><span class="manage-label">创建日期</span><span class="manage-value">{{ parseTime(detailData.createTime, '{y}-{m}-{d}') }}</span></div>
                    <div class="manage-item"><span class="manage-label">修改日期</span><span class="manage-value">{{ parseTime(detailData.updateTime, '{y}-{m}-{d}') }}</span></div>
                    <div class="manage-item"><span class="manage-label">最后更新</span><span class="manage-value">{{ detailData.updateByName || findUserName(detailData.updateBy) }}</span></div>
                 </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 新建跟进记录对话框 -->
    <el-dialog title="跟进记录" v-model="followupDialogOpen" width="700px" append-to-body destroy-on-close class="followup-dialog">
      <el-form ref="followupFormRef" :model="followupForm" :rules="followupRules" label-width="100px">
        <div class="dlg-customer-row">客户：<span class="hl">{{ detailData.customerName || '-' }}</span></div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拜访人" prop="visitor">
              <el-select v-model="followupForm.visitor" placeholder="请选择" style="width: 100%" filterable>
                <el-option v-for="item in teamMembers" :key="item.userNo || item.id" :label="item.realName" :value="item.realName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="随访人" prop="accompany">
              <el-select v-model="followupForm.accompany" placeholder="请选择" style="width: 100%" filterable clearable>
                <el-option v-for="item in userOptions" :key="item.staffId" :label="item.staffName" :value="item.staffName" />
              </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="followupForm.visitType" placeholder="请选择" style="width: 100%">
                <el-option v-for="dict in visitTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拜访时间" prop="visitDate">
              <el-date-picker v-model="followupForm.visitDate" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="下次拜访时间">
          <el-date-picker v-model="followupForm.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="followupForm.purpose" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>

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

        <el-form-item label="记录图片">
          <image-upload v-model="followupForm.recordPicture" :limit="9" :isShowTip="false" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFollowup" :loading="followupSubmitting" style="padding: 8px 24px;">确 认</el-button>
          <el-button @click="followupDialogOpen = false" style="padding: 8px 24px;">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 团队成员管理弹窗 -->
    <el-dialog
      :title="memberEditVisible ? '编辑团队成员' : '添加团队成员'"
      v-model="memberDialogVisible"
      width="440px"
      append-to-body
      destroy-on-close
      class="team-member-dialog"
    >
      <el-form label-width="100px" label-position="left">
        <!-- 添加人员 -->
        <el-form-item label="人员姓名：" v-if="memberAddVisible">
          <el-select v-model="memberAddForm.staffId" placeholder="请选择人员" filterable style="width: 100%">
            <el-option v-for="user in userOptions" :key="user.staffId" :label="user.staffName" :value="user.staffId" />
          </el-select>
        </el-form-item>
        
        <!-- 编辑人员姓名显示 -->
        <el-form-item label="人员姓名：" v-if="memberEditVisible">
          <span style="color: #333; font-weight: 500;">{{ memberEditForm.staffName }}{{ memberEditForm.deptName ? '/' + memberEditForm.deptName : '' }}</span>
        </el-form-item>

        <el-form-item label="成员角色：">
          <el-select v-if="memberEditVisible" v-model="memberEditForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="role in memberRoleOptions" :key="role.dictValue" :label="role.dictLabel" :value="role.dictValue" />
          </el-select>
          <el-select v-else v-model="memberAddForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="role in memberRoleOptions" :key="role.dictValue" :label="role.dictLabel" :value="role.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item label="权限：">
          <el-radio-group v-if="memberEditVisible" v-model="memberEditForm.permission">
            <el-radio 
              v-for="p in permissionOptions" 
              :key="p.dictValue" 
              :value="p.dictValue"
            >{{ p.dictLabel }}</el-radio>
          </el-radio-group>
          <el-radio-group v-else v-model="memberAddForm.permission">
            <el-radio 
              v-for="p in permissionOptions" 
              :key="p.dictValue" 
              :value="p.dictValue"
            >{{ p.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right; padding-right: 10px;">
          <el-button type="primary" @click="memberEditVisible ? submitMemberEdit() : submitMemberAdd()" style="padding: 8px 24px;">确 认</el-button>
          <el-button @click="memberEditVisible = false; memberAddVisible = false" style="padding: 8px 24px;">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SalesLeads">
import { ref, reactive, computed, onMounted, watch, getCurrentInstance, nextTick } from 'vue';
import { useUserStore } from "@/store/modules/user";
import { listLeads, delLeads, getLeads, addLeads, updateLeads, claimLeads, transferLeads } from '@/api/saleManage/leads/index';
import { listTeamMember, addTeamMember, updateTeamMember, delTeamMember } from '@/api/saleManage/leads/teamMemberApi';
import { selectStaffOptionList } from "@/api/system/comStaff/index";
import { listCompanyOption } from "@/api/customer/customerInfo/index";
import { listCommonDict } from "@/api/customer/customerDict";
import { listDept } from "@/api/system/dept/index";
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listRecord, addRecord } from "@/api/visit/record";
import { listContact, addContact, updateContact } from "@/api/customer/crmContact";
import { InfoFilled, Close, Upload, Plus, Edit, Download, Search, UserFilled, ArrowDown } from '@element-plus/icons-vue';
import { listByIds } from '@/api/system/oss/index';
import { globalHeaders } from '@/utils/request';
import { getSalesResultAnalyzeByObjectNo, addSalesResultAnalyze, updateSalesResultAnalyze } from '@/api/saleManage/leads/salesResultAnalyze';
import { listOperationLog } from '@/api/customer/operationLog';
import { listProvinceWithCities } from '@/api/customer/addressArea';

const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const parseTime = proxy.parseTime || ((time, pattern) => {
  if (!time) return null;
  const date = new Date(time);
  const opt = {
    "y+": date.getFullYear().toString(),
    "m+": (date.getMonth() + 1).toString(),
    "d+": date.getDate().toString()
  };
  return pattern.replace(/(y+|m+|d+)/g, (match) => opt[match[0].toLowerCase() + "+"]);
});

const loading = ref(false);
const total = ref(0);
const leadsList = ref([]);
const dateRange = ref([]);
const multipleSelection = ref([]);
const totalAmount = ref(0.00);

// 操作日志相关
const logList = ref([]);
const logLoading = ref(false);

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

const formatLogAction = (log) => {
  return getLogActionText(log.actionType);
};

const translateDetails = (details) => {
  if (!details) return '';
  if (details.includes('projectStatus') || details.includes('projectSchedule') || details.includes('项目商机') || details.includes('修改销售线索') || details.includes('销售线索')) {
    return '销售线索';
  }
  const fieldMap = {
    'projectName': '项目名称',
    'projectStatus': '项目状态',
    'projectSchedule': '项目进度',
    'status': '状态'
  };
  let result = details;
  Object.keys(fieldMap).forEach(key => {
    if (result.includes(key)) result = result.replace(key, fieldMap[key]);
  });
  return result;
};

const formatLogTarget = (log) => {
  if (!log.targetObject) return '';
  let details = log.actionDetails || '';
  if (details.includes('projectSchedule') || details.includes('projectStatus') || details.includes('修改销售线索') || details.includes('项目商机') || details.includes('销售线索')) {
    let stepName = log.targetObject;
    if (log.targetObject === detailData.projectName) {
      const match = details.match(/\d/);
      if (match && saleStatusOptions.value) {
        const dict = saleStatusOptions.value.find(o => String(o.dictValue) === String(match[0]));
        stepName = dict ? dict.dictLabel : '';
      } else stepName = '';
    } else if (stepName.includes('进度状态变更')) {
      const parts = stepName.split(',');
      if (parts.length > 1 && /^\d+$/.test(parts[1]) && saleStatusOptions.value) {
        const dict = saleStatusOptions.value.find(o => String(o.dictValue) === String(parts[1]));
        if (dict) return `进度状态变更,${dict.dictLabel}`;
      }
      return stepName;
    } else if (/^\d+$/.test(stepName) && saleStatusOptions.value) {
        const dict = saleStatusOptions.value.find(o => String(o.dictValue) === String(stepName));
        if (dict) return `进度状态变更,${dict.dictLabel}`;
    }
    if (stepName && !stepName.includes('进度状态变更')) return `进度状态变更,${stepName}`;
    return stepName || '';
  }
  return log.targetObject;
};

const fetchOperationLogs = async (id) => {
  if (!id) return;
  logLoading.value = true;
  try {
    const res = await listOperationLog({ dataType: 1, objectNo: id });
    logList.value = res.data || [];
  } catch (error) {
  } finally {
    logLoading.value = false;
  }
};

const companyOptions = ref([]); // 公司选项
const userOptions = ref([]); // 用户选项
const deptOptions = ref([]); // 部门选项
const customerOptions = ref([]); // 客户选项
const saleStatusOptions = ref([]); // 销售状态选项
const timeQueryTypeOptions = ref([]); // 时间查询类型选项
const projectLevelOptions = ref([]); // 项目级别选项
const procurementMethodOptions = ref([]); // 采购方式选项
const infoSourceOptions = ref([]); // 信息来源选项
const industryOptions = ref([]); // 行业分类选项
const memberRoleOptions = ref([]); // 团队角色选项
const permissionOptions = ref([]); // 权限字典选项

const transferVisible = ref(false);
const claimVisible = ref(false);
const drawerOpen = ref(false);
const drawerTitle = ref('');
const formRef = ref(null);

const followupLoading = ref(false);
const followupList = ref([]);
const followupQuery = reactive({
  visitType: undefined
});
const visitTypeOptions = ref([]); // 拜访方式选项
const followupDialogOpen = ref(false);
const followupFormRef = ref(null);
const followupSubmitting = ref(false);
const followupForm = reactive({
  visitor: undefined,
  accompany: undefined,
  visitType: undefined,
  visitDate: undefined,
  nextVisitDate: undefined,
  purpose: undefined,
  progress: undefined,
  recordPicture: undefined
});
const followupRules = reactive({
  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 detailDrawerOpen = ref(false);
const detailLoading = ref(false);
const detailData = reactive({
  id: undefined,
  projectName: undefined,
  companyNo: undefined,
  customerName: undefined,
  projectBudget: undefined,
  winRate: undefined,
  expectedCompletionTime: undefined,
  status: undefined,
  profession: undefined,
  deptNo: undefined,
  marketingActivityName: undefined,
  infoSource: undefined,
  projectLevel: undefined,
  projectArea: undefined,
  procurementMethod: undefined,
  purchaseContent: undefined,
  competitor: undefined,
  projectDescription: undefined,
  fileList: [],
  createBy: undefined,
  createTime: undefined,
  updateBy: undefined,
  updateTime: undefined,
  leader: undefined,
  leaderName: undefined,
  projectNo: undefined,
});

// 左侧标签页配置
const leftTabs = [
  { key: 'info', label: '项目信息' },
  { key: 'contact', label: '项目联系人' },
  { key: 'analysis', label: '结算分析' },
  { key: 'attachment', label: '附件' },
  { key: 'quote', label: '报价单' }
];
const activeLeftTab = ref('info');

const rightTabs = [
  { key: 'team', label: '团队成员' },
  { key: 'followup', label: '跟进记录' },
  { key: 'log', label: '操作日志' },
  { key: 'manage', label: '管理信息' }
];
const activeRightTab = ref('team');

// 团队成员数据
const teamMembers = ref([]);

// 编辑团队成员弹窗
const memberEditVisible = ref(false);
const memberEditForm = reactive({
  staffId: undefined,
  staffName: '',
  role: '',
  permission: '0'
});

// 附件列表数据容器
const fileList = ref([]);
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload');
const imgUrlPrefix = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/download/');
const headers = ref(globalHeaders());

let editingMemberIndex = -1;

// 添加团队成员弹窗
const memberAddVisible = ref(false);
const memberAddForm = reactive({
  staffId: undefined,
  role: '',
  permission: '0'
});

const memberDialogVisible = computed({
  get: () => memberEditVisible.value || memberAddVisible.value,
  set: (val) => {
    if (!val) {
      memberEditVisible.value = false;
      memberAddVisible.value = false;
    }
  }
});

// 项目联系人数据
const contactList = ref([]);
const contactLoading = ref(false);

const associateContactVisible = ref(false);
const associateLoading = ref(false);
const customerContactList = ref([]);
const associateSelection = ref([]);

const projectContactDrawerOpen = ref(false);
const projectContactFormRef = ref(null);
const projectContactForm = reactive({
  name: '',
  contactType: '1',
  sex: '0',
  age: '',
  nativePlace: '',
  birthday: '',
  description: '',
  status: '1',
  phonenumber: '',
  deptName: '',
  position: '',
  officePhone: '',
  provinceCity: [],
  addressDetail: '',
  jobContent: '',
  projectRole: '',
  isKeyPerson: undefined,
  prCondition: '',
  companyNo: undefined,
  customerNo: undefined,
  customName: undefined
});

const provinceCityOptions = ref([]);
const projectRoleOptions = ref([]);

const projectContactRules = reactive({
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  contactType: [{ required: true, message: '请选择联系人类型', trigger: 'change' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  status: [{ required: true, message: '请选择在职状态', trigger: 'change' }],
  phonenumber: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }],
  deptName: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  position: [{ required: true, message: '职位不能为空', trigger: 'blur' }]
});

const handleAssociateSelectionChange = (selection) => {
  associateSelection.value = selection;
};

// 结算分析表单数据
const analysisForm = reactive({
  id: undefined,
  resultType: 'win', // win-赢单, lose-丢单
  summary: undefined,
  loseReason: undefined,
  fileNo: undefined,
});
// 结算分析附件列表
const analysisFileList = ref([]);

// 附件加载状态
const fileLoading = ref(false);

// 报价单数据
const quoteList = ref([]);
const quoteLoading = ref(false);
// 选中的报价单
const selectedQuote = ref(null);
// 报价单明细（产品列表）
const quoteItemList = ref([]);
const quoteItemLoading = ref(false);

const form = reactive({
  id: undefined,
  izClue: 1, // 默认线索
  projectNo: undefined,
  companyNo: undefined,
  deptNo: undefined,
  customerNo: undefined,
  customerName: undefined,
  projectName: undefined,
  projectType: undefined,
  projectBudget: undefined,
  winRate: undefined,
  approvalDate: undefined,
  expectedCompletionTime: undefined,
  projectLevel: undefined,
  profession: undefined,
  businessPersonnel: undefined,
  submitter: undefined,
  projectArea: undefined,
  procurementMethod: undefined,
  infoSource: undefined,
  competitor: undefined,
  projectDescription: undefined,
  fileNo: undefined,
  leader: undefined,
  leaderName: undefined,
  activityNo: undefined,
  marketingActivityName: undefined,
  productSupport: undefined,
  projectSchedule: undefined,
  publicBiddingDeadline: undefined,
  purchaseContent: undefined,
  status: '1', // 依据字典，默认跟进中
  remark: undefined,
  fileList: []
});

// 监听文件编号变化，同步拉取详细信息展示在表格
watch(() => form.fileNo, async (val) => {
  if (val) {
    if (fileList.value.length === 0 || listToString(fileList.value) !== val) {
       const res = await listByIds(val);
       fileList.value = res.data.map(item => ({
         name: item.originalName,
         url: item.url,
         ossId: item.ossId,
         type: getFileType(item.originalName),
         uploadTime: item.createTime
       }));
    }
  } else {
    fileList.value = [];
  }
}, { immediate: true });

// 监听详情数据的文件编号，同步拉取详细信息
const detailFileList = ref([]);
watch(() => detailData.fileNo, async (val) => {
  if (val) {
    const res = await listByIds(val);
    detailFileList.value = res.data.map(item => ({
      name: item.originalName,
      url: item.url,
      ossId: item.ossId,
      type: getFileType(item.originalName),
      uploadTime: item.createTime
    }));
  } else {
    detailFileList.value = [];
  }
});

// 获取文件后缀
const getFileType = (name) => {
  if (!name) return '未知';
  const parts = name.split('.');
  return parts.length > 1 ? parts[parts.length - 1].toUpperCase() : '文件';
};

// 对象转成指定字符串分隔
const listToString = (list, separator = ',') => {
  let strs = '';
  list.forEach((item) => {
    if (item.ossId) {
      strs += item.ossId + separator;
    }
  });
  return strs != '' ? strs.substring(0, strs.length - 1) : '';
};

// 附件上传成功
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    const newFile = {
      name: res.data.fileName,
      url: res.data.url,
      ossId: res.data.ossId,
      type: getFileType(res.data.fileName),
      uploadTime: parseTime(new Date())
    };
    fileList.value.push(newFile);
    form.fileNo = listToString(fileList.value);
    proxy.$modal.msgSuccess("上传成功");
  } else {
    proxy.$modal.msgError(res.msg);
  }
};

// 删除附件
const handleDeleteFile = (index) => {
  fileList.value.splice(index, 1);
  form.fileNo = listToString(fileList.value);
};

const rules = reactive({
  companyNo: [{ required: true, message: '归属公司不能为空', trigger: 'change' }],
  customerNo: [{ required: true, message: '客户名称不能为空', trigger: 'change' }],
  leader: [{ required: true, message: '项目负责人不能为空', trigger: 'change' }],
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  projectBudget: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
  winRate: [{ required: true, message: '赢单率不能为空', trigger: 'blur' }],
  expectedCompletionTime: [{ required: true, message: '立项时间不能为空', trigger: 'change' }],
  projectArea: [{ required: true, message: '项目区域不能为空', trigger: 'blur' }],
  purchaseContent: [{ required: true, message: '采购内容不能为空', trigger: 'blur' }],
  projectDescription: [{ required: true, message: '项目描述不能为空', trigger: 'blur' }],
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  companyNo: undefined,
  projectName: undefined,
  customerName: undefined,
  leader: undefined,
  deptNo: undefined,
  productSupport: undefined,
  status: undefined,
  timeType: undefined
});

const transferForm = reactive({
  newOwner: '',
  keepAsMember: true
});

const claimForm = reactive({
  newManager: '',
  keepOldManager: true
});

const getList = async () => {
  loading.value = true;
  try {
    const res = await listLeads(proxy.addDateRange(queryParams, dateRange.value));
    leadsList.value = res.rows || [];
    total.value = res.total || 0;
    // 计算总金额
    totalAmount.value = leadsList.value.reduce((acc, cur) => acc + (Number(cur.projectBudget) || 0), 0);
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  loadTeamMembers(id);
  loadFollowupList();
};

const handleRightTabChange = (name) => {
  activeRightTab.value = name;
  if (name === 'followup') {
    loadFollowupList();
  }
};

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection;
};

const handleTransfer = () => {
  transferVisible.value = true;
};

/** 单条认领 */
const handleClaim = async (row) => {
  try {
    await claimLeads({
      ids: [row.id],
      leader: userStore.userId,
      leaderName: userStore.nickname
    });
    proxy.$modal.msgSuccess("认领成功");
    getList();
  } catch (e) {
  }
};

const handleBatchClaim = () => {
  if (multipleSelection.value.length === 0) {
    proxy.$modal.msgWarning("请先选择要认领的线索");
    return;
  }
  claimVisible.value = true;
};

const submitTransfer = async () => {
  if (!transferForm.newOwner) {
    proxy.$modal.msgWarning("请选择新负责人");
    return;
  }
  const ids = multipleSelection.value.map(item => item.id);
  const ownerUser = userOptions.value.find(u => u.staffId == transferForm.newOwner || u.userId == transferForm.newOwner);
  const leaderName = ownerUser ? ownerUser.staffName : '';
  try {
    await transferLeads({ ids, leader: transferForm.newOwner, leaderName: leaderName });
    proxy.$modal.msgSuccess("转移成功");
    transferVisible.value = false;
    getList();
  } catch (e) {
    /* API error handled by request interceptor */
    }
};

const submitClaim = async () => {
  if (!claimForm.newManager) {
    proxy.$modal.msgWarning("请选择项目负责人");
    return;
  }
  const ids = multipleSelection.value.map(item => item.id);
  // 根据用户ID查找用户名称
  const managerUser = userOptions.value.find(u => u.staffId == claimForm.newManager || u.userId == claimForm.newManager);
  const leaderName = managerUser ? managerUser.staffName : '';
  try {
    await claimLeads({
      ids,
      leader: claimForm.newManager,
      leaderName: leaderName
    });
    proxy.$modal.msgSuccess("认领成功，线索已转为项目商机");
    claimVisible.value = false;
    getList(); // 刷新列表，项目负责人会更新
  } catch (e) {
    /* API error handled by request interceptor */
  }
};

const handleAdd = () => {
  reset();
  drawerTitle.value = "新增销售线索";
  drawerOpen.value = true;
};

/** 客户名称选择变化时，同步绑定客户名称、行业、部门 */
const handleCustomerChange = (customerNo) => {
  if (customerNo) {
    const customer = customerOptions.value.find(item => item.customerNo === customerNo);
    if (customer) {
      form.customerName = customer.customerName;
      form.profession = customer.industryCategoryId || undefined;
      form.deptNo = String(customer.belongDeptId || '');
    }
  } else {
    form.customerName = undefined;
    form.profession = undefined;
    form.deptNo = undefined;
  }
};

/** 负责人选择变化时，同步绑定负责人姓名 */
const handleLeaderChange = (leaderId) => {
  if (leaderId) {
    const staff = userOptions.value.find(item => item.staffId === leaderId);
    if (staff) {
      form.leaderName = staff.staffName;
    }
  } else {
    form.leaderName = undefined;
  }
};

/** 递归查找部门名称 */
const findDeptName = (deptId) => {
  if (!deptId || !deptOptions.value || deptOptions.value.length === 0) return null;
  for (const dept of deptOptions.value) {
    if (dept.deptId == deptId) return dept.deptName;
    if (dept.children && dept.children.length > 0) {
      const found = findDeptInChildren(dept.children, deptId);
      if (found) return found;
    }
  }
  return null;
};

/** 在子节点中递归查找 */
const findDeptInChildren = (children, deptId) => {
  for (const child of children) {
    if (child.deptId == deptId) return child.deptName;
    if (child.children && child.children.length > 0) {
      const found = findDeptInChildren(child.children, deptId);
      if (found) return found;
    }
  }
  return null;
};

/** 获取销售状态名称 */
const getSaleStatusLabel = (status) => {
  if (!saleStatusOptions.value || saleStatusOptions.value.length === 0) return status;
  const item = saleStatusOptions.value.find(i => String(i.dictValue) === String(status));
  return item ? item.dictLabel : status;
};

const reset = () => {
  form.id = undefined;
  form.izClue = 1;
  form.projectNo = undefined;
  form.companyNo = undefined;
  form.deptNo = undefined;
  form.customerNo = undefined;
  form.customerName = undefined;
  form.projectName = undefined;
  form.projectType = undefined;
  form.projectBudget = undefined;
  form.winRate = undefined;
  form.approvalDate = undefined;
  form.expectedCompletionTime = undefined;
  form.projectLevel = undefined;
  form.profession = undefined;
  form.businessPersonnel = undefined;
  form.submitter = undefined;
  form.projectArea = undefined;
  form.procurementMethod = undefined;
  form.infoSource = undefined;
  form.competitor = undefined;
  form.projectDescription = undefined;
  form.fileNo = undefined;
  form.leader = undefined;
  form.leaderName = undefined;
  form.activityNo = undefined;
  form.marketingActivityName = undefined;
  form.productSupport = undefined;
  form.projectSchedule = undefined;
  form.publicBiddingDeadline = undefined;
  form.purchaseContent = undefined;
  form.status = '1';
  form.fileList = [];
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

/** 查询公司列表 */
function getCompanyList() {
  listCompanyOption().then(response => {
    companyOptions.value = response.data;
  });
}

/** 查询员工下拉选项列表 */
function getUserList() {
  selectStaffOptionList().then(response => {
    userOptions.value = response.data;
  });
}

/** 查询部门树形列表 */
function getDeptList() {
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, 'deptId');
  });
}

/** 查询销售状态列表 */
function getSaleStatusList() {
  listCommonDict('J0001').then(response => {
    saleStatusOptions.value = response.data.map(item => ({
      value: String(item.dictValue),
      label: item.dictLabel,
      elTagType: item.listClass,
      elTagClass: item.cssClass
    }));
  });
}

/** 查询时间查询类型列表 */
function getTimeQueryTypeList() {
  listCommonDict('time_query_type').then(response => {
    timeQueryTypeOptions.value = response.data;
  });
}

/** 查询项目级别列表 */
function getProjectLevelList() {
  listCommonDict('L0001').then(response => {
    projectLevelOptions.value = response.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel,
      elTagType: item.listClass,
      elTagClass: item.cssClass
    }));
  });
}

/** 查询采购方式列表 */
function getProcurementMethodList() {
  listCommonDict('X0001').then(response => {
    procurementMethodOptions.value = response.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel,
      elTagType: item.listClass,
      elTagClass: item.cssClass
    }));
  });
}

/** 查询信息来源列表 */
function getInfoSourceList() {
  listCommonDict('X0002').then(response => {
    infoSourceOptions.value = response.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel,
      elTagType: item.listClass,
      elTagClass: item.cssClass
    }));
  });
}

/** 查询客户列表 */
function getCustomerList() {
  listCustomerInfo().then(response => {
    customerOptions.value = response.rows;
  });
}

/** 查询行业分类列表 */
function getIndustryList() {
  listIndustryCategory().then(response => {
    industryOptions.value = response.data;
  });
}

/** 查询团队角色列表 */
function getMemberRoleList() {
  listCommonDict('T0001').then(res => {
    memberRoleOptions.value = res.data || [];
  });
  listCommonDict('team_permission').then(res => {
    permissionOptions.value = res.data || [];
  });
  listCommonDict('visit_type').then(res => {
    visitTypeOptions.value = res.data || [];
  });
}

/** 团队成员搜索关键词 */
const memberSearchKeyword = ref("");
const filteredTeamMembers = computed(() => {
  if (!memberSearchKeyword.value) return teamMembers.value;
  return teamMembers.value.filter(m => m.realName && m.realName.includes(memberSearchKeyword.value));
});

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.id != undefined) {
        updateLeads(form).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          drawerOpen.value = false;
          getList();
        });
      } else {
        addLeads(form).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          drawerOpen.value = false;
          getList();
        });
      }
    }
  });
};

const cancelForm = () => {
  drawerOpen.value = false;
  reset();
};

const handleUpdate = (row) => {
  reset();
  const id = row.id;
  getLeads(id).then(response => {
    Object.assign(form, response.data);
    drawerTitle.value = "修改销售线索";
    drawerOpen.value = true;
  });
};

const handleDetail = (row) => {
  detailLoading.value = true;
  detailDrawerOpen.value = true;
  activeLeftTab.value = 'info';
  activeRightTab.value = 'team';
  getLeads(row.id).then(response => {
    const data = response.data || {};
    Object.assign(detailData, data);
    // 从API加载子项数据
    loadTeamMembers(data.id);
    loadFollowupList();
    loadProjectContacts(); // 加载联系人
    loadAnalysisData(); // 加载结果分析
    fetchOperationLogs(data.id); // 加载操作日志
  }).finally(() => {
    detailLoading.value = false;
  });
};

/** 加载项目联系人列表 */
const loadProjectContacts = async () => {
  if (!detailData.id) return;
  contactLoading.value = true;
  try {
    const params = { 
      customerNo: detailData.customerNo,
      companyNo: detailData.companyNo
    };
    console.log('加载项目联系人参数:', params);
    const res = await listContact(params);
    console.log('项目联系人返回:', res);
    contactList.value = res.rows || [];
  } catch (err) {
    console.error('加载项目联系人失败:', err);
  } finally {
    contactLoading.value = false;
  }
};

/** 加载结果分析数据 */
const loadAnalysisData = async () => {
  if (!detailData.projectNo) {
    console.warn('当前线索缺少项目编号，无法加载结果分析');
    return;
  }
  try {
    const res = await getSalesResultAnalyzeByObjectNo(detailData.projectNo);
    if (res.data) {
      analysisForm.id = res.data.id;
      analysisForm.resultType = res.data.dealResult === 1 ? 'win' : 'lose';
      analysisForm.summary = res.data.winSumUp;
      analysisForm.loseReason = res.data.loseReason;
      analysisForm.fileNo = res.data.fileNo;
      
      // 加载附件详情
      if (analysisForm.fileNo) {
        const ossRes = await listByIds(analysisForm.fileNo);
        analysisFileList.value = ossRes.data.map(item => ({
          name: item.originalName,
          url: item.url,
          ossId: item.ossId,
          type: getFileType(item.originalName),
          uploadTime: item.createTime
        }));
      } else {
        analysisFileList.value = [];
      }
    } else {
      // 重置表单
      analysisForm.id = undefined;
      analysisForm.resultType = 'win';
      analysisForm.summary = undefined;
      analysisForm.loseReason = undefined;
      analysisForm.fileNo = undefined;
      analysisFileList.value = [];
    }
  } catch (err) {
    console.error('加载结果分析失败:', err);
  }
};

/** 保存结果分析数据 */
const handleSaveAnalysis = async () => {
  if (!detailData.id) {
    proxy.$modal.msgError("线索信息不存在");
    return;
  }
  
  const data = {
    id: analysisForm.id,
    dataType: 1, // 1表示线索
    objectNo: detailData.projectNo,
    dealResult: analysisForm.resultType === 'win' ? 1 : 2,
    winSumUp: analysisForm.summary,
    loseReason: analysisForm.loseReason,
    fileNo: analysisForm.fileNo
  };
  
  try {
    if (data.id) {
      await updateSalesResultAnalyze(data);
    } else {
      await addSalesResultAnalyze(data);
    }
    proxy.$modal.msgSuccess("保存成功");
    loadAnalysisData();
  } catch (err) {
    console.error('保存结果分析失败:', err);
  }
};

/** 结果分析附件上传成功 */
const handleAnalysisUploadSuccess = (res) => {
  if (res.code === 200) {
    const newFile = {
      name: res.data.fileName,
      url: res.data.url,
      ossId: res.data.ossId,
      type: getFileType(res.data.fileName),
      uploadTime: parseTime(new Date())
    };
    analysisFileList.value.push(newFile);
    analysisForm.fileNo = listToString(analysisFileList.value);
    proxy.$modal.msgSuccess("上传成功");
  } else {
    proxy.$modal.msgError(res.msg);
  }
};

/** 结果分析删除附件 */
const handleAnalysisDeleteFile = (index) => {
  analysisFileList.value.splice(index, 1);
  analysisForm.fileNo = listToString(analysisFileList.value);
};

/** 从API加载团队成员列表 */
// 加载跟进记录列表
const loadFollowupList = async () => {
  if (!detailData.id) return;
  followupLoading.value = true;
  try {
    const params = {
      objectNo: detailData.id,
      callTypeCode: followupQuery.visitType
    };
    const res = await listRecord(params);
    const rows = res.rows || [];
    
    // 批量处理图片 ID 转 URL
    const allOssIds = rows
      .filter(r => r.recordPicture && !r.recordPicture.startsWith('http'))
      .map(r => r.recordPicture)
      .join(',');
      
    if (allOssIds) {
      const ossRes = await listByIds(allOssIds);
      const ossMap = {};
      ossRes.data.forEach(item => {
        ossMap[item.ossId] = item.url;
      });
      
      rows.forEach(r => {
        if (r.recordPicture && !r.recordPicture.startsWith('http')) {
          const ids = r.recordPicture.split(',');
          r.recordPicture = ids.map(id => ossMap[id] || id).join(',');
        }
      });
    }
    
    followupList.value = rows;
  } catch (err) {
    console.error('加载跟进记录失败:', err);
  } finally {
    followupLoading.value = false;
  }
};

// 打开新建跟进记录弹窗
const handleNewFollowup = () => {
  // 确保人员列表已加载
  if (!userOptions.value || userOptions.value.length === 0) {
    getUserList();
  }
  
  Object.assign(followupForm, {
    visitor: undefined,
    accompany: undefined,
    visitType: undefined,
    visitDate: parseTime(new Date(), '{y}-{m}-{d}'),
    nextVisitDate: undefined,
    purpose: undefined,
    progress: undefined,
    recordPicture: undefined
  });
  followupDialogOpen.value = true;
  nextTick(() => {
    if (followupFormRef.value) followupFormRef.value.clearValidate();
  });
};

// 处理项目联系人下拉指令
const handleContactCommand = (command) => {
  if (command === 'associate') {
    handleAssociateCustomerContact();
  } else if (command === 'create') {
    handleAddProjectContact();
  }
};

/** 关联客户联系人 */
const handleAssociateCustomerContact = () => {
  if (!detailData.customerNo) {
    proxy.$modal.msgWarning("当前线索未关联客户，无法获取联系人");
    return;
  }
  associateContactVisible.value = true;
  associateLoading.value = true;
  listContact({ customerNo: detailData.customerNo }).then(res => {
    customerContactList.value = res.rows || [];
  }).finally(() => {
    associateLoading.value = false;
  });
};

/** 提交关联联系人 */
const submitAssociateContact = async () => {
  if (associateSelection.value.length === 0) {
    proxy.$modal.msgWarning("请至少选择一个联系人");
    return;
  }
  
  try {
    // 遍历选中的联系人，更新它们的 platformCode 为当前线索 ID 实现绑定
    const promises = associateSelection.value.map(contact => {
      return updateContact({
        id: contact.id,
        platformCode: String(detailData.id)
      });
    });
    
    await Promise.all(promises);
    proxy.$modal.msgSuccess(`成功关联 ${associateSelection.value.length} 个联系人`);
    associateContactVisible.value = false;
    // 刷新当前详情的项目联系人列表
    loadProjectContacts(); 
  } catch (err) {
    console.error('关联联系人失败:', err);
  }
};

/** 新建项目联系人 */
const handleAddProjectContact = () => {
  Object.assign(projectContactForm, {
    name: '',
    contactType: '公司职员',
    sex: '男',
    age: undefined,
    nativePlace: '',
    birthday: undefined,
    description: '',
    status: '在职',
    phonenumber: '',
    deptName: '',
    position: '',
    officePhone: '',
    provinceCity: [],
    addressDetail: '',
    jobContent: '',
    projectRole: '',
    isKeyPerson: undefined,
    prCondition: '',
    companyNo: detailData.companyNo,
    customerNo: detailData.customerNo,
    customName: detailData.customerName
  });
  projectContactDrawerOpen.value = true;
};

const submitProjectContact = () => {
  projectContactFormRef.value.validate(async (valid) => {
    if (valid) {
      const province = projectContactForm.provinceCity?.[0] || '';
      const city = projectContactForm.provinceCity?.[1] || '';
      const fullAddress = [province, city, projectContactForm.addressDetail].filter(Boolean).join('');
      const data = {
        name: projectContactForm.name,
        contactType: projectContactForm.contactType,
        sex: projectContactForm.sex,
        age: projectContactForm.age,
        nativePlace: projectContactForm.nativePlace,
        birthday: projectContactForm.birthday,
        characterDesc: projectContactForm.description,
        employmentStatusCode: projectContactForm.status,
        phoneNumber: projectContactForm.phonenumber,
        department: projectContactForm.deptName,
        position: projectContactForm.position,
        landline: projectContactForm.officePhone,
        province: province,
        city: city,
        workAddress: fullAddress,
        workDesc: projectContactForm.jobContent,
        projectRole: projectContactForm.projectRole,
        izCruxPerson: projectContactForm.isKeyPerson ? '是' : '否',
        authorityDesc: projectContactForm.prCondition,
        companyNo: projectContactForm.companyNo,
        customerNo: projectContactForm.customerNo,
        customName: projectContactForm.customName,
      };
      
      try {
        console.log('新增联系人数据:', data);
        await addContact(data);
        proxy.$modal.msgSuccess("保存成功");
        projectContactDrawerOpen.value = false;
        loadProjectContacts(detailData.id);
      } catch (err) {
        console.error('新增项目联系人失败:', err);
      }
    }
  });
};

// 提交跟进记录
const submitFollowup = () => {
  if (!followupFormRef.value) return;
  followupFormRef.value.validate(async (valid) => {
    if (valid) {
      followupSubmitting.value = true;
      const data = {
        objectNo: detailData.id,
        customerName: detailData.customerName,
        customerNo: detailData.customerNo,
        department: detailData.deptNo,
        profession: detailData.profession,
        salesman: followupForm.visitor,
        visitor: followupForm.visitor,
        goalObject: detailData.customerName, // 线索通常拜访的是客户
        followPeopleName: followupForm.accompany || '',
        callTypeCode: followupForm.visitType,
        callDate: followupForm.visitDate,
        nextCallDate: followupForm.nextVisitDate,
        callAim: followupForm.purpose,
        followUpCondition: followupForm.progress,
        recordPicture: followupForm.recordPicture,
        platformCode: 'crm'
      };
      try {
        await addRecord(data);
        proxy.$modal.msgSuccess("新增跟进记录成功");
        followupDialogOpen.value = false;
        loadFollowupList();
      } catch (err) {
        console.error('新增跟进记录失败:', err);
      } finally {
        followupSubmitting.value = false;
      }
    }
  });
};

// 字典名称翻译支持
const findVisitTypeName = (code) => {
  const dict = visitTypeOptions.value.find(d => String(d.dictValue) === String(code));
  return dict ? dict.dictLabel : code || '拜访';
};

const loadTeamMembers = async (leadsId) => {
  if (!leadsId) return;
  try {
    const res = await listTeamMember(leadsId);
    // 直接使用后端返回的原始数据，所有字段均由后端名称翻译注解自动处理
    teamMembers.value = res.rows || res.data || [];
  } catch (err) {
    console.error('加载团队成员失败:', err);
    teamMembers.value = [];
  }
};

/** 根据角色代码获取角色名称 */
const getRoleLabelByCode = (code) => {
  if (!code) return '';
  if (memberRoleOptions.value && memberRoleOptions.value.length > 0) {
    const found = memberRoleOptions.value.find(r => r.dictValue == code);
    return found ? found.dictLabel : code;
  }
  return code;
};



/** 从详情页跳转编辑 */
const handleEditFromDetail = () => {
  detailDrawerOpen.value = false;
  handleUpdate(detailData);
};

/** 查找公司名称 */
const findCompanyName = (companyNo) => {
  if (!companyNo) return '';
  return companyOptions.value.find(i => i.companyCode === companyNo)?.companyName || companyNo || '';
};

/** 查找行业名称 */
const findIndustryName = (professionId) => {
  if (!professionId) return '';
  return industryOptions.value.find(i => i.id == professionId)?.industryCategoryName || professionId || '';
};

/** 查找信息来源名称 */
const findInfoSourceName = (id) => {
  if (!id) return '';
  return infoSourceOptions.value.find(i => i.value == id)?.label || id || '';
};

/** 查找项目级别名称 */
const findProjectLevelName = (id) => {
  if (!id) return '';
  return projectLevelOptions.value.find(i => i.value == id)?.label || id || '';
};

/** 查找采购方式名称 */
const findProcurementMethodName = (id) => {
  if (!id) return '';
  return procurementMethodOptions.value.find(i => i.value == id)?.label || id || '';
};

/** 监听左侧Tab切换 */
watch(activeLeftTab, (newVal) => {
  if (newVal === 'quote') {
    if (!selectedQuote.value && quoteList.value.length > 0) {
      handleQuoteRowClick(quoteList.value[0]);
    }
  }
});

/** 根据用户ID查找用户名称 */
const findUserName = (userId) => {
  if (!userId) return '';
  const user = userOptions.value.find(u => String(u.staffId) === String(userId) || String(u.userId) === String(userId));
  if (user) return user.staffName;
  return String(userId) || '';
};

/** 新增报价单 */
const handleAddQuote = () => {
  // 创建新报价单对象
  const newId = 'q_' + Math.random().toString(36).substr(2, 9);
  const newItem = {
    id: newId,
    quoteName: '新建报价单 ' + parseTime(new Date(), '{y}{m}{d}'),
    amount: 0,
    status: '0', // 草稿
    createTime: parseTime(new Date())
  };
  
  // 添加到列表
  quoteList.value.push(newItem);
  
  // 自动选中新报价单，触发下方明细编辑区的显示
  selectedQuote.value = newItem;
  quoteItemList.value = []; // 初始化明细列表
  
  proxy.$modal.msgSuccess("已新建报价单草稿，请在下方添加产品明细");
};

/** 报价单行点击 - 加载明细 */
const handleQuoteRowClick = (row) => {
  selectedQuote.value = row;
  loadQuoteItems(row.id);
};

/** 加载报价单明细 */
const loadQuoteItems = async (quoteId) => {
  quoteItemLoading.value = true;
  try {
    const res = await listLeads({ id: quoteId });
    quoteItemList.value = [];
  } finally {
    quoteItemLoading.value = false;
  }
};

/** 报价单详情 */
const handleQuoteDetail = (row) => {
  selectedQuote.value = row;
  loadQuoteItems(row.id);
};

/** 删除报价单 */
const handleDeleteQuote = (row) => {
  proxy.$modal.confirm(`确认删除报价单"${row.quoteName}"吗？`).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    if (selectedQuote.value?.id === row.id) {
      selectedQuote.value = null;
      quoteItemList.value = [];
    }
  }).catch(() => {});
};

/** 添加产品到报价单 */
const handleAddQuoteItem = () => {
  quoteItemList.value.push({
    id: undefined,
    productId: undefined,
    productCode: '',
    productName: '',
    productImage: '',
    unit: '',
    specification: '',
    quantity: 1,
    platformPrice: '',
    minPrice: '',
    quotePrice: '',
    grossMargin: undefined,
    _isNew: true
  });
};

/** 计算毛利率 */
const calcGrossMargin = (row) => {
  if (row.quotePrice && row.minPrice && Number(row.quotePrice) > 0) {
    const margin = ((Number(row.quotePrice) - Number(row.minPrice)) / Number(row.quotePrice) * 100).toFixed(2);
    row.grossMargin = margin;
  } else {
    row.grossMargin = undefined;
  }
};

/** 保存报价单产品行 */
const handleSaveQuoteItem = async (row) => {
  if (!row.quotePrice) {
    proxy.$modal.msgWarning("请输入报价");
    return;
  }
  proxy.$modal.msgSuccess("保存成功");
  if (row._isNew) {
    row._isNew = false;
  }
};

/** 删除报价单产品行 */
const handleDeleteQuoteItem = (row) => {
  proxy.$modal.confirm("确认删除该产品吗？").then(() => {
    const index = quoteItemList.value.indexOf(row);
    if (index > -1) {
      quoteItemList.value.splice(index, 1);
    }
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

/** 打开编辑团队成员弹窗 */
const handleMemberEdit = (member) => {
  editingMemberIndex = teamMembers.value.indexOf(member);
  memberEditForm.staffId = member.userNo || member.staffId;
  memberEditForm.staffName = member.realName;
  // 用 updateAccredit 整型回填表单（新字典 0/1）
  memberEditForm.role = member.roleCode || '';
  memberEditForm.permission = String(member.updateAccredit ?? '0');
  memberEditVisible.value = true;
};

/** 提交编辑团队成员 */
const submitMemberEdit = async () => {
  if (!memberEditForm.role) {
    proxy.$modal.msgWarning("请选择团队角色");
    return;
  }
  const member = teamMembers.value[editingMemberIndex];
  if (!member) {
    proxy.$modal.msgError("成员数据异常");
    return;
  }
  const roleLabel = memberRoleOptions.value.find(r => r.dictValue === memberEditForm.role)?.dictLabel || memberEditForm.role;
  try {
    await updateTeamMember({
      id: member.id,
      roleCode: memberEditForm.role,
      updateAccredit: Number(memberEditForm.permission),
      izManager: roleLabel === '业务负责人' ? 1 : 0
    });
    // 重新从后端加载团队成员列表，确保 roleName、permission 等 JOIN 字段正确刷新
    await loadTeamMembers(detailData.id);
    memberEditVisible.value = false;
    proxy.$modal.msgSuccess("修改成功");
  } catch (e) {
    /* API error handled by request interceptor */
  }
};

/** 打开添加团队成员弹窗 */
const handleAddMember = () => {
  // 重置表单
  memberAddForm.staffId = undefined;
  memberAddForm.role = '';
  memberAddForm.permission = '0';
  memberAddVisible.value = true;
};

/** 提交添加团队成员 */
const submitMemberAdd = async () => {
  if (!memberAddForm.staffId) {
    proxy.$modal.msgWarning("请选择添加人员");
    return;
  }
  // 重复校验：检查是否已存在该用户
  const exists = teamMembers.value.find(m => m.staffId == memberAddForm.staffId);
  if (exists) {
    proxy.$modal.msgWarning("该成员已在团队中，无需重复添加");
    return;
  }
  const selectedUser = userOptions.value.find(u => u.staffId == memberAddForm.staffId);
  const roleLabel = memberRoleOptions.value.find(r => r.dictValue === memberAddForm.role)?.dictLabel || memberAddForm.role;
  try {
    await addTeamMember({
      dataType: 1,
      objectNo: String(detailData.id),
      userNo: memberAddForm.staffId,
      realName: selectedUser?.staffName || '',
      roleCode: memberAddForm.role,
      updateAccredit: Number(memberAddForm.permission),
      izManager: roleLabel === '业务负责人' ? 1 : 0
    });
    // 刷新成员列表
    await loadTeamMembers(detailData.id);
    memberAddVisible.value = false;
    proxy.$modal.msgSuccess("添加成功");
  } catch (e) {
    /* API error handled by request interceptor */
  }
};

/** 移除团队成员 */
const handleRemoveMember = (member) => {
  if (!member.id) {
    proxy.$modal.msgWarning("该成员未保存，无法移除");
    return;
  }
  proxy.$modal.confirm(`确认移除成员"${member.realName}"吗？`).then(async () => {
    try {
      await delTeamMember(member.id);
      const index = teamMembers.value.indexOf(member);
      if (index > -1) {
        teamMembers.value.splice(index, 1);
      }
      proxy.$modal.msgSuccess("移除成功");
    } catch (e) {
      /* API error handled */
    }
  }).catch(() => {});
};

const handleDelete = (row) => {
  const ids = row.id || multipleSelection.value.map(item => item.id);
  proxy.$modal.confirm(`确认删除选中的项目线索吗？`).then(() => {
    return delLeads(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

onMounted(() => {
  getList();
  getCompanyList();
  getUserList();
  getDeptList();
  getSaleStatusList();
  getTimeQueryTypeList();
  getProjectLevelList();
  getProcurementMethodList();
  getInfoSourceList();
  getCustomerList();
  getIndustryList();
  getMemberRoleList();
  getProvinceCityList();
  getProjectRoleList();
});

const getProvinceCityList = async () => {
  try {
    const res = await listProvinceWithCities();
    provinceCityOptions.value = res.data || [];
  } catch (err) {
    console.error('加载省市数据失败:', err);
  }
};

const getProjectRoleList = () => {
  listCommonDict('LXRJE0001').then(res => {
    projectRoleOptions.value = res.data || [];
  });
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background-color: #f7f9fb;
  min-height: calc(100vh - 84px);
}

.search-card {
  margin-bottom: 12px;
  border: none;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  :deep(.el-form-item) {
    margin-bottom: 2px;
  }
}

.search-btns {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 12px;
  padding-left: 0;
  
  .el-button {
    border-radius: 6px;
    height: 32px;
    padding: 8px 16px;
  }
}

.summary-stripe {
  margin: 15px 0;
  background: #fff;
  padding: 10px 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .stripe-title {
    font-size: 15px;
    font-weight: 600;
    color: #333;
  }
  
  .stripe-total {
     font-size: 14px;
     color: #475569;
     margin-left: -200px; // 拉近标题与总计
     .red-text {
       color: #f43f5e;
       font-weight: bold;
       margin: 0 5px;
     }
  }
  
  .stripe-actions {
    display: flex;
    gap: 10px;
  }
}

.table-card {
  border: none;
}

.standard-table {
  border-radius: 6px;
  overflow: hidden;
  :deep(th.el-table__cell) {
    background-color: #f8fafc !important;
    color: #475569;
    font-weight: 600;
  }
}

.claim-tip {
  margin-top: 15px;
  padding: 10px;
  background-color: #fdf2f2;
  border-radius: 4px;
  color: #7f1d1d;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 8px;
}

// 编辑团队成员弹窗
.member-edit-dialog {
  .member-edit-name {
    font-size: 14px;
    color: #334155;
    font-weight: 500;
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-bottom: 10px;
}

.label-nowrap {
  :deep(.el-form-item__label) {
    white-space: nowrap !important;
  }
}

// 抽屉样式
.leads-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
    background-color: #f8fafc;
  }
}

.drawer-header {
  padding: 15px 25px;
  background: #fff;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 10;
  
  .header-title {
    display: flex;
    align-items: center;
    gap: 15px;
    
    .main-title {
      font-size: 18px;
      font-weight: 600;
      color: #334155;
    }
    
    .sub-title {
      font-size: 14px;
      color: #64748b;
    }
  }
  
  .close-btn {
    font-size: 20px;
    color: #64748b;
    &:hover {
      color: #0ea5e9;
    }
  }
}

.drawer-content {
  flex: 1;
  padding: 20px 25px;
  overflow-y: auto;
  
  .form-section {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #3b82f6; // 蓝色标题
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f1f5f9;
      display: flex;
      align-items: center;
      
      &::before {
        content: "";
        width: 4px;
        height: 16px;
        background: #3b82f6;
        margin-right: 10px;
        border-radius: 2px;
      }
    }
    
    .attachment-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e1e7f1;
      margin-bottom: 0px;
      background-color: #f5f9ff; // 浅蓝色背景
      padding: 8px 15px;
      border-radius: 4px 4px 0 0;
      
      &::before {
        display: none; // 原型图没有左边的小竖条
      }
      
      span {
        color: #3b82f6; // 蓝色文字
        font-weight: 600;
        font-size: 14px;
      }
      
      .upload-btn {
        margin-left: auto;
      }
    }
  }
  
  :deep(.el-form-item__label) {
    color: #475569;
  }
  
  :deep(.el-input-group__append) {
    background-color: transparent;
    padding: 0 10px;
    color: #64748b;
  }
}

.drawer-footer {
  padding: 15px 25px;
  background: #fff;
  border-top: 1px solid #e2e8f0;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.at-table {
  border-radius: 0 0 4px 4px;
  border-top: none;
  overflow: hidden;
  :deep(th.el-table__cell) {
    background-color: #f8fafc !important;
    font-weight: 500;
    color: #333;
  }
}

.empty-text {
  padding: 20px;
  color: #94a3b8;
  text-align: center;
}

// 详情抽屉样式
.detail-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
  }
}

.detail-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

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

  .main-title {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
  }
  
  .close-btn {
    font-size: 20px;
    color: #64748b;
    cursor: pointer;
    &:hover { color: #ef4444; }
  }
}

.detail-main {
  flex: 1;
  display: flex;
  overflow: hidden;
  background-color: #fff;
}

// 左侧内容区
.detail-left {
  flex: 7;
  min-width: 0;
  background: #fff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-right: 1px solid #e2e8f0;

  .left-tabs {
    display: flex;
    border-bottom: 1px solid #f1f5f9;
    padding: 0 10px; // 缩小容器左右边距
    flex-shrink: 0;

    .left-tab-item {
      padding: 16px 25px; // 增加单个 Tab 的点击区域和间距
      font-size: 14px;
      color: #64748b;
      cursor: pointer;
      position: relative;
      transition: all 0.2s;

      &:hover { color: #ef4444; }
      
      &.active {
        color: #ef4444;
        font-weight: 600;
        &::after {
          content: '';
          position: absolute;
          bottom: -1px;
          left: 15px; // 下划线缩进
          right: 15px;
          height: 3px;
          background: #ef4444;
          border-radius: 2px 2px 0 0;
        }
      }
    }
  }

  .tab-content {
    flex: 1;
    overflow-y: auto;
    padding: 25px 30px; // 增加内边距
  }
}

.info-section {
  margin-bottom: 24px;

  &:last-child { margin-bottom: 0; }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .section-label {
      font-size: 16px;
      font-weight: 600;
      color: #1e293b;
      position: relative;
    }
  }

  .info-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr); // 强制所有都为三列
    gap: 12px 60px;
    margin-bottom: 4px;

    .info-item {
      display: flex;
      align-items: center;
      min-height: 28px;

      .info-label {
        width: 100px;
        flex-shrink: 0;
        font-size: 13px;
        color: #94a3b8;
      }

      .info-value {
        font-size: 13px;
        color: #1e293b;
        font-weight: 500;
        word-break: break-all;
      }
    }
  }

  .info-row-item {
    display: flex;
    align-items: center;
    min-height: 36px;
    margin-bottom: 8px;

    .info-label {
      width: 100px; // 保持 100px 统一对齐
      flex-shrink: 0;
      font-size: 13px;
      color: #94a3b8;
    }

    .info-value {
      font-size: 14px;
      color: #1e293b;
      font-weight: 600;
    }
  }
}

.followup-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 5px;
  
  .follow-img {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    cursor: pointer;
    transition: transform 0.2s;
    &:hover {
      transform: scale(1.05);
    }
  }
}

.content-row.no-label {
  padding-left: 0;
}

// 项目联系人表格
.contact-section {
  .contact-header {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 16px;
  }

  .contact-table {
    border-radius: 4px;
    overflow: hidden;

    :deep(th.el-table__cell) {
      background-color: #f8fafc !important;
      color: #475569;
      font-weight: 600;
      font-size: 13px;
    }
    :deep(td.el-table__cell) {
      font-size: 13px;
      color: #334155;
    }
  }
}

// 结算分析
.analysis-section {
  .analysis-form {
    .analysis-row {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .form-label {
        width: 70px;
        flex-shrink: 0;
        font-size: 14px;
        color: #334155;
        font-weight: 500;
      }

      .result-radio {
        :deep(.el-radio) { margin-right: 24px; }
      }
    }

    .summary-textarea-wrap {
      margin-bottom: 16px;

      :deep(.el-textarea__inner) {
        border-radius: 6px;
      }
    }

    .upload-area {
      :deep(.el-button) { border-radius: 6px; }
    }
  }
}

// 附件与报价单
.attachment-section, .quote-section {
  height: 100%;
  display: flex;
  flex-direction: column;

  .quote-table-header {
    display: flex;
    justify-content: flex-end;
    padding: 0 0 12px 0;
    
    .btn-add-product {
      background-color: #3b82f6;
      border-color: #3b82f6;
      border-radius: 4px;
    }
  }

  .quote-empty-state {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
    background: #f8fafc;
    border: 2px dashed #e2e8f0;
    border-radius: 8px;
  }

  .quote-item-table {
    border-radius: 4px;
    overflow: hidden;

    :deep(th.el-table__cell) {
      background-color: #f1f5f9 !important; // 更接近原型的淡灰色
      color: #475569;
      font-weight: 500;
      font-size: 13px;
      padding: 12px 0;
    }
    :deep(td.el-table__cell) {
      font-size: 13px;
      color: #334155;
      padding: 10px 0;
    }
    :deep(.el-input__inner) {
      text-align: center;
    }

    .no-image {
      color: #cbd5e1;
      font-size: 14px;
    }

    .margin-low {
      color: #ef4444;
      font-weight: 600;
    }
  }

  .attach-table, .quote-table {
    border-radius: 4px;
    overflow: hidden;

    :deep(th.el-table__cell) {
      background-color: #f8fafc !important;
      color: #475569;
      font-weight: 600;
      font-size: 13px;
    }
    :deep(td.el-table__cell) {
      font-size: 13px;
      color: #334155;
    }
  }
}

// 右侧边栏
.detail-right {
  flex: 3; // 统一比例对齐原型图
  flex-shrink: 0;
  background: #fff;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .right-tabs {
    display: flex;
    border-bottom: 1px solid #f1f5f9;
    flex-shrink: 0;
    background: #fff;

    .right-tab-item {
      flex: 1;
      text-align: center;
      padding: 16px 8px;
      font-size: 13px;
      color: #1d2129; // 改为更深的颜色
      cursor: pointer;
      transition: all 0.2s;
      position: relative;

      &:hover { color: #f53f3f; }

      &.active {
        color: #f53f3f;
        font-weight: 600;
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 32px;
          height: 3px;
          background: #f53f3f;
          border-radius: 2px;
        }
      }
    }
  }

  .right-tab-content {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
  }
}

.team-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;

  .team-title {
    font-size: 14px;
    font-weight: 600;
    color: #1d2129;
  }

  .add-icon {
    cursor: pointer;
    color: #94a3b8;
    font-size: 18px;
    transition: color 0.2s;
    &:hover { color: #3b82f6; }
  }
}

.team-search { margin-bottom: 20px; }

.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;
      min-width: 0;
      
      .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; }
      }
    }
  }
}


.manage-info {
  .manage-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px 20px;

    .manage-item {
      display: flex;
      align-items: center;

      .manage-label {
        width: 70px;
        font-size: 13px;
        color: #94a3b8;
        flex-shrink: 0;
      }

      .manage-value {
        font-size: 13px;
        color: #334155;
      }
    }
  }
}

// 跟进记录列表
.followup-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  margin-bottom: 10px;

  .filter-item {
    display: flex;
    align-items: center;
    gap: 10px;
    .filter-label { font-size: 13px; color: #64748b; }
  }
}

.followup-list {
  .followup-item {
    background: #f8fafc;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    border: 1px solid #f1f5f9;

    .followup-header {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 12px;

      .visitor-name { font-weight: 600; color: #1e293b; font-size: 14px; }
      .visit-time { font-size: 13px; color: #94a3b8; flex: 1; }
    }

    .followup-body {
      .content-row {
        margin-bottom: 8px;
        .label { font-size: 12px; color: #64748b; margin-bottom: 4px; display: block; }
        .content-text {
          font-size: 13px;
          color: #334155;
          line-height: 1.5;
          background: #fff;
          padding: 8px 12px;
          border-radius: 4px;
          border: 1px solid #e2e8f0;
        }
      }
    }
  }
}

// 跟进记录对话框
.followup-dialog {
  .dlg-customer-row {
    margin-bottom: 18px;
    font-size: 14px;
    color: #64748b;
    .hl { color: #1e293b; font-weight: 600; margin-left: 8px; }
  }

  .upload-placeholder {
    width: 80px;
    height: 80px;
    border: 1px dashed #cbd5e1;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #94a3b8;
    cursor: pointer;
    transition: all 0.2s;
    &:hover { border-color: #ef4444; color: #ef4444; }
  }

  :deep(.el-form-item__label) {
  }
}

// 抽屉规范化样式
.drawer-header-standard {
  height: 60px;
  padding: 0 24px;
  background: #fff;
  border-bottom: 1px solid #f1f5f9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;

  .header-title-text {
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;
  }
  
  .close-btn {
    font-size: 20px;
    color: #94a3b8;
    cursor: pointer;
    &:hover { color: #ef4444; }
  }
}

.drawer-body-standard {
  flex: 1;
  padding: 24px;
  background-color: #f8fafc;
  overflow-y: auto;

  .section-title {
    color: #409eff;
    font-size: 15px;
    padding: 12px 16px;
    margin: 0 -24px 20px -24px;
    background: #f5f7fa;
  }
}

.drawer-footer-standard {
  padding: 20px 24px;
  background: #fff;
  border-top: 1px solid #f1f5f9;
  display: flex;
  justify-content: flex-end;
  gap: 16px;

  .btn-save {
    background-color: #409eff;
    border-color: #409eff;
    padding: 8px 24px;
  }

  .btn-cancel {
    padding: 8px 24px;
    color: #64748b;
  }
}

.project-contact-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 18px;
  }
  
  :deep(.el-form-item__label) {
    color: #475569;
  }
}

// 操作日志样式
.log-list {
  padding: 10px 0;
  
  .log-item {
    padding: 12px 0;
    font-size: 14px;
    line-height: 1.5;
    border-bottom: 1px dashed #f1f5f9;
    
    &:last-child {
      border-bottom: none;
    }

    .log-time {
      color: #94a3b8; /* 灰色 */
      margin-right: 8px;
    }
    
    .log-user {
      color: #409eff; /* 蓝色 */
      margin-right: 4px;
    }
    
    .log-action {
      color: #86909c; /* 灰色 */
    }
    
    .log-target {
      color: #409eff; /* 蓝色 */
    }
  }
}
</style>
