<template>
  <div class="page_item page_list">

    <div class="search_content">
        <div class="content_left">
          <label class="left_title">届别：</label>
          <el-select  v-model="params.graduates"   placeholder="选择届别" @change="GoSearch()" class="select_width" >
            <el-option label="全部届别" value=""></el-option>
            <el-option v-for="item in graduatesList"
              :key="item.value"
              :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-select  v-model="params.levels"   placeholder="选择学段" @change="ChangeLevels()" class="select_width" >
            <el-option label="全部学段" value=""></el-option>
            <el-option v-for="item in levelsList"
              :key="item.value"
              :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-input placeholder="考试名称，编号"  v-model="params.keyWord" @input="GoSearch" @change="GoSearch()" class="input_width" > 
            <el-button @click="GoSearch()"  slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <div class="content_right">
          <el-button @click="Refresh">
            <img src="@/assets/icon/refresh_default.png" />刷新
          </el-button>
          <el-button type="primary" @click="OpenAddExam" >
            <img src="@/assets/icon/add_icon.webp" />新增考试
          </el-button>
        </div>
    </div>
    <FiltersItem :data="filtersData" @select="GetSelect"></FiltersItem>
    <div class="content_list">
      <div class="page_jg_16" v-if="examList.length>0"></div>
      <div class="list_item" v-for="exam in examList">
        <div class="item_left">
          <div class="left_course" :style="{backgroundColor:getCourseBgColor(exam.courseName)}" >
            {{exam.courseName}}
          </div>
          <div class="left_info">
            <div class="info_title">
              {{exam.examSubjectName}}
            </div>
            <div class="info_message">
              <span>时间：{{exam.createDate}}</span>
              <span>年级：{{exam.gradeName}}</span>
              <span>创建人：{{exam.createdBy}}</span>
              <span>考试编号：{{exam.examSubjectCode}}</span>
            </div>
          </div>
        </div>
        <div class="item_right">
          <div class="ele_button right_button">
            
            <span @click="OpenDeleteExam(exam)" class="btn_delete" v-if="exam.canDelete==1">删除</span>
            <span class="btn_disabled" v-else>删除</span>
            <span @click="OpenEditorExam(exam)" class="btn_editor">编辑</span>
            <span @click="GotoExam(exam)" class="btn_editor">进入考试</span>
          </div>
        </div>
      </div>
      <div class="no_content_data" v-if="examList.length==0">
        暂无数据
      </div>
    </div>
    <div class="page_pagination">
      <el-pagination background
        :page-size="pageInfo.pageSize"
        :pager-count="11"
        layout="prev, pager, next"
        :total="pageInfo.total"
        :current-page="pageInfo.pageNum" 
        @current-change="HandlePageChange"
      />
    </div>
    <AddExam ref="addExamRef" :editData="currentEditItem" v-model="showAddExam" @success="HandleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive,onMounted } from 'vue'
import FiltersItem from '@/components/FiltersItem.vue';
import AddExam from '@/components/AddExam.vue' // 注意路径可能需要调整
import { getHeadData,getExamList ,deleteExam} from '@/api/exam'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCourseBgColor } from '@/utils/common' 
import { useRouter } from 'vue-router' 
import { useExamStore } from '@/store/exam'
const examStore = useExamStore()
const router = useRouter()
const showAddExam = ref(false)
// 新增：用于存储当前编辑的数据，null 表示新增模式
const currentEditItem = ref<any>(null)

const params = reactive({
  graduates: '',//届别
  levels: '',//学段
  keyWord: '',//关键词
  gradeCode:'',//年级code
  courseCode:'',//科目code
})
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})//分页信息
// 定义接口类型以增强类型安全（可选但推荐）
interface SearchParams {
  graduates: string;
  levels: string;
  keyWord: string;
}
// 1. 定义过滤项中列表项的类型
interface FilterListItem {
  label: string
  value: string
}

// 2. 定义单个过滤条件的类型
interface FilterItem {
  label: string
  list: FilterListItem[]
  value: string
}


const filtersData=ref<FilterItem[]>([
  {
    label:'年级',
    list:[],
    value:'',
  },
  {
    label:'科目',
    list:[],
    value:'',
  }
]);//过滤条件数据


const graduatesList=ref<any[]>([]);//届别列表
const levelsList=ref<any[]>([]);//学段列表
const examList=ref<any[]>([]);//考试列表


const ChangeLevels = () => {

  GoSearch();
}


