<template>
  <div class="step_exam_item">
    <div class="left_line"></div>
    <div class="step_item" v-for="(item, index) in menuList" :key="index"  :class="activeIndex==index?(activeIndex==2?'active_score':'active'):''">
      <div class="step_title" @click="MenuChange(index, item)">
        <div class="num_box">
          <span v-if="item.status === 1" class="el-icon-success"></span>
          <span v-else class="step_num">{{ index + 1 }}</span>
        </div>
        <span>{{ item.name }}</span>
      </div>
      <div class="step_desc" v-if="item.name=='成绩查询'">
        <div class="menu_item" :class="childMenuPath==menu.path?'menu_item_active':''" v-for="menu in item.menu" @click="MenuSelect(menu)">
          {{menu.name}}
        </div>
      </div>
      <div v-else class="step_desc" @click="MenuChange(index, item)">
        {{ item.desc }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useExamStore } from '@/store/exam'
import { useAnalysisStore } from '@/store/analysis'
import { queryQuestionGroupByAiId } from '@/api/analysis'

const examStore = useExamStore()
const analysisStore = useAnalysisStore()
const getChildMenuPath = computed(() => analysisStore?.childMenuPath || '');
// --- 响应式数据 ---
const route = useRoute()//读取当前路由对象
const router = useRouter()//访问全局路由方法

const stepOnIndex = ref<number>(0)//步骤索引
const childMenuPath = ref<string>(getChildMenuPath.value)//子级菜单路径
const menuListRaw = ref<any[]>([]) // 用于存储计算后的菜单列表，以便 watch 能检测到变化（如果需要）

// --- 计算属性 ---

// 1. 考试科目 ID
const examSubjectId = computed(() => {
  // 替换为: return makeTemplateStore.examTempDetail?.id
  return examStore.currentExam?.id
})

// 2. 考试状态字符串
const examStateStr = computed(() => {
  // 替换为: return makeTemplateStore.examStateStr
  return examStore.currentExam?.examStateStr
})

// 3. 考试类型 1 选择题 2 填空题 3 Ai作文
const examType=computed(() => {
  return examStore.currentExam?.examType  // 默认为选择题
})
// 考试步骤
const stepFlow = computed(() => {
  return examStore.currentExam?.stepFlow
})
const isShowGroupAnalysis = computed(() => analysisStore?.isShowGroupAnalysis || false);

// 5. 动态菜单列表
const menuList = computed(() => {
  console.log('打印菜单examType', examSubjectId.value, examType.value)
  let list: any[] = []
  if(examType.value==1)
  {
    //选择题判分
    if(stepFlow.value < 2){
      list = [
        { name: '试题结构', number: '1', path: 'question', desc: '建立考试试题结构、设置标答、分组等信息', status: 0 },
        { name: '扫描学生', number: '2', path: 'scanList', desc: '扫描学生，处理扫描异常学生等', status: 0 },
      ];
    }else{
      let analysisMenu = []
      if(isShowGroupAnalysis.value){
        analysisMenu = [
          { name: '成绩单',number: '4', path: 'score' },
          { name: '错题分析',number: '5', path: 'errorAnalysis' },
          { name: '选项明细',number: '6', path: 'optionDetail' },
          { name: '水平分布',number: '7', path: 'levelDistribution' },
          { name: '班级对比',number: '8', path: 'classComparison' },
          { name: '小题分析',number: '9', path: 'questionAnalysis' },
          { name: '分组分析',number: '10', path: 'groupAnalysis' },
          { name: '选项分析',number: '11', path: 'optionAnalysis' },
          { name: '命题分析',number: '12', path: 'propositionAnalysis' },
        ];
      }else{
        analysisMenu = [
          { name: '成绩单',number: '4', path: 'score' },
          { name: '错题分析',number: '5', path: 'errorAnalysis' },
          { name: '选项明细',number: '6', path: 'optionDetail' },
          { name: '水平分布',number: '7', path: 'levelDistribution' },
          { name: '班级对比',number: '8', path: 'classComparison' },
          { name: '小题分析',number: '9', path: 'questionAnalysis' },
          { name: '选项分析',number: '11', path: 'optionAnalysis' },
          { name: '命题分析',number: '12', path: 'propositionAnalysis' },
        ];
      }
      list = [
        { name: '试题结构', number: '1', path: 'question', desc: '建立考试试题结构、设置标答、分组等信息', status: 0 },
        { name: '扫描学生', number: '2', path: 'scanList', desc: '扫描学生，处理扫描异常学生等', status: 0 },
        { name: '成绩查询', number: '3', path: 'analysis/score', desc: '设置每个主观题下的划分区信息及位置', status: 0 ,
          menu:analysisMenu
        },
      ];
    }
  }
  else if(examType.value==2)
  {
    //填空题判分

  }
  else
  {
    //Ai作文

  }
  
 

  

  // // 更新状态
  // const stateStr = String(examStateStr.value || '')
  // list.forEach((item) => {
  //   if (stateStr.includes(item.number)) {
  //     item.status = 1
  //   } else {
  //     item.status = 0
  //   }
  // })

  return list
})

