<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="输入姓名或学号">
                <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>

            <button @click="visible_add=true"> 添加学生 </button>

            <button class="import_class" @click="importData">批量导入学生</button>

            <classToggle v-model:isLeft="isSingleDelete">
                <template #left>
                    单个删除
                </template>
                <template #right>
                    批量删除
                </template>
            </classToggle>

            <button v-show="!isSingleDelete" class="Del" @click="DeleteStudents()">确认删除</button>
        </div>
        <div class="content">
            <div class="Loading" v-show="!DataLoading">Loading...</div>
            <classTable v-show="DataLoading">
                <template #head>
                    <tr>
                        <th>序号</th>
                        <th>学生姓名</th>
                        <th>学号</th>
                        <!-- <th>是否加入班级</th> -->
                        <th>
                                <span v-show="!isSingleDelete" style="margin-right: 5px;">全选</span>
                                <input 
                                    type="checkbox"
                                    v-show="!isSingleDelete"
                                    v-model="allDeleted"
                                >
                        </th>
                    </tr>
                </template>
                <template #body>
                    <tr v-for="(item,index) in showData" :key="index+item.officialNumber">
                        <template v-if="item.officialNumber!==0">
                            <td>{{ (currentPage-1)*5+index+1 }}</td>
                            <td  
                                @click="$router.push(`/home/studentDetail?classId=${classId}&courseId=${courseId}&stuId=${item.studentId}`)"
                                @mouseenter="hoverStuId=item.officialNumber" 
                                @mouseleave="hoverStuId=-1"
                                :class="{Gethover:hoverStuId===item.officialNumber,Blue:true}"
                                >{{ item.stuName }}</td>
                            <td>{{ item.officialNumber }}</td>
                            <!-- <td>
                                <div class="added" v-if="item.stateCode===1">已加入 </div>
                                <div class="notadd" v-else> 未加入</div>                        
                            </td> -->
                            <td>
                                <button v-show="isSingleDelete" class="Del" @click="handleDelete(item.officialNumber)">DEL</button>
                                <input 
                                    type="checkbox"
                                    v-show="!isSingleDelete" 
                                    :value="item.officialNumber" 
                                    v-model="deleteIds"
                                    @change="console.log(deleteIds)"
                                >
                            </td>
                        </template>
                        <template v-else>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </template>
                    </tr>
                </template>
            </classTable>
        </div>
        <div class="pages">
            <el-pagination
                v-model:current-page="currentPage"
                :page-size="5"
                :pager-count="5"
                layout="total, prev, pager, next"
                :total="searchData.length"
            />
        </div>
    </div>

    <div v-if="visible_del" class="modal-mask" @click.self="isloading || (visible_del=false)" >
        <div class="modal-container">
            <div class="modal-header">
                <h2>{{isloading?"删除中...":"你确定要删除 "+deleteName+":"+deleteId+" 吗？"}}</h2>
            </div>
            <div class="modal-footer">
                <button class="yes-button" @click.stop="DeleteStudent" :disabled="isloading">确定</button>
                <button class="no-button" @click.stop="visible_del=false;" :disabled="isloading">取消</button>
            </div>
        </div>
    </div>

    <div v-if="visible_add" class="modal-mask" @click.self="isloading_add || (visible_add=false)" >
        <div class="modal-container">
            <div class="add1" v-show="!isloading_add">
                <h2>学生姓名：</h2> <input type="text" v-model.trim="addStudentName" ></input>
            </div>
            <div class="add1" v-show="!isloading_add">
                <h2>学生学号：</h2> <input type="text" v-model.trim="addOfficalNumber" ></input>
            </div>
            <div class="add1" v-show="isloading_add" 
            :style="{'height': '66%', 'margin-left':'210px'}">
                <h2>上传中...</h2>
            </div>
            <div class="modal-footer add2">
                <button class="yes-button" @click.stop="AddStudent" :disabled="isloading_add">确定</button>
                <button class="no-button" @click.stop="visible_add=false" :disabled="isloading_add">取消</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import classTable from './components/classTable.vue';
