<template>
  <div class="app-container">
    <!-- 1. 顶部搜索筛选表单 -->
    <el-card class="box-card" shadow="never">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px" class="search-form">
        <el-form-item label="岗位等级" prop="level">
          <el-select v-model="queryParams.level" placeholder="全部" clearable style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="初级" value="1" />
            <el-option label="中级" value="2" />
            <el-option label="高级" value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="测评状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部状态" clearable style="width: 200px">
            <el-option label="全部状态" value="" />
            <el-option label="在售" value="1" />
            <el-option label="已撤下" value="2" />
            <el-option label="删除" value="3" />
            <el-option label="待上架" value="4" />
            <el-option label="已下架" value="5" />
          </el-select>
        </el-form-item>

        <el-form-item label="岗位类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="全部状态" clearable style="width: 200px">
             <el-option label="全部状态" value="" />
             <el-option label="全职" value="1" />
             <el-option label="实习" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="价格区间" prop="priceRange">
          <el-select v-model="queryParams.priceRange" placeholder="全部" clearable style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="0-500" value="0-500" />
            <el-option label="500-1000" value="500-1000" />
            <el-option label="1000以上" value="1000+" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间" style="width: 308px">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="测评名称" prop="kwd">
          <el-input
            v-model="queryParams.kwd"
            placeholder="测评名称/ID"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          >
            <!-- 假设项目配置了 element plus 图标自动导入 -->
            <template #prefix><i-ep-search /></template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <!-- 动态统计已选条件 -->
      <div class="filter-count">
        已选择 <span class="highlight">{{ filterCount }}</span> 个筛选条件
      </div>
    </el-card>

    <!-- 2. 数据表格区 -->
    <el-card class="box-card mt10" shadow="never">
      <!-- 2.1 快捷操作栏 -->
      <div class="toolbar">
        <div class="left-actions">
           <!-- 表格外全选控制，也可依赖表格内置的全选功能 -->
           <el-checkbox v-model="selectAll" @change="handleSelectAll" style="margin-right: 15px;">全选</el-checkbox>
           <el-button plain size="small" :disabled="multiple" @click="handleBatchDelete">批量删除</el-button>
           <el-button plain size="small" :disabled="multiple" @click="handleBatchOffline">批量下架</el-button>
           <el-button plain size="small" :disabled="multiple" @click="handleBatchOnline">批量上架</el-button>
        </div>
        <div class="right-actions">
           <el-button plain size="small" @click="handleExport">导出数据</el-button>
           <el-button plain size="small" @click="getList">刷新</el-button>
           <el-button plain size="small" @click="handleSyncUnit">同步至单位</el-button>
           <el-button plain size="small" @click="handleSyncStaff">同步至员工</el-button>
           <el-button type="primary" size="small" @click="handleAdd">新增测评</el-button>
        </div>
      </div>

      <!-- 2.2 表格主体 -->
      <el-table ref="tableRef" v-loading="loading" :data="assessmentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        
        <el-table-column label="测评图片" align="center" width="90">
          <template #default="scope">
            <el-image
                class="assessment-img"
                :src="scope.row.imageUrl"
                fit="cover"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="测评信息" align="left" min-width="220">
          <template #default="scope">
            <div class="info-title">{{ scope.row.title }}</div>
            <div class="info-id">ID: {{ scope.row.id }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="岗位类型" align="center" prop="type" width="100" />
        
        <el-table-column label="单价" align="center" prop="price" width="120">
          <template #default="scope">
            ¥{{ Number(scope.row.price).toLocaleString('zh-CN', {minimumFractionDigits: 2}) }}
          </template>
        </el-table-column>
        
        <el-table-column label="状态" align="center" prop="activeStatus" width="100">
          <template #default="scope">
            <!-- switch的颜色，符合原型的开启为蓝色 -->
            <el-switch
              v-model="scope.row.activeStatus"
              :active-value="true"
              :inactive-value="false"
              style="--el-switch-on-color: #409eff;"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="报名人数" align="center" prop="salesVolume" width="100">
          <template #default="scope">
             <el-link type="primary" :underline="false" @click="handleApplicantList(scope.row)">
               {{ scope.row.salesVolume }}
             </el-link>
          </template>
        </el-table-column>
        
        <el-table-column label="通过率" align="center" prop="passRate" width="100">
          <template #default="scope">
            {{ scope.row.passRate }}%
          </template>
        </el-table-column>
        
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        
        <el-table-column label="状态" align="center" prop="statusLabel" width="100">
          <template #default="scope">
            <!-- 状态带颜色 -->
            <span :class="getStatusClass(scope.row.statusLabel)">{{ scope.row.statusLabel }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link type="primary" :underline="false" style="margin-right: 12px;" @click="handleView(scope.row)">查看</el-link>
            <el-link type="primary" :underline="false" @click="handleUpdate(scope.row)">编辑</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 2.3 底部同款分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
           显示 {{ (queryParams.pageNum - 1) * queryParams.pageSize + 1 }} 
           到 {{ Math.min(queryParams.pageNum * queryParams.pageSize, total) }} 条，
           共 {{ total }} 条
        </div>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="prev, pager, next, sizes"
          :total="total"
          @size-change="getList"
          @current-change="getList"
        />
      </div>
    </el-card>

    <!-- 3. 同步至单位弹窗 -->
    <el-dialog title="同步测评" v-model="syncUnitOpen" width="550px" append-to-body>
      <el-form :model="syncUnitForm" label-width="80px">
        <el-form-item label="同步公司" prop="companyIds">
          <el-select v-model="syncUnitForm.companyIds" multiple collapse-tags placeholder="请选择公司" style="width: 100%">
            <el-option v-for="item in companyOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="padding-top: 20px;">
          <el-button @click="syncUnitOpen = false" style="background-color: #f4f4f5; border: none;">取消</el-button>
          <el-button type="primary" @click="submitSyncUnit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 4. 同步至员工弹窗 -->
    <el-dialog title="同步测评" v-model="syncStaffOpen" width="550px" append-to-body>
      <el-form :model="syncStaffForm" label-width="80px">
        <el-form-item label="同步人员" prop="userIds">
          <el-select v-model="syncStaffForm.userIds" multiple collapse-tags placeholder="请选择人员" style="width: 100%">
            <el-option v-for="item in staffOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="padding-top: 20px;">
          <el-button @click="syncStaffOpen = false" style="background-color: #f4f4f5; border: none;">取消</el-button>
          <el-button type="primary" @click="submitSyncStaff">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';

// 假设这些来自 RuoYi 封装的 Hooks / API，您需要根据真实情况导入
// import { listAssessment, mockApiCall... } from "@/api/business/assessment";

/** ---- 参考变量名和业务数据声明 ---- */
const router = useRouter();
const loading = ref(false);
const total = ref(12568);
const dateRange = ref([]);
const queryRef = ref();
const tableRef = ref();

// "全选" 与 多选操作禁用判断
const selectAll = ref(false);
const multiple = ref(true); // 是否多选为空，空为true即禁用

// 查询的表单数据结构定义 (参考接口)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  level: '',
  status: '',
  type: '',
  priceRange: '',
  kwd: ''
});

