<template>
    <div class="main">
        <div class="search">
            <img src="@/assets/search.svg" width="20px" height="20px"></img> 
            <div class="searchInput">
                <input type="text" v-model.trim="searchInput" placeholder="输入姓名或学号" :disabled="!isTable">
                <div class="fix">
                    <span>搜索</span>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#b8b8b8" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>
                </div>
            </div>
            <div class="Myselect">
                <select id="selectHomework" v-model="TheHomework" @change="changeHomework" :disabled="!isTable"> 
                    <option value=-1>选择作业</option>
                    <option v-for="item in Homeworksdata" :value="item.assignmentId">{{item.assignmentName}}</option>
                </select>
                <div class="show">
                        {{ ShowTheHomework }}
                </div>
            </div>
            <div class="Myselect">
                <select id="selectSort" v-model="TheSort" :disabled="!isTable"> 
                    <option value="无">排序方式</option>
                    <option v-for="item in sortMethods" :value="item">{{item}}</option>
                </select>
                <div class="show">
                        {{ ShowTheSort }}
                </div>
            </div>
            <classToggle v-model:isLeft="isTable">
                <template #left>
                    table
                </template>
                <template #right>
                    chart
                </template>
            </classToggle>
            <div class="exportButton">
                    <button @click="exportData">导出数据</button>
            </div>
        </div>
        <div class="content">
            <div class="Loading" v-show="!DataLoading">Loading...</div>
            <div class="half-table" v-show="DataLoading">
                <classTable v-if="isTable">
                <template #head>
                    <tr>
                        <th>序号</th>
                        <th>学生姓名</th>
                        <th>学号</th>
                        <th>成绩</th>
                    </tr>
                </template>
                <template #body>
                    <tr v-for="(item,index) in showData.slice(0,5)" :key="index+item.officialNumber">
                        <template v-if="item.officialNumber!==0">
                            <td>{{ (currentPage-1)*10+index+1 }}</td>
                            <td
                                @click="$router.push(`/home/studentDetail?classId=${classId}&courseId=${courseId}&stuId=${item.studentId}`)"
                                @mouseenter="hoverStuId=item.studentId"
                                @mouseleave="hoverStuId=-1"
                                :class="{Gethover:hoverStuId===item.studentId,Blue:true}"
                                >{{ item.stuName }}</td>
                            <td>{{ item.officialNumber }}</td>
                            <td  @click="$router.push(`/home/assignment/${ShowTheHomeworkId}/correct?studentId=${item.studentId}`)">
                                <div class="highScore" v-if="item.score>=80"> {{ item.score }}</div>
                                <div class="midScore" v-else-if="item.score>=60"> {{ item.score }}</div>
                                <div class="lowScore" v-else-if="item.score>0"> {{ item.score }}</div>
                                <div class="uncorrected" v-else-if="item.status==='SUBMITTED'"> 未批改</div>
                                <div class="unsubmitted" v-else-if="item.status==='NOT_SUBMITTED'"> 未提交</div>             
                            </td>
                        </template>
                        <template v-else>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </template>
                    </tr>
                </template>
                </classTable>
                <div ref="chartRef1" class="chart" v-else></div>
            </div>
            <div class="half-table" v-show="DataLoading">
                <classTable v-if="isTable">
                <template #head>
                    <tr>
                        <th>序号</th>
                        <th>学生姓名</th>
                        <th>学号</th>
                        <th>成绩</th>
                    </tr>
                </template>
                <template #body>
                    <tr v-for="(item,index) in showData.slice(5,10)" :key="index+item.officialNumber">
                        <template v-if="item.officialNumber!==0">
                            <td>{{ (currentPage-1)*10+index+6 }}</td>
                            <td
                                @click="$router.push(`/home/studentDetail?classId=${classId}&courseId=${courseId}&stuId=${item.studentId}`)"
                                @mouseenter="hoverStuId=item.studentId"
                                @mouseleave="hoverStuId=-1"
                                :class="{Gethover:hoverStuId===item.studentId,Blue:true}"
                                >{{ item.stuName }}</td>
                            <td>{{ item.officialNumber }}</td>
                            <td @click="$router.push(`/home/assignment/${ShowTheHomeworkId}/correct?studentId=${item.studentId}`)">
                                <div class="highScore" v-if="item.score>=80"> {{ item.score }}</div>
                                <div class="midScore" v-else-if="item.score>=60"> {{ item.score }}</div>
                                <div class="lowScore" v-else-if="item.score>0"> {{ item.score }}</div>
                                <div class="uncorrected" v-else-if="item.status==='SUBMITTED'"> 未批改</div>
                                <div class="unsubmitted" v-else-if="item.status==='NOT_SUBMITTED'"> 未提交</div>                
                            </td>
                        </template>
                        <template v-else>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </template>
                    </tr>
                </template>
                </classTable>
                <div ref="chartRef2" class="chart chart2" v-else></div>
            </div>
        </div>
        <div class="pages" v-show="DataLoading && isTable">
            <el-pagination
                v-model:current-page="currentPage"
                :page-size="10"
                :pager-count="5"
                layout="total, prev, pager, next"
                :total="searchData.length"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
