<template>
    <view class="page">
        <view class="txt-white ui-flex-row ui-flex-align-center"
            style="border-bottom: 4px solid #4472C4;padding-left: 40rpx;height: 54px;width: 100%;z-index: 10;backdrop-filter: blur(4px);box-sizing: border-box;"
            :style="{'background-color': multiSelect ? '#4472c4' : ''}">
            <view class="ui-p ui-flex-row">
                <text class="f40">{{chooseClassName}}</text>
                <view class="ui-flex-row">
                    <text class="f40 ui-ml30 ui-mr10">{{teacher.teacher_name}}</text>
                    <!-- <u-icon name="arrow-down-fill" color="#fff"></u-icon> -->
                </view>
            </view>

            <view class="ui-p ui-flex ui-flex-1 ui-flex-align-center" style="justify-content: end;width: 450px;"
                v-if="multiSelect">
                <view class="ui-mr30">
                    <text class="f32" style="#9ccbff">请点击选择学生批量点评</text>
                </view>
                <view class="ui-flex" style="width: 320px;">
                    <el-button @click="setMulti(false)" plain text="取消选择" style="background-color: #0d4980;"
                        class="ui-mr10">取消选择</el-button>
                    <el-badge :value="activeList.length">
                        <el-button type="primary" @click="commentMulti()">
                            批量点评
                        </el-button>
                    </el-badge>
					<el-badge :value="activeList.length" class="ui-ml30">
					    <el-button type="primary" @click="commentAll()">
					        全班点评
					    </el-button>
					</el-badge>
                </view>
            </view>
        </view>

        <!-- <view class="platform" v-if="chooseClassName">
            <view class="platform-text txt-white">讲台</view>
            <view class="ranked-radio"></view>
        </view> -->
        <Draggable class="ui-flex-row ui-flex-space-around" :disabled="!seatMove" forceFallback
            style="padding:20rpx 0 200rpx 0;" group="ii" @end="onMoveColumnEnd" @choose="activeList = []" v-model="list"
            :delay="500" animation="300">
            <view v-for="(column, index) in list" :key="index" class="ui-flex-column" :class="{
                        'ui-mrr' : !!(index%2),
                        'ui-mll' : !(index%2)
                    }">
                <!-- <view class="ui-flex-column" :class="{
                        'ui-mr10' : !!index%1,
                        'ui-ml10' : !!index%2
                    }"> -->
                <view @click="toClickStu(stuItem)" v-for="stuItem in column.nodes" :key="stuItem.key"
                    class="ui-flex-column ranked-item-tr ui-flex-align-center"
                    :class="{
                        active : activeList.includes(stuItem.id),
                        'ranked-item-hide' : !(stuItem.id || seatMove)
                    }">
                    <image class="stu-image" :src="getLevelIcon(stuItem)" style="width: 130rpx;height: 48rpx;"></image>
                    <image class="stu-image" style="width: 100rpx;height: 100rpx;margin-top: -20rpx; border-radius: 300px; " :src="cartoonHeadImg ? stuItem.student_cartoon_photo : stuItem.student_photo+'?x-image-process=style/square400'" mode=""></image>
                    <view class="stu-tag text-center ui-flex-row ui-mt10">
                        <view class="stu-tag-add ui-flex-1">{{stuItem.plus_score_total}}</view>
                        <view class="stu-tag-sub ui-flex-1">{{stuItem.minus_score_total}}</view>
                    </view>
                    <view class="txt-white f28 ui-pt10">
                        {{stuItem.title}}
                    </view>
                    <u-badge absolute style="left: 10px;top: 10px;"
                        :value="activeList.indexOf(stuItem.id) + 1"></u-badge>
                </view>
                <!-- </view> -->
            </view>
        </Draggable>

        <!-- 点评 -->
        <markScore @change='change' @close='onScoreClose' :stuList='activeList' ref="markScore"></markScore>

        <!-- 点评记录 -->
        <!--  :stuList="activeList" -->
        <markScoreList ref="markScoreList" :cartoonHeadImg="cartoonHeadImg" :chooseClassId="chooseClassId"></markScoreList>

        <!-- 随机点名 -->
        <randomRollCall ref="randomRollCall" :cartoonHeadImg="cartoonHeadImg" :list="studentList" @comment="randomRollComment"></randomRollCall>

        <!-- 计时器 -->
        <timerClock ref="timerClock"></timerClock>

        <!-- 排行榜 -->
        <rankList ref="rankList" :cartoonHeadImg="cartoonHeadImg" :chooseClassId="chooseClassId"></rankList>

        <view v-if="seatMove" class="ui-pull-bottom ui-p"
            style="background-color: #0000006b;backdrop-filter: blur(4px);border-top: 1px solid #616161;">
            <view class="ui-flex-row ui-flex-center txt-white ui-mt10 ui-mb30">
                长按拖动调整整列，单选2位学生互相交换，
                <stuChangeExcel :stuList="list" @change="list = $event"></stuChangeExcel>
            </view>
            <view class="ui-flex-row ui-flex-center">
                <el-button round type="primary" @click="updateStuChange">保存座位</el-button>
                <el-button round type="text" @click="setSeatMove(false)">取消</el-button>
            </view>
        </view>

        <view v-else class="ui-pull-bottom ui-flex-row ui-p"
            style="background-color: #0000006b;backdrop-filter: blur(4px);border-top: 1px solid #616161;">
            <view class="ui-flex-1 ui-flex-row">

                <el-dropdown trigger="click" @command="doChooseClass">
                    <view-btn-item title="选择班级" src="../../static/jyicon/shubao.png"></view-btn-item>
                    <el-dropdown-menu slot="dropdown" :class="{'min-height': classesList.length >= 10}">
                        <el-dropdown-item v-for="(item) in classesList" :key="item.id" :command="item">
                            <text class="ui-mr10">{{item.class_name}}</text>
                            <text v-if="item.id == chooseClassId" class="el-icon-check"></text>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>

                <view-btn-item title="点评记录" src="../../static/jyicon/kedan.png"
                    @click="$refs.markScoreList.open()"></view-btn-item>
                <view-btn-item title="切换头像" src="../../static/jyicon/chengchang.png"
                    @click="cartoonHeadImg = !cartoonHeadImg"></view-btn-item>
                <view-btn-item title="座位调整" src="../../static/jyicon/xuewei.png"
                    @click="setSeatMove(true)"></view-btn-item>
                <view-btn-item :title="multiSelect ? '取消多选' : '学生多选'" src="../../static/jyicon/gerenzhongxin.png"
                    @click="setMulti(!multiSelect)"></view-btn-item>
                <view-btn-item title="随机点名" src="../../static/jyicon/fangfa.png"
                    @click="$refs.randomRollCall.open()"></view-btn-item>
                <view-btn-item title="计时器" src="../../static/jyicon/shalou.png"
                    @click="$refs.timerClock.open()"></view-btn-item>
                <view-btn-item title="撤销点评" src="../../static/jyicon/dingyue.png"
                    :class="[lastTipBatchId ? 'bottom-btn-item' : 'bottom-btn-item-disabled']"
                    @click="repealScore()"></view-btn-item>
            </view>

            <view class="ui-flex-row">
                <view-btn-item title="排行榜" src="../../static/jyicon/jiangpai.png"
                    @click="$refs.rankList.open()"></view-btn-item>
                <!-- <view-btn-item title="切换老师" src="../../static/jyicon/jiangpai.png" @click="debug"></view-btn-item> -->
                <view-btn-item title="退出登录" src="../../static/jyicon/xiaoxi.png" @click="loginOut()"></view-btn-item>
            </view>
        </view>
    </view>
