<script setup lang="ts">
import router from "@/router";
import {Back} from "@element-plus/icons-vue";
import {computed, onMounted, provide, type Ref, ref, watch} from "vue";
import {ElLoading, ElMessage} from "element-plus";
import useApis from "@/apis";
import {useRoute} from "vue-router";

const apis = useApis()
const route = useRoute()

//pageHeader
interface CourseVO{
  courseName: string;
  courseId: number;
}
interface AssignmentVO{
  assignmentName: string;
  assignmentId: number;
}
const dialogVisible = ref(false)
const maxPauseTime = ref(2000)
provide('maxPauseTime',maxPauseTime)

const loadingStatus = ref({
  edit:false,
  pause:false,
  process:false,
  total:false
})
provide('loadingStatus',loadingStatus)

const selectedCourse  = ref({courseName: "", courseId: -1});
const selectedClass  = ref({courseName: "", classId: -1});
const courseList:Ref<CourseVO[]> = ref([]);
let courseData:any[]= []
const selectedAssignment  = ref({assignmentName: "", assignmentId: -1});
watch(selectedAssignment,()=>{
  AssignmentChanged(selectedAssignment.value);
})
const assignmentList:Ref<AssignmentVO[]> = ref([]);
const dataIsLoading:Ref<boolean> = ref(true);
let assignmentData:any[]= []

const emptyText = computed(()=>{
  if (selectedCourse.value.courseId === -1){
    return "暂无课程"
  }
  else{
    return "当前作业暂无学生提交"
  }
})
function getCourseList(){
  console.log("获取课程列表")
  let pageHTML = document.getElementById("info-card")
  console.log(pageHTML)
  const loading = ElLoading.service({
    text: '获取数据中',
    target: pageHTML,
    background: '#F5F5F59E'
  })
  
  // 从路由参数中获取课程ID和作业ID
  const courseIdFromRoute = route.query.courseId ? Number(route.query.courseId) : null
  const assignmentIdFromRoute = route.query.assignmentId ? Number(route.query.assignmentId) : null
  
  apis.getCourseByTeacherId(0,100)
      .then((res: any)=>{
        if (res&&res.data.code===200){
          courseData = res.data.data.records as [any];
          // console.log(courseData)
          courseList.value = courseData.map((item:any)=>{
            return {courseName: item.courseName, courseId: item.courseId}
          })
          if (courseList.value&&courseList.value.length>0){
            // 如果路由中有课程ID参数，尝试选中该课程
            if (courseIdFromRoute) {
              const targetCourse = courseList.value.find(c => c.courseId === courseIdFromRoute)
              if (targetCourse) {
                selectedCourse.value = targetCourse
                console.log("从路由参数选中课程:", targetCourse.courseName)
              } else {
                selectedCourse.value = courseList.value[0]
              }
            } else {
              selectedCourse.value = courseList.value[0]
            }
          }
          else {
            selectedCourse.value = {courseName: "", courseId: -1}
            loading.close();
            return;
          }
          
          // 获取选中课程的作业列表
          const targetCourseId = selectedCourse.value.courseId
          apis.getAssignmentByCourseId(targetCourseId,0,1000)
            .then((res: any)=>{
              if (res&&res.data.code===200){
                loading.close();
                dataIsLoading.value = false;
                let temp = res.data.data.records.filter((item:any)=>{
                  return item.type === 'writing' || item.type === '写作';
                })
                console.log("temp:",temp)
                assignmentList.value = temp.map((item:any)=>{
                    return {assignmentName: item.assignmentName, assignmentId: item.assignmentId}
                })
                console.log(assignmentList.value);
                // assignmentData = temp as any[];
                if (assignmentList.value&&assignmentList.value.length>0){
                  // 如果路由中有作业ID参数，尝试选中该作业
                  if (assignmentIdFromRoute) {
                    const targetAssignment = assignmentList.value.find(a => a.assignmentId === assignmentIdFromRoute)
                    if (targetAssignment) {
                      selectedAssignment.value = targetAssignment
                      console.log("从路由参数选中作业:", targetAssignment.assignmentName)
                    } else {
                      selectedAssignment.value = assignmentList.value[0]
                    }
                  } else {
                    selectedAssignment.value = assignmentList.value[0]
                  }
                }
                else{
                  selectedAssignment.value = {assignmentName: "", assignmentId: -1}
                }
              }
              else{
                ElMessage.error("获取作业列表失败")
              }
            })
            .catch((err: any) => {
              console.log(err);
              ElMessage.error("获取作业列表失败")
            })
        }
        else{
          ElMessage.error("获取课程列表失败")
        }
        console.log(res);
      })
      .catch((err: any) => {
        console.error(err);
      })
}