import classTable from './components/classTable.vue';
import classToggle from './components/classToggle.vue'
import {onMounted, ref, computed, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from "@/store"
import {ElLoading, ElMessage} from "element-plus";
import * as echarts from 'echarts'
import useApis from "@/apis";
import { log } from 'console';

const apis = useApis()
const store = useStore()
const route = useRoute()
const router = useRouter()
const classId = +route.query.classId;
const courseId = +route.query.courseId;

const currentPage = ref(1)
const searchInput = ref("")
const TheHomework = ref(-1)
const ShowTheHomework = ref("")
const ShowTheHomeworkId = ref(-1)
const TheSort = ref("无")
const ShowTheSort = ref("默认")
const hoverStuId = ref(-1)

const StudentsDataLoading = ref(false)
const HomeworkDataLoading = ref(false)
const isTable = ref(true)

const Studentsdata = ref([])
const Homeworksdata = ref([])


const sortMethods = ["默认","成绩从低到高","成绩从高到低","未批改优先","未提交优先"]

const chartRef1 = ref(null)
const chartRef2 = ref(null)
const setChart = () => {

    const chartInstance = echarts.init(chartRef1.value)
    const chartInstance2 = echarts.init(chartRef2.value)
    let excellentnum=0, goodnum=0 , failnum=0 , uncorrectednum=0 , unsubmittednum=0
    Studentsdata.value.forEach((item)=>{
        if(item.status === "NOT_SUBMITTED"){
            unsubmittednum++
        }
        else if(item.status === "SUBMITTED"){
            uncorrectednum++
        }
        else if(item.score<60){
            failnum++
        }
        else if(item.score<80){
            goodnum++
        }
        else{
            excellentnum++
        }
    })
    
    const option = {
        title: {
        text: ShowTheHomework.value+'详情',
        // subtext: '纯属虚构',
        left: 'center'
        },
        tooltip: {
        trigger: 'item',
        formatter: '{b}: {d}%'
        },
        legend: {
        orient: 'vertical',
        left: 'left'
        },
        series: [
        {
            name: '作业组成',
            type: 'pie',
            radius: '50%',
            data: [
                { value: excellentnum, name: '优秀', itemStyle: { color: '#7ADBB0' } },
                { value: goodnum, name: '良好', itemStyle: { color: '#F0C05A' } },
                { value: failnum, name: '不及格', itemStyle: { color: '#F4A261' } },
                { value: unsubmittednum, name: '未提交', itemStyle: { color: '#C45C4A' } },
                { value: uncorrectednum, name: '未批改', itemStyle: { color: '#D9D9D9' } }
            ],
            emphasis: {
            itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
            }
        }
        ]
    }
    const option2 = {
        title: {
        text: ShowTheHomework.value+'详情',
        // subtext: '纯属虚构',
        left: 'center'
        },
        tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow' // 悬停时显示阴影效果
        },
        formatter: '{b}: {c}'
        },
        xAxis: {
            type: 'category',
            data: ['优秀', '良好', '不及格', '未提交', '未批改']
        },
        yAxis: {
            type: 'value',
            name: '人数'
        },
        series: [
        {
            name: '作业组成',
            type: 'bar',
            radius: '50%',
            data: [
                { value: excellentnum, name: '优秀', itemStyle: { color: '#7ADBB0' } },
                { value: goodnum, name: '良好', itemStyle: { color: '#F0C05A' } },
                { value: failnum, name: '不及格', itemStyle: { color: '#F4A261' } },
                { value: unsubmittednum, name: '未提交', itemStyle: { color: '#C45C4A' } },
                { value: uncorrectednum, name: '未批改', itemStyle: { color: '#D9D9D9' } }
            ],
            barWidth: '40%',
            emphasis: {
            itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
            }
        }
        ]
    }

    chartInstance.setOption(option)
    chartInstance2.setOption(option2)
}