</template>

<script>
    import Draggable from "@/components/vuedraggable/src/vuedraggable.js";
    import markScore from './components/mark-score.vue'
    import markScoreList from './components/mark-score-list.vue'
    import randomRollCall from './components/random-roll-call.vue'
    import timerClock from './components/timer-clock.vue'
    import rankList from './components/rank-list.vue'
    import viewBtnItem from './components/view-button-item.vue'
    import stuChangeExcel from './components/students-change-excel.vue'
    import {
        getStuSchoolIdByStuClassId
    } from "@/common/api/stu.js"
    // const ExcelJS = require('exceljs');

    export default {
        components: {
            markScore,
            markScoreList,
            randomRollCall,
            timerClock,
            rankList,
            viewBtnItem,
            Draggable,
            stuChangeExcel,
        },
        data() {
            return {
                // show_classes: false,
                list: [],
                classesList: [],
                chooseClassName: '',
                chooseClassId: '',
                activeList: [],
                multiSelect: false,
                lastTipBatchId: '', // 最后点评的uuid，用于撤销,
                seatMove: false, //0不调整
                cartoonHeadImg : true,
            }
        },
        computed: {
            studentList() {
                let list = [];
                this.list.forEach(item => {
                    item.nodes.forEach(el => {
                        if (el.id) {
                            list.push(el)
                        }
                    })
                })
                return list;
            },
            teacher() {
                return this.$store.state.teacherInfo || {}
            }
        },
        onLoad() {
            this.getClassroomList();

            let teacher_id = this.teacher.id;
            this.$api.sendRequest({
                url: `/mobile/teacher/draw`,
                method: "get",
                data: {
                    teacher_id: teacher_id,
                    year: 2024

                },
                success: res => {

                }
            })
        },
        methods: {
            debug() {
                console.log(this)
            },
            getLevelIcon(item) {
                let url = '//zhxy.obs.cn-hz1.ctyun.cn:443/static/';
                if (item.score_total == 0) {
                    return url + 'tag_level/0.png'
                }
                let val = ~~((item.score_total) / 10);
                val = (val <= 0 ? 1 : val);
                val = (val >= 16 ? 16 : val);
                return url + 'tag_level/' + val + '.png';
            },
            // change(e) {
            //     this.type = e == 0 ? 1 : 2
            //     this.getTabs()
            // },
            setMulti(value) {
                this.multiSelect = value;
                this.activeList = [];
            },
            loginOut() {
                uni.removeStorageSync("teacherInfo")
                uni.removeStorageSync("token", '')
                uni.reLaunch({
                    url: "/pages/login/login"
                })
            },
            doChooseClass(val) {
                uni.setStorage({
                    key: 'lastClasses',
                    data: val,
                    success(e) {
                        console.log(e)
                    }
                });

                this.chooseClassId = val.id
                this.chooseClassName = val.class_name
                this.getStudent()
                // this.show_classes = false
            },
            // DelectSuccess(index) {
            //     console.log(index);
            //     this.getStudent()
            //     this.getstudentTabLog()
            // },
            getClassroomList() {
                let teacher_id = this.teacher.id
                this.$api.sendRequest({
                    url: `/mobile/teacher/teachClasses`,
                    method: "post",
                    data: {
                        teacher_id: teacher_id
                    },
                    fali: res => {
                        console.log(res);
                    },
                    success: res => {
                        this.classesList = res.data;
                        if (res.data.length) {
                            let value = uni.getStorageSync('lastClasses')
                            this.$nextTick(() => {
                                this.doChooseClass(value || res.data[0])
                            })
                        }
                    }
                })
            },
            // 随机点名后批量评价
            randomRollComment(checkList) {
                if (checkList.length) {
                    this.activeList = checkList.map(item => {
                        return item.id
                    });
                    this.commentMulti();
                }
            },
            // 多选学生点评
            commentMulti() {
                // this.stuName = this.stuNameList.toString()
                let title = this.activeList.map(stuId => {
                    return this.studentList.find(el => {
                        return el.id == stuId;
                    }).title;
                }).join();
				if (title.length > 15) {
					title=title.substring(0, 15) + '...';
				}

                // this.getTabs()
                this.$refs.markScore.open(title);
            },
			commentAll() {
				this.activeList=[]
			    let title = "全班"
				this.list.map(item=>{
					item.nodes.map(item2=>{
						if(item2.id){
							this.activeList.push(item2.id)
						}
					})
				})
			
			    // this.$refs.markScore.open(title);
			},
            setSeatMove(value) {
                if (value) {
                    this.setMulti(false);
                    this.listCopy = uni.$u.deepClone(this.list);
                } else {
                    this.list = uni.$u.deepClone(this.listCopy);
                }
                this.seatMove = value;
                this.activeList = [];
            },
            // 两个学生交换位置
            onMoveStuChange(id1, id2) {
                this.list.forEach(item => {
                    item.nodes.forEach((el, index) => {
                        if (el == this.onMoveStuChange._move1) {
                            // console.log(1,el);
                            this.$set(item.nodes, index, uni.$u.deepClone(this.onMoveStuChange._move2));
                        }
                        if (el == this.onMoveStuChange._move2) {
                            this.$set(item.nodes, index, uni.$u.deepClone(this.onMoveStuChange._move1));
                        }
                    })
                })
                this.activeList = [];
            },
            
            onMoveColumnEnd(list) { //自动处理，无需改变
                // console.log(list);
            },
            // 更新座位
            updateStuChange() {
                let seat_list = this.list.map(item => {
                    let nodesLen = item.nodes.length;
                    return {
                        id: item.id,
                        title: item.title,
                        nodes: item.nodes.filter((el, index) => {
                            if(el.id){
                                return true;
                            }
                            
                            return index + 1 < nodesLen;
                        }).map(el => {
                            return {
                                id: el.id,
                                key: el.key,
                                title: el.title
                            }
                        })
                    }
                })
                // console.log(seat_list);
                // return;
                this.$api.sendRequest({
                    url: `/mobile/saveSeat`,
                    method: "PUT",
                    data: {
                        classroom_id: this.chooseClassId,
                        seat_list: seat_list
                    },
                    success: res => {
                        uni.showToast({
                            title: res.msg,
                        });
                        this.seatMove = false;
                        // this.setSeatMove(true);
                    }
                })
            },
            // 点击学生
            toClickStu(item) {
                if(!item.id){
                    if(!this.seatMove){
                        return;
                    }
                    if(this.seatMove && this.activeList.length == 0){
                        return;
                    }
                }
                if (this.seatMove) { //单个换位置
                    if (this.activeList.length == 0) {
                        this.activeList.push(item.id);
                        this.onMoveStuChange._move1 = item;
                    } else {
                        this.onMoveStuChange._move2 = item;
                        this.onMoveStuChange(this.activeList[0], item.id);
                    }
                    return;
                }

                if (this.multiSelect) {
                    let index = this.activeList.indexOf(item.id)
                    if (index >= 0) {
                        this.activeList.splice(index, 1);
                    } else {
                        this.activeList.push(item.id);
                    }
                    return;
                }

                this.activeList = [item.id];
                this.commentMulti();
            },
            // 获取学生列表
            getStudent() {
                this.$api.sendRequest({
                    url: `/mobile/studentTab/seat`,
                    data: {
                        class_id: this.chooseClassId
                    },
                    success: res => {
                        this.list = res.data;
                        /* .reverse().map(item => {
                                                    item.nodes = item.nodes.reverse().filter(el => {
                                                        return !!el.id;
                                                    })
                                                    return item;
                                                }) */
                    }
                })
            },
            // getTabs() {
            //     this.$api.sendRequest({
            //         url: `/mobile/studentTab/getStudentTabs`,
            //         method: "post",
            //         data: {
            //             teacher_id: this.$store.state.teacher_id,
            //             type: this.type
            //         },
            //         success: res => {
            //             this.tabList = res.data
            //         }
            //     })
            // },
            onScoreClose(lastTipBatchId = false) {
                if (lastTipBatchId) {
                    this.activeList = []
                    this.multiSelect = false
                    this.getStudent();
                    this.lastTipBatchId = lastTipBatchId;
                }
                // this.getstudentTabLog()
            },
            repealScore() {
                this.$api.sendRequest({
                    url: `/mobile/studentTab/multiDelStudentTabLog`,
                    method: "post",
                    data: {
                        batch_id: this.lastTipBatchId
                    },
                    success: res => {
                        this.lastTipBatchId = null;
                        this.getStudent();
                    }
                })
            }
        },
    }