function getAssignmentList(courseId:number){
  let pageHTML = document.getElementById("info-card")
  // console.log(pageHTML)
  const loading = ElLoading.service({
    text: '获取作业列表中',
    target: pageHTML,
    background: '#F5F5F59E'
  })
  
  // 从路由参数中获取作业ID（仅在用户手动切换课程时不使用）
  const assignmentIdFromRoute = route.query.assignmentId ? Number(route.query.assignmentId) : null
  
  apis.getAssignmentByCourseId(courseId,0,1000)
      .then((res: any)=>{
        if (res&&res.data.code===200){
          let temp = res.data.data.records.filter((item:any)=>{
            return item.type === 'writing' || item.type === '写作';
          })
          assignmentList.value = temp.map((item:any)=>{
            return {assignmentName: item.assignmentName, assignmentId: item.assignmentId}
          })
          // assignmentData = temp as any[];
          if (assignmentList.value&&assignmentList.value.length>0){
            // 如果路由中有作业ID参数且该作业在列表中，选中该作业
            if (assignmentIdFromRoute) {
              const targetAssignment = assignmentList.value.find(a => a.assignmentId === assignmentIdFromRoute)
              if (targetAssignment) {
                selectedAssignment.value = targetAssignment
                console.log("选中路由参数中的作业:", targetAssignment.assignmentName)
              } else {
                selectedAssignment.value = assignmentList.value[0]
              }
            } else {
              selectedAssignment.value = assignmentList.value[0]
            }
          }
          else{
            selectedAssignment.value = {assignmentName: "", assignmentId: -1}
          }
          loading.close();
        }
      })
}


const courseSelected = computed(()=>{
  return selectedCourse.value&&selectedCourse.value.courseName !== "";
});
function goBack() {
  router.go(-1);
}

/**
 * 课程切换
 * @param value 课程名
 */
function courseChanged(value:CourseVO){
  console.log("用户切换了课程")
  //TODO
  getAssignmentList(value.courseId);
}


const engagements = ref([]);
const currentEngagementIndex = ref(-1);
const preButtonDisabled = computed(()=>{
  return currentEngagementIndex.value<=0
      || loadingStatus.value.pause
      || loadingStatus.value.process
      || loadingStatus.value.total
      || loadingStatus.value.edit
});
const nextButtonDisabled = computed(()=>{
  return currentEngagementIndex.value>=engagements.value.length-1
      || loadingStatus.value.pause
      || loadingStatus.value.process
      || loadingStatus.value.total
      || loadingStatus.value.edit
})
const isLoading = computed(()=>{
  return loadingStatus.value.pause
      || loadingStatus.value.process
      || loadingStatus.value.total
      || loadingStatus.value.edit
})
const currentEngagement = ref()
watch(currentEngagementIndex,()=>{
  if (currentEngagementIndex.value>=0&&currentEngagementIndex.value<engagements.value.length){
    currentEngagement.value =  engagements.value[currentEngagementIndex.value];
    console.log(currentEngagement.value)
  }
  else{
    currentEngagement.value = null;
  }
})
provide('currentEngagement',currentEngagement);


/**
 * 切换作业题目
 * @param value 作业题目
 * @constructor
 */