const exportData = () => {
    console.log('exportData',classId,ShowTheHomeworkId.value)
    // apis.downLoadAllBehaviorDataByClass(classId,ShowTheHomeworkId.value)
    // apis.downLoadAllBehaviorData(ShowTheHomeworkId.value)
    apis.downLoadAllBehaviorDataByClass(classId,ShowTheHomeworkId.value)
    .then((res:any) => {
        if (res && res.status === 200){
        let blob = res.data as Blob;
        const fileName = `${ShowTheHomework.value}作业行为数据.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('下载失败')
    })
}

const identify = () => {
    if(store.user.role === "STUDENT"){
        router.push('/404')
    }
}
const getHomeworks = async () => {
    // console.log(courseId,classId);
    console.log(ShowTheHomeworkId.value);
    await apis.getAssignmentByCourseId(courseId)
        .then((res:any)=>{
            // console.log('----------------------');
            // console.log(res.data.data.records);
            res.data.data.records.forEach(item => Homeworksdata.value.push(item))
            if(res.data.data.records.length!=0){
            ShowTheHomework.value = res.data.data.records[0].assignmentName
            ShowTheHomeworkId.value = res.data.data.records[0].assignmentId
            }
        })
    // t.forEach(item => Homeworksdata.value.push(item))
    HomeworkDataLoading.value = true
    console.log('ShowTheHomeworkId',ShowTheHomeworkId.value);
}
const getStudents = () => {
    StudentsDataLoading.value=false
    console.log('+++++++++++++++++++++++');
    console.log(classId,ShowTheHomeworkId.value);
    apis.getClassStatesOfCourse(classId,ShowTheHomeworkId.value)
        .then((res:any)=>{
            console.log(res.data.data);
            Studentsdata.value = res.data.data
        })
        .catch((err:any)=>{
            console.log('-------------------------');
            console.log(err);
        })
        StudentsDataLoading.value = true
}
const changeHomework = () => {
    console.log(ShowTheHomework.value)
    getStudents()
}

const searchData = computed(()=>{
    if(searchInput.value===""){
        return Studentsdata.value
    }
    else{
        return Studentsdata.value.filter(student => {
          return (
            student.stuName.includes(searchInput.value) ||
            student.officialNumber.toString().includes(searchInput.value)
          )
        })
    }
})


const showData = computed(() => {
    const showdata = searchData.value.slice((currentPage.value-1)*10,currentPage.value*10)
    while(showdata.length<10){
        showdata.push(    {
        "officialNumber": 0,
        "stuName": "",
        "status": "",
        "score": 0,
        "studentId": -1
        })
    }
    return showdata
})

const DataLoading = computed(() => {
   return StudentsDataLoading.value && HomeworkDataLoading.value
})

watch(TheHomework, () => {
    nextTick(() => {
        // console.log(ShowTheHomework.value,TheHomework.value);
        if(TheHomework.value != -1){
            let t = Homeworksdata.value.find(item=>item.assignmentId==TheHomework.value)
            ShowTheHomework.value = t.assignmentName
            ShowTheHomeworkId.value = t.assignmentId
            TheHomework.value = -1
        }
        // console.log(ShowTheHomework.value,TheHomework.value);
    });
});
watch(TheSort, () => {
    nextTick(() => {
        // console.log(ShowTheSort.value,TheSort.value);
        if(TheSort.value != "无"){
            ShowTheSort.value = TheSort.value
            TheSort.value = "无"
        }
        // console.log(ShowTheSort.value,TheSort.value);
    });
});
watch(ShowTheSort,(newData) =>{
    if(newData==="未提交优先"){
        Studentsdata.value = Studentsdata.value.sort((a,b)=>{
            return a.status === "NOT_SUBMITTED" ? -1 : b.status === "NOT_SUBMITTED" ? 1 : 0;
        })
        console.log("未批改已排序");
        console.log(Studentsdata.value);
        
    }
    else if(newData==="未批改优先"){
        Studentsdata.value = Studentsdata.value.sort((a,b)=>{
            return a.status === "SUBMITTED" ? -1 : b.status === "SUBMITTED" ? 1 : 0;
        })
    }
    else if(newData==="成绩从低到高"){
        Studentsdata.value = Studentsdata.value.sort((a,b)=>{
            if (a.status === "CORRECTED" && b.status !== "CORRECTED") return -1;
            if (a.status !== "CORRECTED" && b.status === "CORRECTED") return 1;
            return a.score - b.score;
        })
    }
    else if(newData==="成绩从高到低"){
        Studentsdata.value = Studentsdata.value.sort((a,b)=>{
            if (a.status === "CORRECTED" && b.status !== "CORRECTED") return -1;
            if (a.status !== "CORRECTED" && b.status === "CORRECTED") return 1;
            return b.score - a.score;
        })
    }
})
watch(isTable, (newVal) => {
    if(newVal === false){
        nextTick(()=>{
            console.log('chartRef1 dom:', chartRef1.value)
            setChart()
        })
    }
})
onMounted(async () => {
    await getHomeworks(); 
    if (ShowTheHomeworkId.value) {
        await getStudents();
    } else {
        console.warn('未获取到作业 ID，无法加载学生数据');
    }
});
</script>

<style scoped>
.main{
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    .search{
    height: 50px;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    margin-top: 20px;
    .exportButton{
        height: 100%;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        margin-left: 20px;
        button{
            height: 27px;
            padding: 0 10px;
            border: 2px solid #e4e7ed;
            border-radius: 7px;
            background-color: #4a90c4;
            color: #fff;
            font-weight: 600;
        }
    }
    .searchInput{
        height: 100%;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        margin-left: 20px;
        input{
            border: 2px solid #e4e7ed;
            border-right: none;
            height: 27px;
            border-radius: 7px 0 0 7px;
            padding: 0 10px;
            color: #606266;
        }
        input::placeholder {
            color:#c2c4c9;
        }
        .fix{
            background-color: #f5f7fa;
            padding: 2px 10px;
            color:#b8b8b8;
            font-weight: 600;
            border: 2px solid #e4e7ed;
            border-radius: 0 7px 7px 0;
        }
    }
    .Myselect{
        margin-left: 15px;
        display: flex;
        flex-direction: row;
        select {
            border: none;
            background-color: #4a90c4;
            font-size: 14px;
            font-weight: 600;
            color:#fff;
            padding: 3px 10px;
            padding-right: 0;
            border-radius: 5px 0 0 5px;
            max-width: 100px;
        }
        select:focus {
            outline: none;
            border: none;
            background-color: #FFF;
            border: 3px solid #4a90c4;
            border-right: 0;
            color:#4a90c4;
        }
        .show{
            width: fit-content;
            color: #4a90c4;
            border: 3px solid #4a90c4;
            font-weight: 600;
            padding-left: 6px;
            padding-right: 5px;
            border-radius: 0 5px 5px 0;
        }
    }
}
.content{
    width: 100%;
    flex-grow: 1;
    display: flex;
    flex-direction: row;
    gap: 40px;
    .half-table{
        width: 50%;
        height: 100%;
        .highScore{
            padding: 2px 10px;
            background-color: #7ADBB0;   
            color: #fff;
            border-radius: 20px;
            width: fit-content;
            margin: auto;
        }
        .midScore{
            padding: 2px 10px;
            background-color: #F0C05A;   
            color: #fff;
            border-radius: 20px;
            width: fit-content;
            margin: auto;
        }
        .lowScore{
            padding: 2px 10px;
            background-color: #F4A261;   
            color: #fff;
            border-radius: 20px;
            width: fit-content;
            margin: auto;
        }
        .unsubmitted{
            padding: 2px 10px;
            background-color: #C45C4A;   
            color: #fff;
            border-radius: 20px;
            width: fit-content;
            margin: auto;
        }
        .uncorrected{
            padding: 2px 10px;
            background-color: #D9D9D9;   
            color: #fff;
            border-radius: 20px;
            width: fit-content;
            margin: auto;
        }
        .chart{
            margin-top: 70px;
            margin-left: 30px;
            height: 300px;
            width: 100%;
        }
        .chart2{
            margin-left: 0;
            margin-right: 30px;
            padding-bottom: 50px;
        }
    }
    .Loading{
        font-size: 40px;
        color: #70bbdb;
        font-weight: 700;
        height: 100%;
        width: 100%;
        text-align: center;
        align-content: center;
    }
}
.pages{
    height: 30px;
    margin-top: 10px;
}
}
</style>