<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card" :body-style="{ padding: '15px 20px 10px' }">
      <el-form :model="queryParams" ref="queryRef" label-width="80px">
        <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 filterable>
                <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="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 filterable>
                <el-option v-for="item in userOptions" :key="item.staffId || item.userId" :label="(item.staffCode || item.userName ? '(' + (item.staffCode || item.userName) + ') ' : '') + (item.staffName || item.nickName)" :value="String(item.staffId || item.userId)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="部门" prop="deptId">
              <el-tree-select
                v-model="queryParams.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="所属部门"
                check-strictly
                style="width: 100%"
                clearable
                filterable
              />
            </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 filterable>
                <el-option v-for="item in userOptions" :key="item.staffId || item.userId" :label="(item.staffCode || item.userName ? '(' + (item.staffCode || item.userName) + ') ' : '') + (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="projectLevel">
              <el-select v-model="queryParams.projectLevel" placeholder="请选择" style="width: 100%" clearable>
                <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="6">
            <el-form-item label="项目类型" prop="businessType">
              <el-select v-model="queryParams.businessType" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in projectTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="入围类型" prop="selectionType">
              <el-select v-model="queryParams.selectionType" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in shortlistedTypeOptions" :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="projectStatus">
              <el-select v-model="queryParams.projectStatus" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in statusOptions" :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="result">
              <el-select v-model="queryParams.result" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in resultOptions" :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" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in timeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="7">
            <el-form-item label="时间范围">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="17">
            <el-form-item label-width="20px">
              <div class="search-btns">
                <el-button 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>

    <el-card shadow="never" class="table-card">
      <div class="tabs-control">
        <div class="tabs-left">
          <span class="page-title">年度入围（项目）信息列表</span>
          <div class="tab-items">
            <div class="tab-item" :class="{ current: activeTab === 'mine' }" @click="handleTabChange('mine')">我负责的年度入围</div>
            <div class="tab-item" :class="{ current: activeTab === 'join' }" @click="handleTabChange('join')">我参与的年度入围</div>
            <div class="tab-item badge-item" :class="{ current: activeTab === 'all' }" @click="handleTabChange('all')">
              全部年度入围
              <span class="badge" v-if="total > 0">{{ total > 99 ? '99+' : total }}</span>
            </div>
          </div>
          <div class="summary-info">
            <span class="total-label">金额总计</span>
            <span class="total-value">{{ Number(totalAmount).toFixed(2) }}</span>
            <span class="total-unit">(万)</span>
          </div>
        </div>
        <div class="tabs-right">
          <div class="action-btns">
            <el-button type="info" plain size="default" icon="Delete" :disabled="multipleSelection.length === 0" @click="handleBatchDelete">批量删除</el-button>
            <el-button type="primary" size="default" icon="Switch" :disabled="multipleSelection.length === 0" @click="handleTransfer">转移给他人</el-button>
          </div>
        </div>
      </div>
      <el-table ref="selectionTable" v-loading="loading" :data="dataList" border class="standard-table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" fixed />
        <el-table-column label="项目名称" align="left" prop="projectName" min-width="220" show-overflow-tooltip fixed>
          <template #default="{ row }">
            <span class="project-name-link" @click="handleDetail(row)">{{ row.projectName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属公司" align="center" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ companyOptions.find(c => String(c.companyCode || c.id) === String(row.companyNo))?.companyName || row.companyName || row.companyNo }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.customerName || row.customName || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="项目级别" align="center" prop="projectLevel" width="100">
          <template #default="{ row }">
            {{ projectLevelOptions.find(o => String(o.value) === String(row.projectLevel))?.label || row.projectLevel }}
          </template>
        </el-table-column>
        <el-table-column label="项目类型" align="center" prop="businessType" width="100">
          <template #default="{ row }">
            {{ projectTypeOptions.find(o => String(o.value) === String(row.businessType))?.label || row.businessType }}
          </template>
        </el-table-column>
        <el-table-column label="金额(万)" align="center" prop="amount" width="100">
          <template #default="{ row }">
            <span>{{ row.amount != null ? Number(row.amount).toFixed(2) : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务期(年)" align="center" prop="standardPeriod" width="100" />
        <el-table-column label="服务时间段" align="center" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.serviceStartTime">{{ row.serviceStartTime }} ~ {{ row.serviceEndTime }}</span>
            <span v-else>{{ row.serviceTime || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="投标截止时间" align="center" prop="tenderDeadline" width="120">
          <template #default="{ row }">
            <span>{{ proxy.parseTime(row.tenderDeadline, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptName" min-width="120" show-overflow-tooltip />
        <el-table-column label="业务负责人" align="center" prop="leaderName" width="100">
          <template #default="{ row }">
            <span>{{ row.leaderName || findUserName(row.managerId || row.leader) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品支持" align="center" prop="productSupportName" width="100">
          <template #default="{ row }">
            <span>{{ row.productSupportName || findUserName(row.productSupport) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="赢单率" align="center" width="80">
          <template #default="{ row }">
            <span>{{ (row.winRate || row.winningRate) ? (row.winRate || row.winningRate) + '%' : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="行业" align="center" prop="industryName" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.industryName || industryOptions.find(o => String(o.id) === String(row.industryId || row.industry || row.profession))?.industryCategoryName || '' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
          <template #default="{ row }">
            <span>{{ proxy.parseTime(row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报名截止时间" align="center" width="120">
          <template #default="{ row }">
            <span>{{ proxy.parseTime(row.registrationDeadline || row.signUpDeadline, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入围类型" align="center" prop="finalizationType" width="100">
          <template #default="{ row }">
            {{ shortlistedTypeOptions.find(o => String(o.value) === String(row.finalizationType))?.label || row.finalizationType }}
          </template>
        </el-table-column>
        <el-table-column label="项目状态" align="center" prop="projectStatus" width="100">
          <template #default="{ row }">
            <span class="status-tag" :class="getStatusClass(row.projectStatus)">
              {{ statusOptions.find(o => String(o.value) === String(row.projectStatus))?.label || (String(row.projectStatus) === '2' ? '进行中' : (String(row.projectStatus) === '0' || String(row.projectStatus) === '1' ? '跟进中' : row.projectStatus)) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="成交结果" align="center" width="100">
          <template #default="{ row }">
            <template v-if="row.result === '1' || row.dealResult === '1' || row.result === 1 || row.dealResult === 1">
              <span style="color: #67c23a;">赢单</span>
            </template>
            <template v-else-if="row.result === '2' || row.dealResult === '2' || row.result === 2 || row.dealResult === 2">
              <span style="color: #f56c6c;">丢单</span>
            </template>
            <template v-else>
              <span :style="{ color: (row.result === '赢单' || row.dealResult === '赢单') ? '#67c23a' : (row.result === '丢单' || row.dealResult === '丢单') ? '#f56c6c' : '' }">
                {{ row.result || row.dealResult || resultOptions.find(o => String(o.value) === String(row.result || row.dealResult))?.label || '' }}
              </span>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button link type="primary" @click="handleProgress(row)">进度</el-button>
            <el-button link type="danger" @click="handleDelete(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>

    <!-- 弹窗组件 -->
    <SelectionAdd 
      v-model="addVisible"
      :companyOptions="companyOptions"
      :userOptions="userOptions"
      :projectLevelOptions="projectLevelOptions"
      :projectTypeOptions="projectTypeOptions"
      :shortlistedTypeOptions="shortlistedTypeOptions"
      :professionOptions="professionOptions"
      :industryOptions="industryOptions"
      @success="getList"
    />
    
    <SelectionEdit 
      v-model="editVisible"
      :id="currentId"
      :companyOptions="companyOptions"
      :userOptions="userOptions"
      :projectLevelOptions="projectLevelOptions"
      :projectTypeOptions="projectTypeOptions"
      :shortlistedTypeOptions="shortlistedTypeOptions"
      :professionOptions="professionOptions"
      :industryOptions="industryOptions"
      @success="getList"
    />

    <SelectionDetail 
      ref="detailDrawerRef"
      v-model="detailVisible"
      :companyOptions="companyOptions"
      :userOptions="userOptions"
      :statusOptions="statusOptions"
      :projectLevelOptions="projectLevelOptions"
      :projectTypeOptions="projectTypeOptions"
      :shortlistedTypeOptions="shortlistedTypeOptions"
      :professionOptions="professionOptions"
      :industryOptions="industryOptions"
      :deptOptions="deptOptions"
      @edit="handleEdit"
      @success="getList"
    />

    <!-- 弹窗：转移他人 -->
    <el-dialog title="项目转移" v-model="transferVisible" width="500px">
       <el-form label-width="100px">
         <el-form-item label="新负责人" required>
            <el-select v-model="transferOwner" placeholder="请选择" style="width: 100%" filterable>
              <el-option v-for="item in userOptions" :key="item.staffId || item.userId" :label="(item.staffCode || item.userName ? '(' + (item.staffCode || item.userName) + ') ' : '') + (item.staffName || item.nickName)" :value="String(item.staffId || item.userId)" />
            </el-select>
         </el-form-item>
         <el-form-item>
           <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>
    <!-- 抽屉：查看/发布进度 -->
    <el-drawer title="查看进度" v-model="progressVisible" size="500px" class="progress-drawer">
      <div class="progress-container">
        <!-- 发布区域 -->
        <div class="progress-publish-box">
          <el-input
            v-model="progressContent"
            type="textarea"
            :rows="6"
            placeholder="请输入进度描述"
            maxlength="200"
            show-word-limit
            resize="none"
          />
          <div class="publish-footer">
            <el-button type="primary" icon="Plus" @click="submitProgress" :loading="publishLoading">发 布</el-button>
          </div>
        </div>

        <!-- 列表区域 -->
        <div class="progress-list" v-loading="progressListLoading">
          <div v-for="(item, index) in progressList" :key="index" class="progress-item">
            <div class="item-header">
              <span class="user-name">{{ item.userName || item.createBy }}</span>
              <span class="time">{{ item.createTime || item.followUpTime }}</span>
            </div>
            <div class="item-content">{{ item.content || item.followUpCondition }}</div>
          </div>
          <el-empty v-if="progressList.length === 0 && !progressListLoading" description="暂无进度数据" :image-size="60" />
        </div>

        <!-- 分页 -->
        <div class="progress-pagination" v-if="progressTotal > 0">
          <el-pagination
            v-model:current-page="progressPage"
            v-model:page-size="progressPageSize"
            layout="prev, pager, next"
            :total="progressTotal"
            @current-change="loadProgress"
            small
          />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="ProjectSelection">
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue';
import { listProjectSelection, delProjectSelection, transferProjectSelection, publishProjectProgress } from '@/api/saleManage/projectSelection/index';
import { listSalesResultAnalyze } from '@/api/saleManage/leads/salesResultAnalyze';
import { listRecord, addRecord } from "@/api/visit/record";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listComStaff } from "@/api/system/comStaff/index";
import { listCompanyOption, getCustomerInfo } from "@/api/customer/customerInfo/index";
import { deptTreeSelect } from "@/api/system/user";

import SelectionAdd from './add.vue';
import SelectionEdit from './edit.vue';
import SelectionDetail from './detail.vue';

const proxy = getCurrentInstance().proxy;
const {
  L0001: projectLevelOptions,
  XMJB0001: projectTypeOptions,
  R0001: shortlistedTypeOptions,
  J0001: statusOptions,
  deal_result: resultOptions,
  time_query_type: timeTypeOptions,
  ZBPL0001: professionOptions
} = toRefs(reactive(proxy.useDict('XMJB0001', 'L0001', 'R0001', 'J0001', 'deal_result', 'time_query_type', 'ZBPL0001')));

const loading = ref(false);
const progressVisible = ref(false);
const progressContent = ref('');
const publishLoading = ref(false);
const total = ref(0);
const dataList = ref([]);
const dateRange = ref([]);
const multipleSelection = ref([]);
const totalAmount = ref(0);
const activeTab = ref('all');

const addVisible = ref(false);
const editVisible = ref(false);
const detailVisible = ref(false);
const currentId = ref(null);
const detailDrawerRef = ref(null);

const transferVisible = ref(false);
const transferOwner = ref('');
const keepAsMember = ref(false);

const progressList = ref([]);
const progressListLoading = ref(false);
const currentProjectNo = ref('');
const progressTotal = ref(0);
const progressPage = ref(1);
const progressPageSize = ref(5);

const userOptions = ref([]);
const companyOptions = ref([]);
const deptOptions = ref([]);
const industryOptions = ref([]);

const queryParams = reactive({
  pageNum: 1, pageSize: 10,
  companyNo: undefined, projectName: undefined, customerName: undefined, managerId: undefined,
  deptId: undefined, projectLevel: undefined, businessType: undefined, projectStatus: undefined,
  timeType: undefined,
  productSupport: undefined,
  result: undefined,
  queryType: undefined,
  finalizationType: 2
});

const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams, dealResult: queryParams.result };
    const res = await listProjectSelection(proxy.addDateRange(params, dateRange.value));
    const list = res.rows || [];
    
    // 异步补全成交结果数据
    if (list.length > 0) {
      const projectNos = list.map(i => i.projectNo).filter(Boolean);
      if (projectNos.length > 0) {
        try {
          const analysisRes = await listSalesResultAnalyze({ objectNos: projectNos.join(',') });
          const analysisMap = {};
          (analysisRes.rows || analysisRes.data || []).forEach(a => {
            analysisMap[a.objectNo] = a.dealResult;
          });
          list.forEach(item => {
            if (item.projectNo && analysisMap[item.projectNo]) {
              item.dealResult = analysisMap[item.projectNo];
            }
          });
        } catch (e) {
          console.error('补全成交结果失败', e);
        }
      }
      
      // 异步补全行业信息 (根据客户动态显示)
      const missingIndustryList = list.filter(i => (i.customNo || i.customerNo) && !i.industryName);
      if (missingIndustryList.length > 0) {
        const uniqueNos = [...new Set(missingIndustryList.map(i => i.customNo || i.customerNo))];
        uniqueNos.forEach(async (no) => {
          try {
            const cRes = await getCustomerInfo(no);
            const cData = cRes.data || cRes;
            const industryId = cData.industryCategoryId || cData.industryId;
            // 尝试从返回的行业名称或根据 ID 从选项中查找
            const industryName = cData.industryName || industryOptions.value.find(o => String(o.id) === String(industryId))?.industryCategoryName;
            if (industryName) {
              list.forEach(item => {
                if ((item.customNo || item.customerNo) === no) {
                  item.industryName = industryName;
                }
              });
              // 触发列表强制更新
              dataList.value = [...list];
            }
          } catch (e) {
            console.error('动态补全行业失败', e);
          }
        });
      }
    }

    dataList.value = list;
    total.value = res.total || 0;
    totalAmount.value = dataList.value.reduce((sum, item) => sum + (Number(item.amount) || 0), 0);
  } catch (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 handleTabChange = (tab) => {
  activeTab.value = tab;
  if (tab === 'mine') queryParams.queryType = 1;
  else if (tab === 'join') queryParams.queryType = 2;
  else delete queryParams.queryType;
  handleQuery();
};

const handleAdd = () => { addVisible.value = true; };
const handleEdit = (row) => { currentId.value = row.id; editVisible.value = true; };
const handleDetail = (row) => { detailDrawerRef.value.open(row); };
const handleProgress = (row) => {
  currentId.value = row.id;
  currentProjectNo.value = row.projectNo;
  progressContent.value = '';
  progressPage.value = 1;
  progressVisible.value = true;
  loadProgress();
};

const loadProgress = async () => {
  if (!currentProjectNo.value) return;
  progressListLoading.value = true;
  try {
    const res = await listRecord({ 
      objectNo: currentProjectNo.value,
      pageNum: progressPage.value,
      pageSize: progressPageSize.value
    });
    progressList.value = res.rows || [];
    progressTotal.value = res.total || 0;
  } catch (err) {
  } finally {
    progressListLoading.value = false;
  }
};

const submitProgress = async () => {
  if (!progressContent.value.trim()) return proxy.$modal.msgWarning("请输入进度内容");
  publishLoading.value = true;
  try {
    await addRecord({
      objectNo: currentProjectNo.value,
      followUpCondition: progressContent.value,
      dataType: '2',
      callDate: proxy.parseTime(new Date(), '{y}-{m}-{d}'),
      callTypeCode: '1',
      callAim: '项目进度跟进'
    });
    proxy.$modal.msgSuccess("发布成功");
    progressContent.value = '';
    progressPage.value = 1;
    loadProgress();
    getList();
  } catch (err) {
    console.error(err);
  } finally {
    publishLoading.value = false;
  }
};

const handleTransfer = () => { transferVisible.value = true; };
const confirmTransfer = async () => {
  if (!transferOwner.value) return proxy.$modal.msgWarning('请选择新负责人');
  const ids = multipleSelection.value.map(item => item.id);
  const user = userOptions.value.find(u => String(u.staffId || u.userId) === String(transferOwner.value));
  try {
    await transferProjectSelection({ 
      ids, leader: transferOwner.value, leaderName: user?.staffName || user?.nickName || '',
      keepOldOwner: keepAsMember.value ? 1 : 0 
    });
    proxy.$modal.msgSuccess('转移成功');
    transferVisible.value = false;
    getList();
  } catch (err) {}
};

const handleDelete = (row) => {
  proxy.$modal.confirm(`确认删除「${row.projectName}」吗？`).then(() => {
    return delProjectSelection(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

const getStatusClass = (status) => {
  const s = String(status);
  if (s === '5') return 'status-success';
  return 'status-following';
};

const handleBatchDelete = () => {
  const ids = multipleSelection.value.map(item => item.id);
  proxy.$modal.confirm(`确认批量删除选中的 ${ids.length} 项记录吗？`).then(() => {
    return delProjectSelection(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("批量删除成功");
  }).catch(() => {});
};

const initOptions = () => {
  listIndustryCategory().then(res => {
    industryOptions.value = res.data || res.rows || [];
  });
  listComStaff({ pageSize: 1000 }).then(r => userOptions.value = r.rows || r.data || []);
  listCompanyOption().then(r => companyOptions.value = r.data);
  deptTreeSelect().then(res => {
    deptOptions.value = res.data;
  });
};

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

onMounted(() => {
  getList();
  initOptions();
});
</script>

<style scoped lang="scss">
.app-container { padding: 15px; 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: 6px; }
  :deep(.el-form-item__label) { white-space: nowrap; font-weight: normal !important; color: #4e5969; }
}



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

.tabs-control {
  display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;
  .tabs-left { display: flex; align-items: center; gap: 20px;
    .page-title { font-size: 16px; color: #333; font-weight: normal; }
    .tab-items { display: flex; gap: 10px;
      .tab-item { padding: 6px 15px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px; color: #606266; cursor: pointer; transition: all 0.2s; position: relative; background: #fff;
        &:hover { color: #409eff; border-color: #c6e2ff; background-color: #ecf5ff; }
        &.current { color: #409eff; border-color: #409eff; background-color: #ecf5ff; }
        &.badge-item { padding-right: 25px; }
        .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); }
      }
    }
    .summary-info { font-size: 14px; color: #f56c6c; margin-left: 10px;
      .total-value { font-size: 16px; font-weight: normal; margin: 0 4px; }
    }
  }
  .tabs-right {
    .action-btns { display: flex; gap: 10px; }
  }
}
.table-card { border: none; }
.standard-table {
  :deep(th.el-table__cell) { background-color: #f8fafc !important; color: #475569; font-weight: normal; }
}

.project-name-link { color: #409eff; cursor: pointer; &:hover { text-decoration: underline; } }

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

.progress-publish-box {
  padding-bottom: 20px;
  .publish-footer {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }
}

.progress-container {
  padding: 0 10px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.progress-list {
  flex: 1;
  overflow-y: auto;
  padding-top: 10px;
  .progress-item {
    padding: 15px 0;
    .item-header {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .user-name { color: #333; font-size: 14px; margin-right: 15px; }
      .time { color: #333; font-size: 14px; }
    }
    .item-content {
      font-size: 14px;
      color: #333;
      line-height: 1.6;
      word-break: break-all;
    }
  }
}

.progress-pagination {
  margin-top: 10px;
  padding-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 状态标签通用样式 */
.status-tag {
  display: inline-block;
  padding: 1px 8px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 18px;
  border: 1px solid transparent;
}

/* 跟进中 - 橙色 */
.status-following {
  background-color: #fff7e8;
  color: #ff7d00;
  border-color: #ffcf8b;
}

/* 结案/成功 - 绿色 */
.status-success {
  background-color: #e8ffea;
  color: #00b42a;
  border-color: #aff0b5;
}
.standard-table {
  :deep(.project-name-link) {
    color: #409eff !important;
    text-decoration: none !important;
    border-bottom: none !important;
    cursor: pointer;
    &:hover {
      color: #66b1ff !important;
      text-decoration: none !important;
    }
  }
}
</style>