function AssignmentChanged(value:AssignmentVO){
  console.log("用户切换了作业")
  if (value.assignmentId === -1){
    currentEngagementIndex.value = -1;
    return;
  }
  
  // 从路由参数中获取学生ID
  const studentIdFromRoute = route.query.studentId ? Number(route.query.studentId) : null
  
  apis.getEngagementByAssignmentId(value.assignmentId,0,10000)
      .then((res:any) => {
        console.log(res);
        if (res.data.code === 200){
          engagements.value = res.data.data.records;
          if (engagements.value&&engagements.value.length>0){
            // 如果路由中有学生ID参数，尝试定位到该学生
            if (studentIdFromRoute) {
              const targetIndex = engagements.value.findIndex((engagement:any) => 
                engagement.studentId === studentIdFromRoute
              )
              if (targetIndex !== -1) {
                currentEngagementIndex.value = targetIndex
                console.log("从路由参数定位到学生，索引:", targetIndex)
              } else {
                currentEngagementIndex.value = 0
                console.log("未找到指定学生，默认选择第一个")
              }
            } else {
              if (currentEngagementIndex.value == 0){
                currentEngagement.value =  engagements.value[0];
              }
              currentEngagementIndex.value = 0;
            }
          }
          else{
            currentEngagementIndex.value = -1;
          }
        }
      })
      .catch((err:any) => {
        console.log("错误信息", err)
      })
}

/**
 * 切换提交
 * @param direction 1:下一个提交 -1:上一个提交 else:切换错误
 */
function assignmentSwitch(direction:number){
  if (direction===1){
    console.log("切换下一个作业")
    currentEngagementIndex.value++;
  }
  else if (direction===-1){
    console.log("切换上一个作业")
    currentEngagementIndex.value--;
  }
  else{
    ElMessage.error("切换错误")
  }
}
const selectedType = ref('single');
/**
 * 下载行为数据
 */
function downLoadBehaviorData(){
  dialogVisible.value = false
  // ElMessage.success(selectedType.value)
  if (selectedType.value === 'single'){
    apis.downLoadBehaviorData(currentEngagement.value.studentId,currentEngagement.value.assignmentId)
        .then((res:any) => {
          console.log(res)
          if (res && res.status === 200){
            let blob = res.data as Blob;
            const fileName = '行为数据.xlsx';
            if ('download' in document.createElement('a')) {
              const link = document.createElement('a');
              link.download = fileName;
              link.style.display = 'none';
              link.href = URL.createObjectURL(blob);
              document.body.appendChild(link);
              link.click();
              ElMessage.success('下载成功')
              URL.revokeObjectURL(link.href); // 释放URL对象
              document.body.removeChild(link);
            }
          }
        })
        .catch((err:any) => {
          console.log(err)
          ElMessage.success('下载失败')
        })
  }
  else if (selectedType.value === 'all'){
    apis.downLoadAllBehaviorData(selectedAssignment.value.assignmentId)
        .then((res:any) => {
          if (res && res.status === 200){
            let blob = res.data as Blob;
            const fileName = '行为数据.xlsx';
            if ('download' in document.createElement('a')) {
              const link = document.createElement('a');
              link.download = fileName;
              link.style.display = 'none';
              link.href = URL.createObjectURL(blob);
              document.body.appendChild(link);
              link.click();
              ElMessage.success('下载成功')
              URL.revokeObjectURL(link.href); // 释放URL对象
              document.body.removeChild(link);
            }
          }
        })
        .catch((err:any) => {
          console.log(err)
          ElMessage.success('下载失败')
        })
  }
  // else if (selectedType.value === 'class'){
  //     apis.downLoadAllBehaviorDataByClass(selectedClass.value.classId,selectedAssignment.value.assignmentId)
  //       .then((res:any) => {
  //         if (res && res.status === 200){
  //           let blob = res.data as Blob;
  //           const fileName = '行为数据.xlsx';
  //           if ('download' in document.createElement('a')) {
  //             const link = document.createElement('a');
  //             link.download = fileName;
  //             link.style.display = 'none';
  //             link.href = URL.createObjectURL(blob);
  //             document.body.appendChild(link);
  //             link.click();
  //             ElMessage.success('下载成功')
  //             URL.revokeObjectURL(link.href); // 释放URL对象
  //             document.body.removeChild(link);
  //           }
  //         }
  //       })
  //       .catch((err:any) => {
  //         console.log(err)
  //         ElMessage.success('下载失败')
  //       })
  // }
  else{
    ElMessage.error("请选择下载类型")
  }
  // apis.downLoadBehaviorData(selectedAssignment.value.assignmentId,selectedCourse.value.courseId)
}
const handleClose = (done: () => void) => {
  done()
}
onMounted(()=>{
  getCourseList();
})
</script>