// 6. 激活的菜单索引  只有三种情况
const activeIndex = computed(() => {
  const currentPath = route.path
  if(currentPath=='/exam/question')
  {
    return 0
  }
  else if(currentPath=='/exam/scanList' || currentPath=='/exam/selectExamination' || currentPath=='/exam/examList' || currentPath=='/exam/scanDetail')
  {
    return 1
  }
  else
  {
    return 2
  }
})

// --- 方法 ---

// 获取模板数据
const GetThirdCardData = () => {
  if (!examSubjectId.value) return

  const param = {
    examSubjectId: examSubjectId.value
  }
  
  // 假设 $api 已全局挂载或在 utils 中引入
  // import { examApi } from '@/api/exam'
  ;(window as any).$api?.exam.getExamThirdCardData(param).then((res: any) => {
    console.log('获取模板相关数据 包含第三方卡和系统卡', res)
    if (res.code === 200) {
      localStorage.setItem('templateData', JSON.stringify(res.data.examCardPageVOS))
      localStorage.setItem('usedCardType', res.data.usedCardType)
      
      // 替换为 Store Commit/Action
      // makeTemplateStore.setMarkType(res.data.markType)
      // makeTemplateStore.setUsedCardType(res.data.usedCardType)
      console.warn('请在此处调用 Store 的 action 更新 markType 和 usedCardType')
    }
  })
}

// // 获取考试流程状态
// const GetExamState = () => {
//   const param = {
//     examSubjectId: route.query.id
//   }
  
//   ;(window as any).$api?.reviewBlock.getExamFlowStatus(param).then((res: any) => {
//     console.log('打印考试流程状态返回', res)
//     if (res.code === 200) {
//       const newStateStr = res.data.finished.join(',')
//       // 替换为 Store Commit/Action
//       // makeTemplateStore.setExamStateStr(newStateStr)
//       console.warn('请在此处调用 Store 的 action 更新 examStateStr')
//     }
//   })
// }

// 菜单点击事件
const MenuChange = (index: number, item: any) => {
  console.log('点击菜单', index, item)
  stepOnIndex.value = index
  childMenuPath.value = ''
  // 触发父组件事件
  // 在 <script setup> 中，需要使用 defineEmits
  router.push('/exam/'+item.path)
}

//子级菜单选择事件
const MenuSelect = (menu: any) => { 
  console.log('选择的子菜单', menu)
  stepOnIndex.value = 2;
  childMenuPath.value = menu.path;
  analysisStore.setChildMenuPath(menu.path);
  // 执行路由跳转
  router.push(`/exam/analysis/${menu.path}`)
}
// --- 生命周期 & 监听 ---

// 定义 emits
const emit = defineEmits(['menuChange'])