// 同步相关状态
const syncUnitOpen = ref(false);
const syncStaffOpen = ref(false);
const syncUnitForm = reactive({ companyIds: [] });
const syncStaffForm = reactive({ userIds: [] });

// 模拟选项数据 (实际需从接口获取)
const companyOptions = ref([
  { id: 1, name: '北京星火科技有限公司' },
  { id: 2, name: '上海众行贸易有限公司' },
  { id: 3, name: '广州南方软件开发单位' }
]);
const staffOptions = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' }
]);

/** ---- 计算有多少个过滤条件 (对应：已选择 0 个筛选条件) ---- */
const filterCount = computed(() => {
  let count = 0;
  if (queryParams.level) count++;
  if (queryParams.status) count++;
  if (queryParams.type) count++;
  if (queryParams.priceRange) count++;
  if (queryParams.kwd) count++;
  if (dateRange.value && dateRange.value.length === 2) count++;
  return count;
});

/** ---- 获取状态对应文字颜色的工具函数 ---- */
const getStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    '在售': 'text-success',
    '删除': 'text-danger',
    '待上架': 'text-warning',
    '已下架': 'text-info',
    '已撤下': 'text-danger' // 按需定义
  };
  return statusMap[status] || 'text-info';
};

/** ---- 模拟UI中填充的数据（您将在 getList 中从接口获取真实数据赋值） ---- */
const assessmentList = ref<any[]>([
  {
    id: 'SP-2023-5896',
    title: '审计员/审计助理在线测验',
    imageUrl: 'https://via.placeholder.com/40',
    type: '全职',
    price: 1299.00,
    activeStatus: true,
    salesVolume: 896,
    passRate: 89.4,
    createTime: '2023-06-15 09:23',
    statusLabel: '在售'
  },
  {
    id: 'SP-2023-5895',
    title: '审计员测验',
    imageUrl: 'https://via.placeholder.com/40',
    type: '实习',
    price: 89.00,
    activeStatus: true,
    salesVolume: 1254,
    passRate: 89.4,
    createTime: '2023-06-14 15:47',
    statusLabel: '在售'
  },
  {
    id: 'SP-2023-5894',
    title: '审计员/审计助理在线测验',
    imageUrl: 'https://via.placeholder.com/40',
    type: '全职',
    price: 3299.00,
    activeStatus: false,
    salesVolume: 328,
    passRate: 89.4,
    createTime: '2023-06-13 11:32',
    statusLabel: '在售'
  },
  {
    id: 'SP-2023-5893',
    title: '审计员/审计助理在线测验',
    imageUrl: 'https://via.placeholder.com/40',
    type: '全职',
    price: 299.00,
    activeStatus: true,
    salesVolume: 568,
    passRate: 89.4,
    createTime: '2023-06-12 10:15',
    statusLabel: '删除'
  }
]);