<template>
  <div id="page" class="page">
    <el-card class="info-card" id="info-card">
      <template #header>
        <el-page-header @back="goBack">
          <template #icon>
            <el-icon color="#909399"><back/></el-icon>
          </template>
          <template #title>
            <span style="font-size: 18px;color: var(--el-text-color-secondary)" > 返回 </span>
          </template>
          <template #content>
            <span > 行为数据记录 </span>
          </template>
          <template #extra>
            <el-select v-model="selectedCourse"
                       placeholder="请选择课程"
                       value-key="courseId"
                       :title="courseSelected?selectedCourse.courseName:'暂无课程'"
                       @change="courseChanged"
                       style="width: 130px;">
              <el-option
                  style="color: var(--el-text-color-regular);font-weight: unset"
                  v-for="item in courseList"
                  :key="item.courseId"
                  :label="item.courseName"
                  :value="item"
              />
            </el-select>
            <el-select v-model="selectedAssignment"
                       :disabled="!courseSelected"
                       value-key="assignmentId"
                       :class="{'disabled':!courseSelected}"
                       placeholder="请选择作业"
                       :title="courseSelected?selectedAssignment.assignmentName:'请先选择课程'"
                       style="width: 130px;margin-left: 10px">
              <el-option
                  style="color: var(--el-text-color-regular);font-weight: unset"
                  v-for="item in assignmentList"
                  :key="item.assignmentId"
                  :label="item.assignmentName"
                  :value="item"
              />
            </el-select>
          </template>
        </el-page-header>
      </template>
      <el-descriptions :column="2" v-if="currentEngagement" style="width: 90%;margin-left: 5%">
        <el-descriptions-item label="课程名">{{selectedCourse.courseName}}</el-descriptions-item>
        <el-descriptions-item label="作业题目">{{selectedAssignment.assignmentName}}</el-descriptions-item>
        <el-descriptions-item label="学生姓名">{{currentEngagement.studentName}}</el-descriptions-item>
        <el-descriptions-item label="学号">
          {{currentEngagement.studentId}}
        </el-descriptions-item>
<!--        <el-descriptions-item label="提交时间">-->
<!--          2025-07-30 09:30:00-->
<!--        </el-descriptions-item>-->
      </el-descriptions>
      <div v-if="currentEngagement" id="info-footer">
        <el-button
          :disabled="isLoading"
          @click="dialogVisible = true" type="success">
          导出行为数据
        </el-button>
        <el-button
            :disabled="preButtonDisabled"
            @click="assignmentSwitch(-1)" type="primary">
          上一个
        </el-button>
        <el-button
            :disabled="nextButtonDisabled"
            @click="assignmentSwitch(1)" type="primary">
          下一个
        </el-button>
      </div>
      <el-empty v-else :description="emptyText" style="height: 227px" />
    </el-card>
    <router-view :class="{hidden:!(!dataIsLoading&&currentEngagement)}" >

    </router-view>
    <el-dialog
        v-model="dialogVisible"
        title="请选择导出的数据类型"
        width="500"
        :before-close="handleClose"
    >
      <el-radio-group v-model="selectedType">
        <el-radio value="single">当前学生行为数据</el-radio>
        <el-radio value="all">所有学生行为数据</el-radio>
        <!-- <el-radio value="class">班级行为数据</el-radio> -->
      </el-radio-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" type="danger">取消</el-button>
          <el-button type="primary"
                     @click="downLoadBehaviorData">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.hidden{
  visibility: hidden;
}
.page{
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 30px;
  margin-bottom: 100px;
}
.info-card{
  width: 70%;
  margin-top: 2%;
  border-radius: 16px;
  min-width: 700px;
}
.disabled{
  cursor: not-allowed;
}
#info-footer{
  display: flex;
  width: 100%;
  flex-direction: row;
  justify-content: end;
  gap: 10px;
  margin-top: 50px;
}
</style>
