<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="companyId">
              <el-select v-model="queryParams.companyId" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in companyOptions" :key="item.companyCode || item.id"
                  :label="item.companyName" :value="item.companyCode || item.id" />
              </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 />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目负责人" prop="managerId">
              <el-select v-model="queryParams.managerId" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in userOptions" :key="item.staffId || item.userId"
                  :label="item.staffName || item.nickName" :value="item.staffId || item.userId" />
              </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="deptId">
              <el-tree-select
                v-model="queryParams.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="所属部门"
                check-strictly
                style="width: 100%"
                clearable
              />
            </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 || item.userId"
                  :label="item.staffName || item.nickName" :value="String(item.staffId || item.userId)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目状态" prop="projectStatus">
              <el-select v-model="queryParams.projectStatus" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in saleStatusOptions" :key="item.dictValue"
                  :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="成交结果" prop="result">
              <el-select v-model="queryParams.result" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in dealResultOptions" :key="item.dictValue"
                  :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="timeType">
              <el-select v-model="queryParams.timeType" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in timeQueryTypeOptions" :key="item.dictValue"
                  :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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="10">
            <el-form-item label-width="0">
              <div class="search-btns">
                <el-button type="primary" 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-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <div class="filter-action-bar">
      <!-- 页面标题 -->
      <div class="page-title">项目商机信息列表</div>
      
      <!-- 分类筛选点击项 -->
      <div class="tab-filters">
        <div class="tab-btn" :class="{ active: activeTab === 'managed' }" @click="handleTabClick('managed')">我负责的项目商机</div>
        <div class="tab-btn" :class="{ active: activeTab === 'participated' }" @click="handleTabClick('participated')">我参与的项目商机</div>
        <div class="tab-btn badge-btn" :class="{ active: activeTab === 'all' }" @click="handleTabClick('all')">
          全部项目商机
          <span class="badge">99+</span>
        </div>
      </div>

      <!-- 金额汇总 -->
      <div class="amount-summary">
        金额总计<span class="red-num">{{ totalAmount ? totalAmount.toFixed(2) : '0.00' }}</span>(万)
      </div>

      <!-- 操作按钮（靠右） -->
      <div class="right-actions">
        <el-button type="info" size="small" icon="Delete" :disabled="multipleSelection.length === 0" @click="handleBatchDelete">批量删除</el-button>
        <el-button type="primary" size="small" icon="Switch" :disabled="multipleSelection.length === 0" @click="handleTransfer">转移给他人</el-button>
      </div>
    </div>

    <el-card shadow="never" class="table-card">
      <el-table ref="opportunityTable" v-loading="loading" :data="opportunityList" 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="240" show-overflow-tooltip fixed />
        <el-table-column label="所属公司" align="center" prop="companyName" min-width="150" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="200" show-overflow-tooltip />
        <el-table-column label="行业" align="center" prop="industry" width="100" />
        <el-table-column label="部门" align="center" prop="deptName" width="100" />
        <el-table-column label="金额(万)" align="center" prop="projectBudget" width="100">
          <template #default="{ row }">
            <span>{{ row.projectBudget != null ? Number(row.projectBudget).toFixed(2) : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="赢单率" align="center" prop="winRate" width="100">
          <template #default="{ row }">
            <span>{{ row.winRate != null ? `${row.winRate}%` : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目级别" align="center" prop="projectLevel" width="100">
          <template #default="{ row }">
            <span>{{ findProjectLevelName(row.projectLevel) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目负责人" align="center" prop="leaderName" min-width="100" />
        <el-table-column label="产品支持" align="center" prop="productSupportName" min-width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="立项时间" align="center" prop="approvalDate" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.approvalDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="截止时间" align="center" prop="expectedCompletionTime" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expectedCompletionTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目状态" align="center" prop="status" width="100">
           <template #default="{ row }">
             <el-tag :type="row.status === '1' ? 'success' : row.status === '2' ? 'danger' : 'warning'" plain>
               {{ getSaleStatusLabel(row.status) }}
             </el-tag>
           </template>
        </el-table-column>
        <el-table-column label="成交结果" align="center" prop="result" width="100">
          <template #default="{ row }">
            <span v-if="String(row.result) === '1'" style="color: #67c23a;">赢单</span>
            <span v-else-if="String(row.result) === '2'" style="color: #f56c6c;">丢单</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleProgressBtn(scope.row)">进度</el-button>
            <el-button link type="primary" @click="handleProgress(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>

    <!-- 抽屉：项目商机新增/编辑 -->
    <el-drawer
      :title="form.id ? '编辑项目商机' : '项目商机（3个月内出结果、金额明确的项目信息，计入：项目商机）'"
      v-model="drawerOpen"
      direction="rtl"
      size="75%"
      :close-on-click-modal="false"
      class="opp-drawer">
      <template #default>
        <div class="drawer-body">
          <el-form ref="formRef" :model="form" label-width="90px" class="opp-form">

            <!-- 基本信息 -->
            <div class="section-block">
              <div class="section-title">基本信息</div>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="归属公司：" required>
                    <el-select v-model="form.companyId" placeholder="请选择" style="width: 100%" clearable>
                      <el-option v-for="item in companyOptions" :key="item.companyCode || item.id"
                        :label="item.companyName" :value="String(item.companyCode || item.id)" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户名称：" required>
                    <el-select v-model="form.customerNo" placeholder="请选择" style="width: 100%" clearable filterable>
                      <el-option v-for="item in customerOptions" :key="item.id"
                        :label="item.customerName" :value="String(item.id || item.customerNo)" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="项目负责人：" required>
                    <el-select v-model="form.managerId" placeholder="请选择" style="width: 100%" clearable>
                      <el-option v-for="item in userOptions" :key="item.staffId || item.userId"
                        :label="item.staffName || item.nickName" :value="String(item.staffId || item.userId)" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目名称：" required>
                    <el-input v-model="form.projectName" placeholder="请输入" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="金额(万)：" required>
                    <el-input v-model="form.amount" placeholder="请输入">
                      <template #append>万</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="赢单率(%)：" required>
                    <el-input v-model="form.winRate" placeholder="请输入">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="立项时间：" required>
                    <el-date-picker v-model="form.setupTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="截止时间：">
                    <el-date-picker v-model="form.deadline" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="营销活动：">
                    <el-select v-model="form.marketingActivity" placeholder="请选择" style="width: 100%" clearable>
                      <el-option label="活动A" value="1" />
                      <el-option label="活动B" value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 项目信息 -->
            <div class="section-block">
              <div class="section-title">项目信息</div>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="项目级别：" required>
                    <el-select v-model="form.projectLevel" placeholder="请选择" style="width: 100%" clearable>
                      <el-option v-for="item in projectLevelOptions" :key="item.dictValue"
                        :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="项目区域：">
                    <el-input v-model="form.projectArea" placeholder="请输入" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="采购方式：">
                    <el-select v-model="form.purchaseMethod" placeholder="请选择" style="width: 100%" clearable>
                      <el-option v-for="item in procurementMethodOptions" :key="item.dictValue"
                        :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="商机来源：">
                    <el-select v-model="form.source" placeholder="请选择" style="width: 100%" clearable>
                      <el-option v-for="item in infoSourceOptions" :key="item.dictValue"
                        :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="项目描述：">
                <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入项目描述" />
              </el-form-item>
              <el-form-item label="竞争对手：">
                <el-input v-model="form.competitor" type="textarea" :rows="4" placeholder="请输入竞争对手" />
              </el-form-item>
            </div>

            <!-- 附件 -->
            <div class="section-block no-border">
              <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="file-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="100" align="center">
                   <template #default="scope">
                     <el-button link type="danger" @click="handleDeleteFile(scope.$index)">删除</el-button>
                   </template>
                </el-table-column>
                <template #empty><span style="color:#999;">暂无数据</span></template>
              </el-table>
            </div>

          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="drawer-footer">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
          <el-button @click="drawerOpen = false">取消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 弹窗：转移他人 -->
    <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="transferOwner" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in userOptions" :key="item.staffId || item.userId"
              :label="item.staffName || item.nickName" :value="String(item.staffId || item.userId)" />
          </el-select>
        </el-form-item>
        <el-form-item class="label-nowrap">
          <el-checkbox v-model="keepAsMember">保留【负责人】为销售团队成员</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmTransfer">确认</el-button>
          <el-button @click="transferVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情抽屉 -->
    <DetailDrawer 
      ref="detailDrawerRef" 
      :saleStatusOptions="saleStatusOptions" 
      :projectLevelOptions="projectLevelOptions" 
      :infoSourceOptions="infoSourceOptions"
      :procurementMethodOptions="procurementMethodOptions"
      @edit="handleUpdate" 
      @success="getList"
    />

    <!-- 进度抽屉 -->
    <ProgressDrawer ref="progressDrawerRef" @success="getList" />
  </div>
</template>

<script setup name="ProjectOpportunity">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { listOpportunity, addOpportunity, updateOpportunity, delOpportunity, transferOpportunity, getOpportunity } from '@/api/saleManage/opportunity/index';
import { selectStaffOptionList } from "@/api/system/comStaff/index";
import { listCompanyOption, listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listCommonDict } from "@/api/customer/customerDict";
import { getToken } from "@/utils/auth";
import { globalHeaders } from '@/utils/request';
import { listByIds } from "@/api/system/oss/index";
import { listDept } from "@/api/system/dept/index";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import DetailDrawer from './DetailDrawer.vue';
import ProgressDrawer from './ProgressDrawer.vue';

const detailDrawerRef = ref(null);
const progressDrawerRef = ref(null);

const { proxy } = getCurrentInstance();
const { parseTime } = proxy.useDict ? { parseTime: proxy.parseTime } : proxy;

/* ========== 状态 ========== */
const loading = ref(false);
const total = ref(0);
const opportunityList = ref([]);
const dateRange = ref([]);
const multipleSelection = ref([]);
const totalAmount = ref(0);

/* ========== 下拉选项 ========== */
const companyOptions = ref([]);
const customerOptions = ref([]);
const userOptions = ref([]);
const deptOptions = ref([]);
const saleStatusOptions = ref([]);
const timeQueryTypeOptions = ref([]);
const projectLevelOptions = ref([]);
const procurementMethodOptions = ref([]);
const infoSourceOptions = ref([]);
const industryOptions = ref([]);
const dealResultOptions = ref([]);

/* ========== 附件上传相关 ========== */
const fileList = ref([]);
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/resource/oss/upload");
const headers = ref(globalHeaders());

/* ========== 抽屉状态 ========== */
const drawerOpen = ref(false);
const submitLoading = ref(false);
const transferVisible = ref(false);
const transferOwner = ref('');
const keepAsMember = ref(false);

/* ========== Tab切换状态 ========== */
const activeTab = ref('all'); // 默认为全选或者按需设定

const handleTabClick = (tab) => {
  activeTab.value = tab;
  handleQuery();
};

/* ========== 查询参数 ========== */
const queryParams = reactive({
  pageNum: 1, pageSize: 10,
  companyId: undefined, projectName: undefined, customerName: undefined,
  managerId: undefined, deptId: undefined, productSupport: undefined,
  projectStatus: undefined, result: undefined, timeType: undefined
});

/* ========== 新增表单 ========== */
const form = reactive({
  id: undefined, companyId: '', customerNo: '', managerId: '', projectName: '',
  amount: undefined, winRate: undefined, setupTime: '', deadline: '',
  marketingActivity: '', projectLevel: '', projectArea: '',
  purchaseMethod: '', source: '', description: '', competitor: '',
  fileNo: ''
});
const formRef = ref(null);

const rules = reactive({
  companyId: [{ required: true, message: '归属公司不能为空', trigger: 'change' }],
  customerNo: [{ required: true, message: '客户名称不能为空', trigger: 'change' }],
  managerId: [{ required: true, message: '项目负责人不能为空', trigger: 'change' }],
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
  winRate: [{ required: true, message: '赢单率不能为空', trigger: 'blur' }],
  setupTime: [{ required: true, message: '立项时间不能为空', trigger: 'change' }],
});

/* ========== 列表查询 ========== */
const getList = async () => {
  loading.value = true;
  try {
    const params = proxy.addDateRange(
      { pageNum: queryParams.pageNum, pageSize: queryParams.pageSize,
        projectType: '销售商机', companyNo: queryParams.companyId,
        projectName: queryParams.projectName, customerName: queryParams.customerName,
        leader: queryParams.managerId, deptNo: queryParams.deptId,
        productSupport: queryParams.productSupport,
        status: queryParams.projectStatus,
        timeType: queryParams.timeType,
        tabType: activeTab.value === 'list' ? undefined : activeTab.value // 透传给后端用于区分数据范围
      },
      dateRange.value
    );
    const res = await listOpportunity(params);
    opportunityList.value = res.rows || [];
    total.value = res.total || 0;
    totalAmount.value = opportunityList.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'); handleQuery(); };
const handleSelectionChange = (selection) => { multipleSelection.value = selection; };

/* ========== 新增（抽屉） ========== */
const handleAdd = () => { reset(); drawerOpen.value = true; };

const reset = () => {
  form.id = undefined; form.companyId = ''; form.customerNo = ''; form.managerId = ''; form.projectName = '';
  form.amount = undefined; form.winRate = undefined; form.setupTime = '';
  form.deadline = ''; form.marketingActivity = ''; form.projectLevel = '';
  form.projectArea = ''; form.purchaseMethod = ''; form.source = '';
  form.description = ''; form.competitor = '';
  form.fileNo = '';
  fileList.value = [];
};

/** 上传成功回调 */
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 = fileList.value.map(f => f.ossId).join(',');
    proxy.$modal.msgSuccess("上传成功");
  } else {
    proxy.$modal.msgError(res.msg);
  }
};

/** 删除附件 */
const handleDeleteFile = (index) => {
  fileList.value.splice(index, 1);
  form.fileNo = fileList.value.map(f => f.ossId).join(',');
};

/** 获取文件后缀/类型 */
const getFileType = (fileName) => {
  if (!fileName) return '未知';
  const lastDotIndex = fileName.lastIndexOf('.');
  if (lastDotIndex === -1) return '文件';
  return fileName.substring(lastDotIndex + 1).toUpperCase();
};

const submitForm = async () => {
  if (!form.companyId) return proxy.$modal.msgWarning('请选择归属公司');
  if (!form.customerNo) return proxy.$modal.msgWarning('请选择客户名称');
  if (!form.managerId) return proxy.$modal.msgWarning('请选择项目负责人');
  if (!form.projectName) return proxy.$modal.msgWarning('请输入项目名称');

  submitLoading.value = true;
  try {
    const selectedCustomer = customerOptions.value.find(c => String(c.id || c.customerNo) === form.customerNo);
    const selectedManager = userOptions.value.find(u => String(u.staffId || u.userId) === form.managerId);
    
    const data = {
      id: form.id,
      izClue: 0, 
      projectType: '销售商机',
      companyNo: form.companyId, 
      customerNo: form.customerNo,
      customerName: selectedCustomer?.customerName || '',
      profession: selectedCustomer?.industryCategoryId || undefined,
      leader: form.managerId, 
      leaderName: selectedManager?.staffName || selectedManager?.nickName || '',
      projectName: form.projectName,
      projectBudget: Number(form.amount), 
      winRate: Number(form.winRate),
      approvalDate: form.setupTime, 
      expectedCompletionTime: form.deadline,
      activityNo: form.marketingActivity || undefined,
      projectLevel: form.projectLevel || undefined, 
      projectArea: form.projectArea || undefined,
      procurementMethod: form.purchaseMethod || undefined, 
      infoSource: form.source || undefined,
      projectDescription: form.description || undefined, 
      competitor: form.competitor || undefined,
      fileNo: form.fileNo,
      status: form.id ? undefined : '0' // 新增时默认跟进中
    };

    if (form.id) {
      await updateOpportunity(data);
      proxy.$modal.msgSuccess('修改成功');
    } else {
      await addOpportunity(data);
      proxy.$modal.msgSuccess('新增成功');
    }
    
    drawerOpen.value = false;
    getList();
  } catch (e) {
    console.error(e);
  } finally {
    submitLoading.value = false;
  }
};

/* ========== 转移 ========== */
const handleTransfer = () => {
  if (!multipleSelection.value.length) return proxy.$modal.msgWarning('请先选择项目');
  transferOwner.value = ''; keepAsMember.value = true; transferVisible.value = true;
};
const confirmTransfer = async () => {
  if (!transferOwner.value) return proxy.$modal.msgWarning('请选择新负责人');
  const ids = multipleSelection.value.map(item => item.id);
  const ownerUser = userOptions.value.find(u => u.staffId == transferOwner.value || u.userId == transferOwner.value);
  try {
    await transferOpportunity({ ids, leader: transferOwner.value, leaderName: ownerUser?.staffName || '' });
    proxy.$modal.msgSuccess('转移成功'); transferVisible.value = false; getList();
  } catch (e) {}
};

/* ========== 编辑（从列表跳转） ========== */
const handleUpdate = (row) => {
  reset();
  const id = row.id;
  getOpportunity(id).then(response => {
    const data = response.data;
    // 映射后端字段到前端表单，并确保 ID 类字段为字符串以匹配下拉选项
    Object.assign(form, {
      ...data,
      companyId: data.companyNo ? String(data.companyNo) : '',
      customerNo: data.customerNo ? String(data.customerNo) : '',
      managerId: data.leader ? String(data.leader) : '',
      amount: data.projectBudget,
      setupTime: data.approvalDate,
      deadline: data.expectedCompletionTime,
      marketingActivity: data.activityNo ? String(data.activityNo) : '',
      projectLevel: data.projectLevel ? String(data.projectLevel) : '',
      purchaseMethod: data.procurementMethod ? String(data.procurementMethod) : '',
      source: data.infoSource ? String(data.infoSource) : '',
      description: data.projectDescription
    });
    
    // 加载已上传文件
    if (form.fileNo) {
      listByIds(form.fileNo).then(res => {
        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 = [];
    }
    drawerOpen.value = true;
  });
};

/* ========== 进度/详情 ========== */
const handleProgress = (row) => {
  if (detailDrawerRef.value) {
    detailDrawerRef.value.open(row);
  }
};

const handleProgressBtn = (row) => {
  if (progressDrawerRef.value) {
    progressDrawerRef.value.open(row);
  }
};

/* ========== 删除 ========== */
const handleDelete = (row) =>
  proxy.$modal.confirm(`确认删除项目「${row.projectName}」吗？`).then(async () => {
    try { await delOpportunity(row.id); getList(); proxy.$modal.msgSuccess('删除成功'); } catch (e) {}
  }).catch(() => {});

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) return proxy.$modal.msgWarning('请先选择要删除的项目');
  proxy.$modal.confirm('确认批量删除选中的项目吗？').then(async () => {
    try { for (const id of multipleSelection.value.map(i => i.id)) await delOpportunity(id); getList(); proxy.$modal.msgSuccess('批量删除成功'); } catch (e) {}
  }).catch(() => {});
};

/* ========== 辅助方法 ========== */
const getSaleStatusLabel = (status) => {
  if (String(status) === '0') return '跟进中';
  if (String(status) === '1') return '结案';

  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 findProjectLevelName = (id) => {
  if (!id) return '';
  return projectLevelOptions.value.find(i => String(i.dictValue) === String(id))?.dictLabel || id;
};

/* ========== 加载选项列表 ========== */
function getCompanyList() { listCompanyOption().then(r => companyOptions.value = r.data); }
function getCustomerList() { listCustomerInfo({ pageSize: 9999 }).then(r => customerOptions.value = r.rows || []); }
function getUserList() { selectStaffOptionList().then(r => userOptions.value = r.data); }
function getDeptList() { listDept().then(r => deptOptions.value = proxy.handleTree(r.data, 'deptId')); }
function getSaleStatusList() { listCommonDict('J0001').then(r => saleStatusOptions.value = r.data); }
function getTimeQueryTypeList() { listCommonDict('time_query_type').then(r => timeQueryTypeOptions.value = r.data); }
function getProjectLevelList() { listCommonDict('L0001').then(r => projectLevelOptions.value = r.data); }
function getProcurementMethodList() { listCommonDict('X0001').then(r => procurementMethodOptions.value = r.data); }
function getInfoSourceList() { listCommonDict('X0002').then(r => infoSourceOptions.value = r.data); }
function getIndustryList() { listIndustryCategory().then(r => industryOptions.value = r.data); }
function getDealResultList() { listCommonDict('deal_result').then(r => dealResultOptions.value = r.data); }

onMounted(() => {
  getList(); getCompanyList(); getCustomerList(); getUserList(); getDeptList();
  getSaleStatusList(); getTimeQueryTypeList(); getProjectLevelList();
  getProcurementMethodList(); getInfoSourceList(); getIndustryList();
  getDealResultList();
});
</script>

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

.search-card {
  margin-bottom: 10px;
  border: none;
  background: #fff;
  border-radius: 8px;
  :deep(.el-form-item) { margin-bottom: 2px; }
  :deep(.el-form-item__label) { white-space: nowrap; }
}

.search-btns {
  display: flex; align-items: center; justify-content: flex-start; gap: 12px;

  .el-button { border-radius: 6px; height: 32px; padding: 8px 16px; }
}

.filter-action-bar {
  margin: 15px 0;
  display: flex;
  align-items: center;
  background: #fff;
  padding: 15px 20px;
  border-radius: 6px;
  gap: 15px;
}

.page-title {
  font-size: 16px;
  color: #333;
}

.tab-filters {
  display: flex;
  gap: 10px;
}

.tab-btn {
  padding: 6px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: all 0.2s;
  background: #fff;
}
.tab-btn:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}
.tab-btn.active {
  color: #409eff;
  border-color: #409eff;
  background-color: #ecf5ff;
}

.badge-btn {
  position: relative;
}
.badge-btn .badge {
  position: absolute;
  top: -8px;
  right: -12px;
  background: #f56c6c;
  color: #fff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  line-height: 1;
  transform: scale(0.85);
}

.amount-summary {
  font-size: 14px;
  color: #f56c6c; 
}
.amount-summary .red-num { font-size: 16px; font-weight: bold; margin: 0 4px; }

.right-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.table-card { border: none; }

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

/* ========== 抽屉表单样式 ========== */
.drawer-body {
  padding: 0 10px; overflow-y: auto; max-height: calc(100vh - 120px);
}

.section-block {
  border-bottom: 1px dashed #e2e8f0; padding-bottom: 18px; margin-bottom: 18px;
  &:last-child { border-bottom: none; }
  .section-title { 
    background-color: #f0f7ff; padding: 8px 15px; margin-bottom: 18px; font-weight: 600; color: #3b82f6; font-size: 14px; border-left: 4px solid #3b82f6; 
    &.attachment-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 10px;
    }
  }
  .file-table { margin-top: 10px; }
}

.opp-form {
  :deep(.el-form-item) { margin-bottom: 18px; }
  :deep(.el-form-item__label) { color: #333; font-size: 13px; white-space: nowrap; }
  :deep(.el-textarea__inner), :deep(.el-input__wrapper) { border-radius: 4px; }
}

.drawer-footer {
  display: flex; justify-content: flex-end; align-items: center; gap: 12px; padding: 0 20px;
}

.opp-drawer {
  :deep(.el-drawer__header) { white-space: nowrap; }
  :deep(.el-drawer__title) { overflow: hidden; text-overflow: ellipsis; }
}

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

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

:global(.el-select-dropdown__item) {
  color: #333 !important;
  &.selected,
  &.is-selected {
    color: #333 !important;
    font-weight: normal !important;
  }
}
</style>