/** ---- 表格操作交互方法 ---- */
const getList = () => {
    // loading.value = true;
    // 调用实际 API: listAssessment(queryParams, dateRange).then(res => { ... })
};

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

const resetQuery = () => {
  dateRange.value = [];
  queryRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: any[]) => {
  multiple.value = !selection.length;
  // 同步更新上方的全选复选框
  selectAll.value = selection.length > 0 && selection.length === assessmentList.value.length;
};

// 头部的全选勾选框逻辑
const handleSelectAll = (val: boolean) => {
  if (val) {
    assessmentList.value.forEach(row => {
      tableRef.value!.toggleRowSelection(row, true);
    });
  } else {
    tableRef.value!.clearSelection();
  }
};

/** ---- 以下为您需要接入实际业务接口的回调方法 ---- */
const handleBatchDelete = () => { /* 调用批量删除接口 */ };
const handleBatchOffline = () => { /* 调用批量下架接口 */ };
const handleBatchOnline = () => { /* 调用批量上架接口 */ };
const handleExport = () => { /* 调用导出 */ };
const handleSyncUnit = () => {
  syncUnitForm.companyIds = [];
  syncUnitOpen.value = true;
};
const handleSyncStaff = () => {
  syncStaffForm.userIds = [];
  syncStaffOpen.value = true;
};
const handleApplicantList = (row: any) => {
  router.push(`/system/assessment/applicant-list?assessmentId=${row.id}`);
};
const submitSyncUnit = () => {
  // 接入实际接口：api.syncToUnits(syncUnitForm.companyIds)
  syncUnitOpen.value = false;
};
const submitSyncStaff = () => {
  // 接入实际接口：api.syncToStaff(syncStaffForm.userIds)
  syncStaffOpen.value = false;
};
const handleAdd = () => {
  router.push('/system/assessment/detail');
};
const handleStatusChange = (row: any) => { /* 调用状态修改 switch 切换接口 */ };
const handleView = (row: any) => { /* 查看详情弹窗或页面 */ };
const handleUpdate = (row: any) => {
  router.push(`/system/assessment/detail?id=${row.id}`);
};

// 初始化
getList();
</script>

<style scoped>
/* 基本间距样式重置 */
.app-container {
  padding: 20px;
}
.mt10 {
  margin-top: 10px;
}
/* 搜索表单内部间距 */
.search-form .el-form-item {
  margin-bottom: 12px;
}
.filter-count {
  font-size: 13px; 
  color: #606266; 
  margin-bottom: 10px;
}
.filter-count .highlight {
  color: #409eff;
  font-weight: 500;
}

/* 操作面板居两端对齐 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 测评信息结构图片与文字样式 */
.assessment-img {
  width: 45px; 
  height: 45px; 
  border-radius: 4px; 
  display: block; 
  margin: 0 auto;
}
.info-title {
  font-weight: 500; 
  font-size: 14px; 
  color: #303133;
}
.info-id {
  color: #909399; 
  font-size: 12px;
  margin-top: 2px;
}

/* 自定义底部左文字右分页样式，模拟蓝湖原型 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}
.pagination-info {
  font-size: 13px;
  color: #606266;
}

/* 状态颜色定义 */
.text-success { color: #13ce66; }
.text-danger { color: #f56c6c; }
.text-warning { color: #e6a23c; }
.text-info { color: #909399; }
</style>