</script>

<style lang="scss" scoped>
    .page {
        background-image: url('https://zhxy.obs.cn-hz1.ctyun.cn:443/static/desk_bg/class_bj.jpg');
        background-size: 100% 100%;
        height: auto;
        // width: 750rpx;
    }

    .platform {
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        height: 30rpx;
        margin-top: 60rpx;

        .platform-color {
            position: absolute;
            left: 0;
            top: 0;
            height: 60rpx;
            background-color: rgba(5, 204, 161, 1);
            width: 10rpx;
        }

        .platform-text {
            text-align: center;
            width: 60%;
            margin-bottom: 40rpx;
        }
    }

    .pop-title {
        border-bottom: 1px solid #f2f2f2;
        font-size: 36rpx;
        padding-bottom: 20rpx;
        display: flex;
        align-items: center;
    }

    .popup-content {
        border-radius: 10px;
        box-sizing: border-box;
        padding: 0 32rpx;
    }

    .btn-roll {
        background-color: #fff;
        border-radius: 25rpx;
        width: 190rpx;
        color: #666;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        margin-left: 32rpx;
    }

    .ranked {
        width: 100%;
        text-align: center;
        font-size: 10px;
        box-sizing: border-box;
        display: flex;
        padding-top: 80rpx;
    }

    .ranked-item-tr {
        position: relative;
        margin-bottom: 26rpx;
        padding-top: 16rpx;
        padding-bottom: 16rpx;
        border-radius: 5px;
        box-sizing: border-box;
        width: 100%;
        cursor: pointer;
        transition: 100ms;
        display: flex;
        justify-content: center;
    }
    .ranked-item-tr:hover,
    .active {
        background: #ffffff85;
    }
    .ranked-item-hide .stu-tag,
    .ranked-item-hide .stu-image,
    {
        opacity: 0;
    }
    
    .min-height {
        max-height: 400px;
        overflow-y: scroll;
    }

    .ranked-radio {
        width: 100px;
        position: absolute;
        left: 50%;
        transform: translate(-50%);
        bottom: 0rpx;

        border-bottom: 3px solid rgba(5, 204, 161, 1);
        border-radius: 50% 50% 0 0;
    }

    .visit-item {
        display: flex;
        align-items: center;

        .visit-item-left {
            width: 120rpx;
            color: #666;
        }
    }

    .stu-tag {
        width: 160rpx;
        margin-left: 10rpx;
        margin-right: 10rpx;
        border-radius: 15px;
        overflow: hidden;
    }

    .stu-tag-add {
        background-color: #ecf5ff;
        color: #3c9cff;
        border: 1px solid #fff;
    }

    .stu-tag-sub {
        background-color: #fef0f0;
        color: #f56c6c;
        border: 1px solid #fff;
        border-left: 0;
    }

    .ui-mrr {
        margin-right: 50rpx;
    }

    .ui-mll {
        margin-left: 50rpx;
    }

    .sortable-chosen {
        background-color: #fbfbfb66;
        border-radius: 5px;

    }

    .sortable-ghost {
        // margin-left : 0 !important;
        // margin-right : 0 !important;
        background-color: #fbfbfb00;
    }
</style>