<template>
    <div class="page_container">
      <div class="container_content">
        <div class="select_school" v-if="schoolType==1">
          选择学校:
          <el-select  v-model="selectSchoolId" @change="ChangeSchool"  placeholder="选择学校" class="select_width" >
            <el-option label="联校" value="" ></el-option>
            <el-option
                v-for="item in schoolList"
                :key="item.schoolCode"
                :label="item.schoolNickName || item.schoolName"
                :value="item.schoolId">
            </el-option>
        </el-select>
        </div>
        <div class="container_item">
          <div class="item_title">方案1</div>
          <div class="item_card" >
            <div class="card_title">
              系统名单
            </div>
            <div class="card_center">
              <img src="@/assets/bg/first_select.png">
              <span class="span_name">系统名单</span>
              
            </div>
            <div class="card_desc">从系统名单制作导入</div>
            <div class="card_button">
              <el-button class="buttom" type="primary" :disabled="schoolType==0 && examSchoolType==1" @click="OpenSystemDialog">立即使用</el-button>
            </div>
          </div>
        </div>
        <div class="container_item">
          <div class="item_title">方案2</div>
          <div class="item_card" >
            <div class="card_title">
              EXCEL导入
            </div>
            <div class="card_center">
              <img src="@/assets/bg/second_select.png">
              <span class="span_name">导入表格</span>
            </div>
            <div class="card_desc">以标准EXCEL模板导入        </div>
            <div class="card_button">
              <el-button @click="DownloadModule" class="bottom">下载模板</el-button>
              <!-- <el-button  @click="OpenUpload" class="buttom" type="primary" :loading="uploadLoading" :disabled="schoolType==0 && examSchoolType==1">{{uploadText}}</el-button> -->
              <el-button class="buttom" type="primary"  :disabled="true">{{uploadText}}</el-button>
              <input ref="uploadRef" accept=".xls, .xlsx" @change="UploadFile" class="buttom" type="file" style="display: none;"></input>
            </div>
          </div>
        </div>
        <!-- 联校账号 查看联考的时候选择单校的时候 不显示历史名单 其他都显示 -->
        <div class="container_item" >
          <div class="item_title" v-if="!(schoolType == 1 && examSchoolType == 1 && selectSchoolId)">方案3</div>
          <div class="item_card" v-if="!(schoolType == 1 && examSchoolType == 1 && selectSchoolId)">
            <div class="card_title">
              历史考试
            </div>
            <div class="card_center">
              <img src="@/assets/bg/thrid_select.png">
              <span class="span_name">复用名单</span>
            </div>
            <div class="card_desc">从历史考试调用考场名单</div>
            <div class="card_button">
              <!-- <el-button class="buttom" type="primary" @click="OpenHistoryDialog" :disabled="schoolType==0 && examSchoolType==1">立即复用</el-button> -->
               <el-button class="buttom" type="primary"  :disabled="true">立即复用</el-button>
            </div>
          </div>
        </div>
      </div>
      <SelectStudent v-model="showSelectStudent"  @success="StudentSuccess"></SelectStudent>
      <!-- <SelectHistoryList ref="selectHistoryListRef" @GoToScanExamHome="GoToScanExamHome" typeValue="1" :schoolId="selectSchoolId" v-if="showHistoryList" @historyCancel="CancelHistoryDialog"></SelectHistoryList>
      <DialogSystemQuery ref="selectSystemListRef" @GoToScanExamHome="GoToScanExamHome" :schoolId="selectSchoolId" v-if="showSystemList" @sysCancel="CancelSystemDialog"></DialogSystemQuery> -->
    </div>
  </template>
  
<script lang="ts" setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import SelectStudent from './components/selectStudent.vue'
// import SelectHistoryList from './ReviewBlock/SelectHistoryList.vue'
import { useExamStore } from '@/store/exam'

const route = useRoute()
const router = useRouter()
const examStore = useExamStore()

// 响应式数据
const showSystemList = ref(true)
const showHistoryList = ref(true)
const selectSchoolId = ref<string | number>('')
const schoolList = ref<any[]>([])
const uploadLoading = ref(false)
const uploadText = ref('立即上传')
const uploadRef = ref<HTMLInputElement | null>(null)
const showSelectStudent = ref(false);
const selectSystemListRef = ref<any>(null)

// 计算属性
const examSubjectId = computed(() => {
  return examStore.examTempDetail?.id
})

const examId = computed(() => {
  return examStore.examDetail?.id
})

const schoolType = computed(() => {
  return examStore.userSchoolType
})

const examSchoolType = computed(() => {
  return examStore.examDetail?.schoolType
})