import classToggle from './components/classToggle.vue'
import {onMounted, reactive, ref, computed} from 'vue';
import { useRoute } from 'vue-router';
import type {ClassStudentVO} from "@/types/vo";
import useApis from "@/apis";
import { get } from 'http';

const route = useRoute()
const apis = useApis()
const classId = +route.query.classId;
const courseId = +route.query.courseId;

const currentPage = ref(1)
const searchInput = ref("")
const visible_add = ref(false)
const visible_del = ref(false)
const isloading = ref(false)
const isloading_add = ref(false)
const addStudentName = ref("")
const addOfficalNumber = ref("")
const deleteId = ref(-1)
const deleteIds = ref<number[]>([])
const deleteName = ref("")
const hoverStuId = ref(-1)
const isSingleDelete = ref(true)

const StudentsDataLoading = ref(false)

const Studentsdata = reactive<ClassStudentVO[]>([])

const handleDelete = (sid) => {
    visible_del.value = true
    deleteId.value = sid
    deleteName.value = Studentsdata.find((item)=>{
        return item.officialNumber === sid
    }).stuName
}
const importData = async () => {
    console.log("importData");
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.xlsx,.xls,.csv'
    input.addEventListener('change', async (e) => {
        const target = e.target as HTMLInputElement
        const selectedFile = target.files?.[0]
        if (!selectedFile) {
            isloading_add.value = false
            return
        }
        isloading_add.value = true
        try {
            const res = await apis.importStudentsOfClass(classId, selectedFile)
            console.log('Import response:', res)
            getStudents()
        } catch (error) {
            console.error('Import failed:', error)
        } finally {
            isloading_add.value = false
        }
    })
    input.click()
}
const DeleteStudent = async () =>{
    isloading.value = true
    await apis.deleteStudentOfClass(classId,[deleteId.value])
        .then((res:any)=>{console.log(res);
        })
    visible_del.value=false
    isloading.value = false
    getStudents()
}
const DeleteStudents = async () => {
    isloading.value = true
    visible_del.value = true
    await apis.deleteStudentOfClass(classId,deleteIds.value)
        .then((res:any)=>{console.log(res);
        })
    deleteIds.value=[]
    visible_del.value=false
    isloading.value = false
    getStudents()
}
const AddStudent = async () => {
    isloading_add.value = true
    console.log(addStudentName.value)
    console.log(+addOfficalNumber.value)
    console.log(classId);
    await apis.addStudentOfClasss(classId,+addOfficalNumber.value)
    isloading_add.value = false
    visible_add.value=false
    addStudentName.value = ""
    addOfficalNumber.value = "" 
    console.log("添加成功");
    getStudents()
    // setTimeout(()=>{
    //     isloading_add.value = false
    //     visible_add.value=false
    //     addStudentName.value = ""
    //     addOfficalNumber.value = "" 
    // }, 1000)
}

const getStudents = () => {
    apis.getStudentsOfClass(classId)
        .then((res:any) => {
            Studentsdata.length=0
            console.log(res.data.data);
            res.data.data.forEach(item => Studentsdata.push(item))
            console.log(res.data);
            StudentsDataLoading.value = true
        })
    
}

const searchData = computed(()=>{
    if(searchInput.value===""){
        return Studentsdata
    }
    else{
        return Studentsdata.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)*5,currentPage.value*5)
    while(showdata.length<5){
        showdata.push(    {
        "officialNumber": 0,
        "stuName": "",
        "stateCode": -1,
        "stateDesc": "",
        "studentId": -1
        })
    }
    return showdata
})
const DataLoading = computed(() => {
  return StudentsDataLoading.value
})