//获取头部筛选数据
const GetHeadData=async ()=>{
    try {
    const res = await getHeadData()
    console.log("打印头部数据res",res)
    if (res && res.code === 200 && res.data) {
      //届别数据
      if (res.data.graduates) 
      {
        graduatesList.value = res.data.graduates
      }
      //学段事件
      if (res.data.levels) 
      {
        levelsList.value = res.data.levels
      }
      //年级数据
      if(res.data.grades)
      {
        const allOption = {
          label: '全部',
          value: '' // 通常“全部”对应的值为空字符串，以便筛选时不传参或传空
        }
        filtersData.value[0].list = [allOption,...res.data.grades]
      } 
      if(res.data.courses)
      {
        const allOption = {
          label: '全部',
          value: '' // 通常“全部”对应的值为空字符串，以便筛选时不传参或传空
        }
        filtersData.value[1].list = [allOption,...res.data.courses]
      }
    } else {
      ElMessage.warning(res?.msg || '获取头部数据失败')
    }
  } catch (error) {
    console.error('GetHeadData error:', error)
    ElMessage.error('网络请求异常，请稍后重试')
  }
}

//选择的过滤条件
const GetSelect = (index: number, value: string) => {
  console.log('选择的过滤条件:', index, value)
  filtersData.value[index].value = value
  if (index === 0) 
  {
    params.gradeCode = value

    GoSearch()
  } else if (index === 1) {
    params.courseCode = value

    GoSearch()
  }
}

//搜索
const GoSearch = () => { 
  GetExamList()
}

//分页切换
const HandlePageChange=(newPage: number)=>{
  pageInfo.pageNum = newPage
  GetExamList()
  console.log('分页切换:', newPage)
}
//获取列表数据
const GetExamList = async () => { 
  console.log('搜索参数:', params)
  const param={
    pageNum:pageInfo.pageNum,
    pageSize:pageInfo.pageSize,

    examType:1,//考试类型  1 智能选择题判分   2 智能填空题判分  3 Ai作文
    graduates:params.graduates,
    levelCode:params.levels,
    queryStr:params.keyWord,
    gradeCode:params.gradeCode,
    courseCode:params.courseCode
  };
  const res= await getExamList(param);
  console.log("打印列表数据",res)
  if(res.code==200)
  {
    examList.value=res.data.records;
    pageInfo.total=Number(res.data.total);

  }
}

//刷新列表
const Refresh = () => { 
  params.graduates = ''
  params.levels = ''
  params.keyWord = ''
  params.gradeCode = ''
  params.courseCode = ''
  filtersData.value[0].value = ''
  filtersData.value[1].value = ''
  GoSearch()
  GetHeadData()
}

//考试添加成功 刷新列表
const HandleSuccess = () => {
  console.log('考试新增成功，刷新列表')
  GetHeadData()
  GoSearch();
}

//新增考试
const OpenAddExam = () => {
  showAddExam.value = true
  currentEditItem.value = null
}

//删除考试方法
const OpenDeleteExam=async(item:any) => {
  ElMessageBox.confirm('确认删除该考试吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    console.log('删除考试', item)
    let param={
      id:item.id
    };
    const res = await deleteExam(param)
    if(res.code == 200) {
      ElMessage.success("删除成功!")
      GetHeadData()
      GoSearch()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

//编辑的时候需要把数据传到子组件里
const OpenEditorExam=(item?:any) => {
  console.log("编辑考试",item);
  currentEditItem.value=item || null;//存储当前编辑的数据，null 表示新增模式
  showAddExam.value = true
  
}

//进入考试 把当前的考试信息存储到本地存储中
const GotoExam=(item:any) => {
  console.log("进入考试",item);

  try {
    // localStorage.setItem('current_exam_info', JSON.stringify(item));
    examStore.setExamInfo(item)
    console.log('将当前的考试信息存储到本地:', item)
  } catch (error) {
    console.error('存储考试信息失败:', error)
  }
  router.push({
    path:'/exam/question',
    query:{
      id:item.id
    }
  })
}

// 组件挂载时获取初始数据
onMounted(() => {
  GetHeadData()
  GoSearch()
})
</script>

<style lang="scss" scoped>
.content_list
{
  width: 100%;
  min-height: calc(100vh - 338px);
   box-sizing: border-box;
  // height:auto;
  // overflow-y: auto;
  
  .list_item
  {
    width: 100%;
    height: 75px;
    border-radius: 6px;
    border:1px solid #DCDFE6;
    box-sizing: border-box;
    margin-bottom: 16px;

    display: flex;
    justify-content: space-between;
    align-items: center;

    .item_left
    {
      padding-left: 10px;
      display: flex;
      justify-content: flex-start;
      gap: 10px;
      .left_course
      {
        width: 46px;
        height: 48px;
        // background: #91CC75;
        border-radius: 5px 5px 5px 5px;
        line-height: 48px;
        text-align: center;
        font-weight: 500;
        font-size: 16px;
        color: #FFFFFF;
      }

      .left_info
      {

        .info_title
        {
          width: 100%;
          font-weight: 500;
          font-size: 18px;
          color: #333;
        }

        .info_message
        {
          display: flex;
          justify-content: flex-start;
          gap: 16px;
          font-weight: 400;
          font-size: 14px;
          color: #999;
        }
      }
    }

    .item_right
    {
      padding-right: 15px;
      .right_button
      {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
      }
    }
  }

}
</style>