<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" label-width="85px">
        <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 || 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="String(item.staffId || item.userId)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 5px;">
          <el-col :span="6">
            <el-form-item label="部门" prop="deptId">
              <el-select v-model="queryParams.deptId" placeholder="所属部门" style="width: 100%" clearable>
                <el-option v-for="item in deptOptions" :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="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="projectLevel">
              <el-select v-model="queryParams.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="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.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 5px;">
           <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.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </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.dictValue" :label="item.dictLabel || item.label" :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 resultOptions" :key="item.dictValue" :label="item.dictLabel" :value="Number(item.dictValue)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="查询类型" prop="timeType" label-width="85px">
              <el-select v-model="queryParams.timeType" style="width: 100%" clearable>
                <el-option v-for="item in timeTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="Number(item.dictValue)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 5px;">
          <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="16">
            <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="tabs-control">
      <div class="tabs-left">
        <div class="list-title">年度入围（项目）信息列表</div>
        <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 v-if="totalCountBadge > 99" class="badge">99+</span>
            <span v-else-if="totalCountBadge > 0" class="badge">{{ totalCountBadge }}</span>
          </div>
        </div>
        <div class="summary-line">
           <span class="stripe-total">金额总计<span class="red-text">{{ Number(totalAmount).toFixed(2) }}</span> (万)</span>
        </div>
      </div>
      <div class="stripe-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="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="center" prop="projectName" min-width="240" show-overflow-tooltip fixed>
          <template #default="scope">
            <span class="project-name-link" @click="handleUpdate(scope.row)">{{ scope.row.projectName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属公司" align="center" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ companyOptions.find(c => (c.companyCode || c.id) === scope.row.companyNo)?.companyName || scope.row.companyNo }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.customerName || scope.row.customName || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="项目级别" align="center" prop="projectLevel" width="100">
          <template #default="scope">
            <span>{{ projectLevelOptions.find(o => String(o.dictValue || o.value) === String(scope.row.projectLevel))?.dictLabel || projectLevelOptions.find(o => String(o.dictValue || o.value) === String(scope.row.projectLevel))?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目类型" align="center" prop="businessType" width="100">
          <template #default="scope">
            <span>{{ projectTypeOptions.find(o => String(o.dictValue || o.value) === String(scope.row.businessType))?.dictLabel || projectTypeOptions.find(o => String(o.dictValue || o.value) === String(scope.row.businessType))?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额(万)" align="center" prop="amount" width="100" sortable />
        <el-table-column label="服务期(年)" align="center" prop="standardPeriod" width="100" />
        <el-table-column label="服务时间段" align="center" prop="serviceTime" width="150" show-overflow-tooltip />
        <el-table-column label="投标截止时间" align="center" prop="tenderDeadline" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.tenderDeadline, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门编号" align="center" prop="deptNo" width="100" />
        <el-table-column label="负责人" align="center" prop="leaderName" width="100" />
        <el-table-column label="产品支持" align="center" prop="productSupport" width="100" />
        <el-table-column label="赢单率(%)" align="center" prop="winningRate" width="100" />
        <el-table-column label="行业" align="center" prop="profession" width="120">
          <template #default="scope">
            {{ (() => { const v = String(scope.row.profession || ''); const p = professionOptions.find(i => String(i.id) === v || String(i.industryCategoryId) === v || String(i.industryId) === v || String(i.dictValue) === v); return p?.industryCategoryName || scope.row.profession; })() }}
          </template>
        </el-table-column>
        <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="signUpDeadline" width="110" sortable>
          <template #default="scope">
            <span>{{ parseTime(scope.row.signUpDeadline, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入围类型" align="center" prop="shortlistedType" width="100">
          <template #default="scope">
            <span>{{ shortlistedTypeOptions.find(o => String(o.dictValue || o.value) === String(scope.row.shortlistedType))?.dictLabel || shortlistedTypeOptions.find(o => String(o.dictValue || o.value) === String(scope.row.shortlistedType))?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目状态" align="center" prop="projectStatus" width="100">
          <template #default="scope">
            <el-tag 
              v-if="statusOptions.find(o => String(o.dictValue || o.value) === String(scope.row.projectStatus))"
              :class="['custom-status-tag', String(scope.row.projectStatus) === '1' ? 'status-follow' : 'status-done']"
              effect="plain"
            >
              {{ statusOptions.find(o => String(o.dictValue || o.value) === String(scope.row.projectStatus))?.dictLabel || statusOptions.find(o => String(o.dictValue || o.value) === String(scope.row.projectStatus))?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" width="220" fixed="right">
          <template #header>
            <div style="display: flex; align-items: center; justify-content: center; gap: 4px;">
              <span>操作</span>
              <el-icon class="cursor-pointer" style="font-size: 16px; color: #606266;"><Setting /></el-icon>
            </div>
          </template>
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center; gap: 12px;">
              <el-button link class="action-btn-gray" @click="handleUpdate(scope.row)">详情</el-button>
              <el-button link type="primary" @click="handleProgress(scope.row)">进度</el-button>
              <el-button link class="action-btn-gray" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </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>

    <!-- 年度入围录入抽屉 -->
    <ProjectSelectionDrawer ref="drawerRef" v-model="open" :title="title" :data="form" @submit="submitForm" />

    <!-- 弹窗：转移他人 -->
    <el-dialog title="是否将选中的年度入围转移给其他负责人？" v-model="transferVisible" width="550px">
       <el-form label-width="100px" style="padding: 20px 0;">
         <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.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>  </div>
</template>

<script setup name="ProjectSelection">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { listProjectSelection, getProjectSelection, delProjectSelection, addProjectSelection, updateProjectSelection, transferProjectSelection } from '@/api/saleManage/projectSelection/index';
import ProjectSelectionDrawer from './ProjectSelectionDrawer.vue';
import { listCommonDict } from "@/api/customer/customerDict";
import { selectStaffOptionList } from "@/api/system/comStaff/index";
import { listCompanyOption } from "@/api/customer/customerInfo/index";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { Setting } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

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

const open = ref(false);
const title = ref("");
const activeTab = ref('all');
const totalCountBadge = ref(0);
const drawerRef = ref(null);
const transferVisible = ref(false);
const transferOwner = ref('');
const keepAsMember = ref(false);
const queryParams = reactive({
  pageNum: 1, pageSize: 10,
  companyNo: undefined, projectName: undefined, customerName: undefined, leader: undefined,
  deptNo: undefined, productSupport: undefined, projectLevel: undefined, businessType: undefined, projectStatus: undefined,
  shortlistedType: undefined, result: undefined, timeType: undefined
});

const form = ref({});

const getList = async () => {
  loading.value = true;
  try {
    const res = await listProjectSelection(proxy.addDateRange(queryParams, dateRange.value));
    dataList.value = res.rows || [];
    total.value = res.total || 0;
    // 计算统计金额（当前页）
    totalAmount.value = dataList.value.reduce((sum, item) => sum + (Number(item.amount) || 0), 0);
    // 获取全部年度入围总数用于徽标
    try {
      const allRes = await listProjectSelection({ pageNum: 1, pageSize: 1 });
      totalCountBadge.value = allRes.total || 0;
    } catch (e) { /* ignore */ }
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    id: undefined, companyNo: '', customerName: '', projectLevel: undefined, businessType: undefined, leader: '', projectName: '',
    amount: undefined, entryFee: undefined, bidBond: undefined, winningRate: undefined,
    signUpDeadline: '', tenderDeadline: '', standardPeriod: undefined, serviceTime: '',
    shortlistedType: undefined, profession: undefined, biddingAgency: '', agencyContact: '',
    bidPeriodType: 1, projectDesc: ''
  };
};

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

/** Tab 切换 */
const handleTabChange = (tab) => {
  if (activeTab.value === tab) return;
  activeTab.value = tab;
  // 根据 Tab 类型设置查询参数
  switch (tab) {
    case 'mine':
      // 我负责的
      queryParams.queryType = 1;
      break;
    case 'join':
      // 我参与的
      queryParams.queryType = 2;
      break;
    case 'all':
      // 全部年度入围
      delete queryParams.queryType;
      break;
  }
  handleQuery();
};
const resetQuery = () => { dateRange.value = []; proxy.resetForm("queryRef"); handleQuery(); };
const handleSelectionChange = (selection) => { multipleSelection.value = selection; };
const handleAdd = () => { reset(); open.value = true; title.value = "新增年度入围项目"; };

const handleUpdate = async (row) => {
  reset();
  const id = row.id || (multipleSelection.value.length > 0 ? multipleSelection.value[0].id : null);
  if (!id) return;
  try {
    const res = await getProjectSelection(id);
    form.value = res.data;
    open.value = true;
    title.value = "年度入围项目详情";
  } catch (err) {
    console.error('获取详情失败:', err);
  }
};

const handleTransfer = () => { transferVisible.value = true; };
const confirmTransfer = async () => {
  if (!transferOwner.value) {
    proxy.$modal.msgWarning('请选择新负责人');
    return;
  }
  const ids = multipleSelection.value.map(item => item.id);
  try {
    await transferProjectSelection({ ids, newLeaderId: transferOwner.value, keepAsMember: keepAsMember.value });
    proxy.$modal.msgSuccess('转移成功');
    transferVisible.value = false;
    getList();
  } catch (err) {
    console.error('权属转移失败:', err);
  }
};

const handleProgress = async (row) => {
  // 先加载项目数据并打开抽屉
  const res = await getProjectSelection(row.id);
  form.value = res.data;
  open.value = true;
  // 延迟一确保抽屉已渲染
  setTimeout(() => {
    drawerRef.value?.openProgressDrawer();
  }, 100);
};

const submitForm = async (formData) => {
  if (formData.id !== undefined) {
    await updateProjectSelection(formData);
    proxy.$modal.msgSuccess("修改成功");
  } else {
    await addProjectSelection(formData);
    proxy.$modal.msgSuccess("新增成功");
  }
  open.value = false;
  getList();
};

const handleDelete = (row) => { 
  const ids = row.id || multipleSelection.value.map(item => item.id);
  proxy.$modal.confirm(`是否确认删除记录？`).then(() => {
    return delProjectSelection(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

const handleBatchDelete = () => { handleDelete({}); };

const projectLevelOptions = ref([]);
const projectTypeOptions = ref([]);
const shortlistedTypeOptions = ref([]);
const professionOptions = ref([]);
const userOptions = ref([]);
const companyOptions = ref([]);

// 搜索区新增选项 - 全部从后端获取
const statusOptions = ref([]);
const resultOptions = ref([]);
const timeTypeOptions = ref([]);
const deptOptions = ref([]);

function getProjectLevelList() { listCommonDict('XMJB0001').then(r => projectLevelOptions.value = r.data); }
function getProjectTypeList() { listCommonDict('L0001').then(r => projectTypeOptions.value = r.data); }
function getShortlistedTypeList() { listCommonDict('R0001').then(r => shortlistedTypeOptions.value = r.data); }
function getProfessionList() { listIndustryCategory().then(r => professionOptions.value = r.data); }
function getUserList() { selectStaffOptionList().then(r => userOptions.value = r.data); }
function getCompanyList() { listCompanyOption().then(r => companyOptions.value = r.data); }
// 项目状态
function getStatusList() {
  listCommonDict('J0001').then(r => {
    statusOptions.value = r.data;
  });
}
// 成交结果
function getResultList() { listCommonDict('deal_result').then(r => resultOptions.value = r.data || []); }
// 查询类型
function getTimeTypeList() { listCommonDict('time_query_type').then(r => timeTypeOptions.value = r.data || []); }
// 部门
import { deptTreeSelect } from "@/api/system/user";
function getDeptList() {
  deptTreeSelect().then(res => {
    const flatList = (list) => {
      let arr = [];
      for (const item of list || []) {
        arr.push({ label: item.label, value: Number(item.id) || item.id });
        if (item.children?.length) arr.push(...flatList(item.children));
      }
      return arr;
    };
    deptOptions.value = flatList(res.data);
  });
}

onMounted(() => {
  getList();
  getProjectLevelList();
  getProjectTypeList();
  getShortlistedTypeList();
  getProfessionList();
  getUserList();
  getCompanyList();
  getStatusList();
  getResultList();
  getTimeTypeList();
  getDeptList();
});
</script>

<style scoped lang="scss">
.custom-status-tag {
  border-radius: 4px;
  border-width: 1px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-weight: 500;
  
  &.status-follow {
    background-color: #fff7e8;
    border-color: #ffe4ba;
    color: #ff7d00; // 橙色文字
  }
  
  &.status-done {
    background-color: #e8ffea;
    border-color: #aff0b5;
    color: #00b42a; // 绿色文字
  }
}
.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; }
}

.search-btns { display: flex; gap: 12px; }

.tabs-control {
  margin: 12px 0 16px; display: flex; align-items: center; justify-content: space-between;
  .tabs-left {
    display: flex; align-items: center; gap: 16px;
    .list-title {
      font-size: 14px; color: var(--el-text-color-primary); font-weight: 400; padding: 0 4px;
    }
  }
  .tab-items {
    display: flex; align-items: center; gap: 8px;
    .tab-item {
      padding: 5px 12px; cursor: pointer; font-size: 13px; color: var(--el-text-color-primary);
      background: var(--el-bg-color); border: 1px solid var(--el-border-color-light); border-radius: 2px;
      position: relative; white-space: nowrap; transition: all 0.2s;
      &.current {
        border-color: var(--el-color-primary); color: var(--el-color-primary);
      }
      &:hover:not(.current) { border-color: var(--el-border-color); }
      &.badge-item {
        margin-right: 8px;
        .badge {
          position: absolute; top: -8px; right: -12px;
          background: var(--el-color-danger); color: #fff; font-size: 10px;
          padding: 0 5px; border-radius: 8px; line-height: 16px;
          min-width: 22px; text-align: center; font-weight: 500;
          box-shadow: 0 0 0 2px var(--el-bg-color);
        }
      }
    }
  }
  .summary-line {
    display: flex; align-items: center; margin-left: 8px;
    .stripe-total { font-size: 13px; color: var(--el-color-danger); .red-text { font-weight: 600; padding: 0 2px; } }
  }
  .stripe-actions { display: flex; gap: 10px; flex-shrink: 0; }
}

.table-card { border: none; }
.standard-table {
  :deep(th.el-table__cell) { background-color: var(--el-fill-color-light) !important; color: var(--el-text-color-regular); font-weight: 600; font-size: 13px; }
  :deep(td.el-table__cell) { font-size: 13px; color: var(--el-text-color-primary); }
  :deep(.el-button--primary.is-link) { color: var(--el-color-primary); &:hover { color: var(--el-color-primary-light-3); } }
  :deep(.el-button--danger.is-link) { color: var(--el-color-danger); &:hover { color: var(--el-color-danger-light-3); } }
}

.action-btn-gray {
  color: var(--el-text-color-regular) !important;
  &:hover {
    color: var(--el-text-color-secondary) !important;
  }
}

.cursor-pointer {
  cursor: pointer;
}

.label-nowrap :deep(.el-form-item__label) { white-space: nowrap !important; }
.dialog-footer { display: flex; justify-content: center; gap: 20px; }
.project-name-link {
  color: var(--el-color-primary);
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}
</style>
