<template>
  <div class="backcheck-container">
    <el-container class="h-full">
      <!-- 左侧分类侧边栏 -->
      <el-aside width="200px" class="mr-4 h-full sidebar modern-card">
        <div class="sidebar-title">背调分类</div>
        <el-menu :default-active="activeMenu" class="border-none mt-2" @select="handleMenuSelect">
          <el-menu-item v-for="c in categories" :key="c.id" :index="c.id" :class="{ 'menu-item-active': c.id === activeMenu }">
            <template #title>
              <el-icon>
                <component :is="c.icon" />
              </el-icon>
              <span>{{ c.name }} ({{ c.count }})</span>
            </template>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧主体内容 -->
      <el-main class="h-full main-content p-0 flex flex-col modern-card">
        <!-- 搜索与头部区域 -->
        <div class="header-section flex justify-between items-center px-4 py-4 shrink-0">
          <div class="flex items-center">
             <el-input v-model="queryParams.keyword" placeholder="搜索单位名称..." style="width: 300px" clearable @keyup.enter="handleQuery" :prefix-icon="Search">
                <template #append>
                   <el-button :icon="Search" @click="handleQuery" />
                </template>
             </el-input>
          </div>
          
          <div>
             <el-button type="primary" class="create-btn" :icon="Plus" @click="handleCreate">创建条款模板</el-button>
          </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-section flex-1 overflow-auto px-4">
          <el-table :data="tableData" v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange" header-cell-class-name="custom-header">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="companyName" label="下单企业" min-width="150" align="center" />
            <el-table-column label="候选人" min-width="120" align="center">
              <template #default="scope">
                <el-link type="primary" :underline="false" class="font-bold" @click="goCandidateList(scope.row)">
                  {{ scope.row.candidateCount }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column label="状态" min-width="120" align="center">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ statusMap[scope.row.status] || scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
        <el-table-column label="下单金额" min-width="150" align="center">
          <template #default="scope">
            <span class="amount-text">￥{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
            <el-table-column label="操作" width="160" align="center" fixed="right">
              <template #default="scope">
                 <el-link type="primary" :underline="false" class="mx-2" @click="handleAction(scope.row, 'view')">
                   查看详情
                 </el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-wrapper flex justify-end px-4 py-4 shrink-0">
           <el-pagination 
             background 
             layout="total, sizes, prev, pager, next" 
             :total="total"
             :page-size="queryParams.pageSize"
             :current-page="queryParams.pageNum"
             @size-change="handleSizeChange"
             @current-change="handleCurrentChange"
           />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Search, Plus } from '@element-plus/icons-vue';
import { listBackCategory } from '@/api/system/backCategory';
import { BackCategoryVO } from '@/api/system/backCategory/types';
import { listBackOrder } from '@/api/system/backOrder';
import { BackOrderVO } from '@/api/system/backOrder/types';

const router = useRouter();
const queryParams = reactive({ 
  keyword: '',
  categoryId: undefined as number | undefined,
  pageNum: 1,
  pageSize: 10
});
const activeMenu = ref('');
const total = ref(0);
const loading = ref(false);

const categories = ref<any[]>([]);
const tableData = ref<BackOrderVO[]>([]);

/** 查询分类列表 */
const getCategoryList = async () => {
  const { data } = await listBackCategory();
  // 先把结构定下来
  categories.value = data.map((item: BackCategoryVO) => ({
    id: item.id.toString(),
    name: item.name,
    count: 0,
    icon: 'i-ep-document'
  }));

  if (categories.value.length > 0 && !activeMenu.value) {
    activeMenu.value = categories.value[0].id;
    queryParams.categoryId = Number(categories.value[0].id);
  }

  // 异步获取真实的分类统计数据
  categories.value.forEach(async (cat: any) => {
    try {
      const res: any = await listBackOrder({ categoryId: Number(cat.id), pageSize: 1, pageNum: 1 });
      if (res && res.total !== undefined) {
        cat.count = res.total;
      }
    } catch (e) {
      console.error(`获取分类 ${cat.name} 数量失败:`, e);
    }
  });
};

/** 查询订单列表 */
const getOrderList = async () => {
  loading.value = true;
  try {
    const data: any = await listBackOrder(queryParams);
    if (data && data.rows) {
      tableData.value = data.rows;
      total.value = data.total || 0;
      // 同步更新左侧侧边栏中当前分类的数量
      const currentCat = categories.value.find(c => c.id === activeMenu.value);
      if (currentCat) {
        currentCat.count = total.value;
      }
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};


onMounted(async () => {
  await getCategoryList();
  await getOrderList();
});

const statusMap: Record<string, string> = {
  '0': '待处理',
  '1': '进行中',
  '2': '已完成',
  '3': '已退款'
};

const getStatusType = (status: string) => {
  const map: Record<string, any> = {
    '0': 'info',
    '1': 'warning',
    '2': 'success',
    '3': 'danger'
  };
  return map[status] || 'info';
};

const handleSelectionChange = () => {};

const handleMenuSelect = (key: string) => {
  activeMenu.value = key;
  queryParams.categoryId = Number(key);
  queryParams.pageNum = 1;
  getOrderList();
};

// 点击“候选人”数字，前往候选人详情列表
const goCandidateList = (row: any) => {
  router.push({ name: 'BackcheckCandidateList', query: { id: row.id } });
};

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

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;
  getOrderList();
};

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getOrderList();
};

// 创建条款
const handleCreate = () => {
  router.push('/system/backclause/index');
};

// 点击操作列（起做、查看）
const handleAction = (row: any, type: string) => {
  goCandidateList(row);
};
</script>

<style scoped lang="scss">
.backcheck-container {
  padding: 20px;
  background-color: #f0f2f5;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
}

.sidebar {
  height: 100%;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  .sidebar-title {
    padding: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    border-bottom: 1px solid #f2f6fc;
  }
  .el-menu {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
    background: transparent;
  }
  .el-menu-item {
    height: 50px;
    line-height: 50px;
    margin-bottom: 4px;
    border-radius: 8px;
    &:hover {
      background-color: #f5f7fa;
    }
    &.is-active {
       background-color: #ecf5ff;
       font-weight: 600;
    }
  }
  .menu-item-active {
    background-color: #ecf5ff !important;
    color: #409eff;
  }
}

.main-content {
  border-radius: 4px;
  height: 100%;
  overflow: hidden;
}

.header-section {
  background-color: #fff;
  border-bottom: 1px solid #f2f3f5;
  .search-btn {
    border-radius: 0 4px 4px 0;
  }
  .create-btn {
    background-color: #409eff;
  }
}

.table-section {
  background-color: #fff;
  padding: 0 16px;
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  :deep(.el-table) {
    flex: 1;
    .el-table__inner-wrapper {
      height: 100% !important;
    }
  }
}

.amount-text {
  font-weight: 600;
  color: #ff4d4f;
}

:deep(.custom-header th) {
  background-color: #f7f8fa !important;
  color: #4e5969;
  font-weight: 500;
  padding: 12px 0;
}

.pagination-wrapper {
  background-color: #fff;
  border-top: 1px solid #f2f3f5;
  padding: 12px 16px;
}
</style>