// 获取考试的学校列表
const GetExamSchoolList = () => {
  const param = {
    examId: examId.value,
  }
//   // 假设 API 在 examStore 或全局 API 中
//   examStore.getJoinExamSchoolList(param).then((res: any) => {
//     console.log("打印当前考试的学校列表", res)
//     if (res.code === 200) {
//       schoolList.value = res.data || []
//     }
//   })
}

// 切换学校
const ChangeSchool = () => {
  // 预留逻辑
}

// 下载模板
const DownloadModule = () => {
//   examStore.downloadModule().then((res: any) => {
//     if (res.data) {
//       const blobFile = res.data
//       const url = window.URL.createObjectURL(new Blob([blobFile]))
//       const link = document.createElement('a')
//       link.href = url
//       link.setAttribute('download', '导入模板.xls')
//       document.body.appendChild(link)
//       link.click()
//       window.URL.revokeObjectURL(url)
//       ElMessage({
//         type: 'success',
//         message: '模板下载成功'
//       })
//     }
//   })
}

// 上传文件
const UploadFile = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!target.files || target.files.length === 0) return
  
  const formdata = new FormData()
  formdata.append('examSubjectId', examSubjectId.value as string)
  formdata.append('reuse', (route.query.reuse as string) || '0')
  formdata.append('file', target.files[0])
  
  if (selectSchoolId.value) {
    formdata.append('schoolId', String(selectSchoolId.value))
  }
  
  uploadLoading.value = true
  uploadText.value = '上传中'
  
  examStore.uploadStudentList(formdata).then((res: any) => {
    if (res.code === 200) {
      uploadLoading.value = false
      uploadText.value = '立即上传'
      if (uploadRef.value) {
        uploadRef.value.value = ''
      }
      router.push({ path: '/joinExamDetail/scanStudentHome' })
    } else {
      uploadLoading.value = false
      uploadText.value = '立即上传'
      if (uploadRef.value) {
        uploadRef.value.value = ''
      }
      ElMessageBox.confirm(`导入失败! ${res.msg}`, '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        closeOnClickModal: false,
        customClass: "page_dialog",
        type: 'error'
      }).catch(() => {})
    }
  })
}

// 打开上传文件弹窗
const OpenUpload = () => {
  if (uploadRef.value) {
    uploadRef.value.click()
  }
}

// 学生名单使用成
const StudentSuccess=(data: any)=>
{
    console.log("学生名单使用成功",data)
    router.push({
      path: '/exam/scanList',
    })

}

// 去到扫描首页
const GoToScanExamHome = (data: any) => {
  console.log("关闭弹窗", data)
  if (route.query.reuse === '1') {
    router.push({
      path: '/joinExamDetail/scanStudentHome',
      query: {
        id: route.query.id as string,
      }
    })
  } else {
    console.log("返回事件GoToScanExamHome", data)
    console.log("打印当前路由", route.path)
    if (route.path === '/joinExamDetail/selectStudentList') {
      router.push({
        path: '/joinExamDetail/scanStudentHome',
        query: {
          id: route.query.id as string,
          schoolId: selectSchoolId.value ? String(selectSchoolId.value) : undefined,
        }
      })
    }
  }
}

// 取消打开系统名单弹窗
const CancelSystemDialog = () => {
  showSystemList.value = false
  nextTick(() => {
    showSystemList.value = true
  })
}

// 打开系统名单
const OpenSystemDialog = () => {
  showSelectStudent.value = true
  console.log("打印当前选择的学校id", selectSchoolId.value)
  if (schoolType.value === 0) {
    selectSchoolId.value = 0
  }

}

// 打开历史考试名单弹窗
const OpenHistoryDialog = () => {
  showHistoryList.value = true
  nextTick(() => {
    if (selectHistoryListRef.value) {
      selectHistoryListRef.value.OpenDialog()
    }
  })
}

// 关闭历史考生弹窗
const CancelHistoryDialog = () => {
  showHistoryList.value = false
  nextTick(() => {
    showHistoryList.value = true
  })
}

onMounted(() => {
  console.log("打印schoolType", schoolType.value)
  console.log("打印examSchoolType", examSchoolType.value)
  console.log("打印当前selectSchoolId", selectSchoolId.value)
  
  if (route.query.schoolId) {
    if (route.query.schoolId === '-1') {
      selectSchoolId.value = ""
    } else {
      selectSchoolId.value = route.query.schoolId as string
    }
  }
  
  GetExamSchoolList()
})
</script>

<style lang="scss" scoped>
// 原有样式保持不变
</style>