watch(examStateStr, (newVal) => {
  // 由于 menuList 是 computed 且依赖 examStateStr，它会自动重新计算
  // 如果这里有其他副作用，请保留
  console.log('考试状态发生变化', newVal)
})

onMounted(async () => {
  // 初始化 stepOnIndex
  if (route.path.includes('scanStudentHome')) {
    
    
   
    stepOnIndex.value = 0
   
  }
  const res = await queryQuestionGroupByAiId(examSubjectId.value)
  if (res.code === 200) {
    analysisStore.setIsShowGroupAnalysis(true);
  }else{
    analysisStore.setIsShowGroupAnalysis(false);
  }
})

</script>

<style lang="scss" scoped>
.step_exam_item {
  position: relative;
  height: 100%;
  .left_line {
    position: absolute;
    top: 0;
    left: 15.55px;
    z-index: 6;
    height: 100%;
    width: 0;
    border-left: 1px dashed #C0C4CC;
  }
  .step_item {
    width: 100%;
    position: relative;
    z-index: 7;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    cursor: pointer;
    .step_title {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      width: 100%;
      height: 34px;
      font-size: 16px;
      color: #333333;
      line-height: 34px;
      font-weight: 600;
      border-top-left-radius: 10px;
    }
    .num_box {
      width: 30px;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;

      .el-icon-success::before {
        font-size: 19px;
      }
    }
    .step_num {
      display: block;
      width: 17px;
      height: 17px;
      font-size: 12px;
      text-align: center;
      font-weight: 500;
      line-height: 17px;
      border-radius: 50%;
      background-color: #B0B2B7;
      color: #fff;
    }
    .step_desc {
      padding: 0px 5px 6px 20px;
      font-size: 12px;
      line-height: 16px;
      color: #999999;

      .menu_item
      {
        font-weight: 400;
        font-size: 14px;
        color: #666666;
        line-height: 35px;
        text-indent: 10px;
      }

      .menu_item_active
      {
        color: #fff;
        background-color: #2e64fa;
        border-radius: 4px 4px 4px 4px;
      }
    }
    &.success {
      border-color: #fff;
      .num_box > span {
        color: #15bc83;
      }
    }
    &.active {
      border-color: #2e64fa;
      background-color: rgba(46, 100, 250, 0.1);
      box-shadow: inset 1px -1px 0px 1.5px #2e64fa;

      // background-color: red;
      .step_title {
        background-color: #2e64fa;
        color: #fff;
      }
      .step_num {
        background-color: #ffff;
        color: #2e64fa;
      }
      .step_desc {
        background-color: rgba(46, 100, 250, 0.1);
      }
    }
  }

  .active_score
  {
      
      .step_title {
        color:#2E64FA;
      }
      .step_num {
        background-color: #B0B2B7;
        color: #2e64fa;
      }

  }

  /* 小屏幕笔记本的样式 常见分辨率：1366x768 */
  @media (max-height: 768px) {
    .step_item {
      margin-bottom: 0px;
      .step_title {
        font-size: 14px;
        line-height: 30px;
        font-weight: 700;
      }
      .step_desc {
        padding: 0px 5px 6px 20px;
        font-size: 10px;
        line-height: 15px;
      }
    }
  }
  /* 中等屏幕笔记本的样式(14-15英寸) 常见分辨率：1600x900, 1920x1080*/
  @media (min-height: 769px) and (max-height: 1080px) {
    .step_item {
      margin-bottom: 15px;
      .step_title {
        font-size: 16px;
        line-height: 30px;
      }
      .step_desc {
        padding: 0px 5px 6px 20px;
        font-size: 12px;
        line-height: 15px;
      }
    }
  }
  /* 大屏幕笔记本的样式(17-20英寸) 常见分辨率：2560x1440*/
  @media screen and (min-height: 1081px) {
    .step_item {
      margin-bottom: 25px;
      .step_title {
        font-size: 17px;
        line-height: 30px;
      }
      .step_desc {
        padding: 10px 5px 10px 20px;
        font-size: 14px;
        line-height: 15px;
      }
    }
  }
}
</style>