const allDeleted = computed({
    get() {
        return deleteIds.value.length === Studentsdata.length
    },
    set(newValue) {
        if(newValue === true){
            deleteIds.value = <number[]>[]
            Studentsdata.forEach((item)=>{
                deleteIds.value.push(+item.officialNumber)
            })
        }
        else{
            deleteIds.value = <number[]>[]
        }
    }
})

onMounted(() => {
    getStudents()
})
</script>

<style scoped>
.main{
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}
.import_class{
    font-size: 14px;
    padding: 1px 12px;
    background-color: #c45c4a;
    color: #fff;
    border: none;
    border-radius: 20px;
    cursor: pointer;
}
.search{
    height: 50px;
    width: 100%;
    margin-top: 20px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    .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;
        }
        
    }
    button{
        background-color: #4a90c4;
        font-size: 14px;
        font-weight: 700;
        border: none;
        padding: 4px 10px;
        color: #fff;
        margin-left: 30px;
        border-radius: 5px;
        cursor: pointer;
    }
}
.content{
    width: 100%;
    flex-grow: 1;
    .Loading{
        font-size: 40px;
        color: #70bbdb;
        font-weight: 700;
        height: 100%;
        text-align: center;
        align-content: center;
    }
}
.Del{
    font-size: 14px;
    padding: 1px 12px;
    background-color: #c45c4a;
    color: #fff;
    border: none;
    border-radius: 20px;
    cursor: pointer;
}
.pages{
    height: 30px;
    margin-top: 10px;
}
.added{
    color: #fff;
    background-color: #7adbb0;
    width: 62px;
    height: 20px;
    margin: auto;
    border-radius: 20px;
    font-weight: 600;
}
.notadd{
    color: #fff;
    background-color: #d9d9d9;
    width: 62px;
    height: 20px;
    margin: auto;
    border-radius: 20px;
    font-weight: 600;
}
input[type="checkbox"]{
    margin-bottom: -2px;
    appearance: none; /* 隐藏默认样式 */
    -webkit-appearance: none;
    width: 15px;
    height: 15px;
    border: 2px solid #4a90c4; /* 边框 */
    border-radius: 4px;    
}
input[type="checkbox"]:checked {
  background-color: #4a90c4; /* 绿色 */
  border-color: #4a90c4;
}
.modal-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    .modal-container {
        border-radius: 30px;
        border: 7px solid #70BBDB;
        background: #FFF;
        box-shadow: 0 4px 4px 0 rgba(0, 0, 0, 0.25);
        width: 35vw;
        height: 25vh;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .modal-header {
            padding: 16px 20px;
            height: 50%;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            color:#70bbdb
        }
        .modal-footer {
            padding: 12px 20px;
            height: 50%;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            gap: 50px;
            .yes-button{
                background-color: #c45c4a;
                color: #fff;
                border: 0;
                padding: 3px 25px;
                font-size: 22px;
                font-weight: 600;
                border-radius: 20px;
                margin-right: 20px;
            }
            .no-button{
                background-color: #4a90c4;
                color: #fff;
                border: 0;
                padding: 3px 25px;
                font-size: 22px;
                font-weight: 600;
                border-radius: 20px;
                margin-right: 20px;
            }
            button{
                cursor: pointer;
            }
            button:disabled{
                background-color: #d9d9d9;
            }
        }
        .add1 {
            height: 33%;
            display: flex;
            flex-direction: row;
            justify-content: start;
            align-items: center;
            color:#70bbdb;
            margin-left: 80px;
            input,select {
                border: none;
                border-bottom: 3px solid #70bbdb;
                font-size: 16px;
                font-weight: 600;
                color:#70bbdb
            }
            input::placeholder {
                color:#b2d7e7
            }
            input:focus,select:focus {
                outline: none;
                border: none;
                outline: 5px solid #70bbdb;
            }
            span{
                font-size: 16px;
                font-weight: 600;
                margin: 0 15px;
            }
        }
        .add2 {
            height: 33%;
        }
    }   
}
</style>