<template>
    <div>
        <!-- <loading :active.sync="isLoading"
                 :is-full-page="true"
                 background-color="#000"
                 :opacity="0.6">
            <template slot="default">
                <svg-icon icon-class="loader" class="loader-icon" />
            </template>
        </loading> -->
        <Loading v-show="isLoading" bgColor="rgba(0, 0, 0, 0.3)"></Loading>
        <div class="home-view">
            <Row :gutter="30" v-if="spanCharts == false">
                <i-col :xs="0" :sm="0" :md="0" :lg="1"></i-col>
                <i-col :xs="24" :sm="24" :md="12" :lg="7">
                    <!-- 加入课程 -->
                    <Card :bordered="true" class="calenderCard">
                        <p slot="title">
                            <svg-icon class="titleIcon" icon-class="calander" />
                            <span class="title">{{ $t("studentWeb.addCourse") }}</span>
                        </p>
                        <div class="addClass">
                            <Input clearable
                                v-model="addClassNo"
                                :placeholder="$t('studentWeb.home.classPla')"
                            >
                                <Button slot="append" @click="addClass">{{ $t('studentWeb.home.joinClass') }}</Button>
                            </Input>
                        </div>
                    </Card>
                    <!-- 课程清单 -->
                    <!-- <router-link to="/studentWeb/courseList"> -->
                        <Card style="overflow: hidden; margin-bottom: 30px">
                            <h3 style="color: #575757; font-weight: 700; margin: 10px 0 15px; cursor: pointer;"
                                @click="() => {this.$router.push('/studentWeb/courseList')}"
                            >
                                <svg-icon class="titleIcon" icon-class="course" />
                                {{ $t("studentWeb.coursesCardTitle") }}
                                <Icon type="ios-arrow-forward" />
                            </h3>
                            <div class="new-join">
                                <p class="title-rect-name">{{ $t("studentWeb.newAddCourse") }}</p>
                                <div v-if="joinCourse.length" style="height: 45vh; overflow: auto;">
                                    <div v-for="(item, index) in joinCourse" :key="index">
                                        <div v-if="index < 5" class="course-new">
                                            <div class="course-title">
                                                <span class="course-type">{{ item.type }}</span>
                                                <span>{{ item.name }}</span>
                                                <p>{{ item.teacher}}</p>
                                            </div>
                                            <p class="time">
                                                <span>加入时间：{{ item.time }}</span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                <p v-else class="course-new">{{ $t("evaluation.noData") }}</p>
                            </div>
                        </Card>
                    <!-- </router-link> -->
                    
                    <!-- 行事历 -->
                    
                </i-col>
                <i-col :xs="24" :sm="24" :md="12" :lg="8">
                    <!-- 活动任务清单 -->
                    <MissionListCard :testData="testData" />
                </i-col>
                <i-col :xs="24" :sm="24" :md="12" :lg="7">
                    <Card :bordered="true" class="barCard" style="display: none">
                        <div class="no-data-text">
                            <img
                                src="@/assets/icon/no_data_evaluation.png"
                                width="120"
                            />
                            <span style="margin-top: 15px; color: #808080">{{
                                $t("studentWeb.public.noData")
                            }}</span>
                        </div>
                        <!-- <div style="position: relative">
                            <div class="spanAllchartBtn" @click="setSpanCharts()">
                                <svg-icon
                                    class="spanAllchartIcon"
                                    icon-class="dimensions"
                                />
                            </div>
                            <ChartCarousel />
                        </div> -->
                    </Card>
                    <Card class="barCard">
                        <h3 style="color: #575757; font-weight: 700">
                            <svg-icon class="titleIcon" icon-class="target" />
                            {{ $t("studentWeb.myProgressBar.tasksCompletionRate") }}
                        </h3>

                        <div class="myProgressBar">
                            <span class="myTestProgressNum">
                                {{ finishAct }}
                                <span style="font-size: 20px">&nbsp;%</span>
                            </span>
                            <Progress class="myTestProgress"
                                    :percent="finishAct"
                                    :stroke-color="['#108ee9', '#87d068']"
                                    :hide-info="true"
                            />
                        </div>
                    </Card>
                    <Card @click.native="noData" style="display: none">
                        <h3 style="color: #575757; font-weight: 700">
                            <svg-icon
                                class="titleIcon studyIcon"
                                icon-class="note"
                            />
                            {{ $t("studentWeb.myProgressBar.selfStudyClickRate") }}
                        </h3>
                        <div class="myProgressBar">
                            <span class="myTestProgressNum">
                                <!-- {{ 22 }} -->
                                --
                                <span style="font-size: 20px">&nbsp;%</span>
                            </span>
                            <div
                                class="myTestProgressContent"
                                :style="{ width: 0 + '%' }"
                                style="
                                    background: linear-gradient(
                                        90deg,
                                        #ffa400,
                                        #fa6400
                                    );
                                "
                            ></div>
                            <div class="myTestProgress"></div>
                        </div>
                    </Card>

                    <!-- 先放在这里，等自学这些有数据了，再放左边 -->
                    <!-- 行事历 -->
                    <Card :bordered="true" class="calenderCard" style="margin-bottom: 0">
                        <p slot="title">
                            <svg-icon class="titleIcon" icon-class="calander" />
                            <span class="title">{{ $t("studentWeb.calenderCardTitle") }}</span>
                        </p>
                        <!-- 上课提醒 -->
                        <div>
                            <p class="title-rect-name">{{ $t("studentWeb.recentClass") }}</p>
                            
                            <div class="remind-course">
                                <div style="height: 20vh; overflow: auto;" v-if="recentClass.length">
                                    <div class="list-one"
                                        v-for="(item, index) in recentClass"
                                        :key="index"
                                        @click="getCourse(item)"
                                    >
                                        <div class="classtitle">
                                            <span></span>
                                            {{ item.name }}
                                            <p>{{ item.teaName }}</p>
                                        </div>
                                        <p class="time">上课时间：{{ item.classTime }}</p>
                                        <p class="place">上课教室：{{ item.roomName }}</p>
                                    </div>
                                </div>
                                <div v-else class="no-data">{{ $t("studentWeb.public.noData") }}</div>
                            </div>
                        </div>
                        <!-- 今日截至 -->
                        <div class="todaydayline">
                            <div class="todaydaylinewraptitle">
                                <p class="title-rect-name">
                                    {{ $t("studentWeb.todaydeadlineList") }}
                                    <Icon type="ios-arrow-forward" />
                                </p>
                                <div class="todaydaylineList">
                                    <div v-if="!todayData.length" class="no-data">{{ $t("studentWeb.public.noData") }}</div>
                                    <div class="list-block"
                                        style='height: 27vh'
                                        v-else
                                    >
                                        <li :id="`tditem${index}`"
                                            class="list-item"
                                            v-for="(item, index) in todayData"
                                            :key="index"
                                            @click="sentSelectedEventTitle(item)"
                                            v-show="eventPageType.includes(item.eventType) == true && item.taskStatus != 1"
                                        >
                                            <ul>
                                                <li class="list-item-icon">
                                                    <svg-icon v-if="item.eventType == 'Homework'"
                                                            icon-class="doc"/>
                                                    <svg-icon v-if="item.eventType == 'Preview'"
                                                            icon-class="selflearninginTime"/>
                                                    <svg-icon v-if="item.eventType == 'Exam'"
                                                            icon-class="test"
                                                            class="reset-testIcon"/>
                                                    <svg-icon v-if="item.eventType == 'Vote'"
                                                            icon-class="vote"/>
                                                    <svg-icon v-if="item.eventType == 'Survey'"
                                                            icon-class="quesnaire"/>
                                                </li>
                                                <li class="list-item-info">
                                                    <p class="list-item-title">
                                                        <span v-show="item.eventType == 'Exam'" class="list-item-typeMark">{{item.owner == 'school'? $t('studentWeb.public.schoolExam'):$t('studentWeb.public.privateExam')}}</span>
                                                        <span v-show="item.eventType == 'Vote'" class="list-item-typeMark">{{item.owner == 'school'? $t('studentWeb.public.schoolVote'):$t('studentWeb.public.privateVote')}}</span>
                                                        <span v-show="item.eventType == 'Survey'" class="list-item-typeMark">{{item.owner == 'school'? $t('studentWeb.public.schoolSurvey'):$t('studentWeb.public.privateSurvey')}}</span>
                                                        <span>{{ item.name }}</span>
                                                    </p>
                                                    <p class="list-item-time">
                                                        {{ $t("studentWeb.endsToday") }}{{ item.todayTime }}{{ $t("studentWeb.endsTodayTime") }}
                                                    </p>
                                                </li>
                                            </ul>
                                        </li>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </Card>
                </i-col>
            </Row>
            <Row :gutter="30" v-if="spanCharts == true">
                <i-col :xs="0" :sm="0" :md="0" :lg="1"></i-col>
                <i-col :xs="24" :sm="24" :md="24" :lg="22">
                    <div class="allcharts">
                        <Row :gutter="30">
                            <div
                                class="spanAllchartBtn isOpen"
                                @click="setSpanCharts()"
                            >
                                <svg-icon
                                    class="spanAllchartIconNow"
                                    icon-class="dimensions"
                                />
                            </div>
                            <i-col :xs="24" :sm="24" :md="24" :lg="8">
                                <h3>{{ $t("studentWeb.chartNames[0]") }}</h3>
                                <StudyTimeChart />
                            </i-col>
                            <i-col :xs="24" :sm="24" :md="24" :lg="8">
                                <h3>{{ $t("studentWeb.chartNames[1]") }}</h3>
                                <SplineAreaChart />
                            </i-col>
                            <i-col :xs="24" :sm="24" :md="24" :lg="8">
                                <h3>{{ $t("studentWeb.chartNames[2]") }}</h3>
                                <StackBarChart />
                            </i-col>
                            <i-col :xs="24" :sm="24" :md="24" :lg="8">
                                <h3>{{ $t("studentWeb.chartNames[3]") }}</h3>
                                <TwoLineChart />
                            </i-col>
                            <i-col :xs="24" :sm="24" :md="24" :lg="8">
                                <h3>{{ $t("studentWeb.chartNames[4]") }}</h3>
                                <EventPieChart />
                            </i-col>
                            <i-col :xs="24" :sm="24" :md="24" :lg="8">
                                <h3>{{ $t("studentWeb.chartNames[5]") }}</h3>
                                <StudyHeatMap />
                            </i-col>
                        </Row>
                    </div>
                </i-col>
            </Row>
        </div>
        <br />
    </div>
</template>

<script>
/* import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/vue-loading.css"; */
import Loading from '@/common/Loading.vue'
import ChartCarousel from "./ChartCarousel/ChartCarousel";
import MissionListCard from "./MissionListCard";
import StudyTimeChart from "../HomeView/ChartCarousel/StudyTimeChart";
import EventPieChart from "../HomeView/ChartCarousel/EventPieChart";
import TwoLineChart from "../HomeView/ChartCarousel/TwoLineChart";
import StackBarChart from "../HomeView/ChartCarousel/StackBarChart";
import SplineAreaChart from "../HomeView/ChartCarousel/SplineAreaChart";
import StudyHeatMap from "../HomeView/ChartCarousel/StudyHeatMap";
import { mapState } from 'vuex';

export default {
    name: "HomeView",
    components: {
        Loading,
        ChartCarousel,
        MissionListCard,
        SplineAreaChart,
        StackBarChart,
        TwoLineChart,
        EventPieChart,
        StudyHeatMap,
        StudyTimeChart,
    },
    data() {
        return {
            eventPageType: ["Preview", "Exam", "Homework", "Vote", "Survey"], //本頁出現的類型
            MyNo: "1", //接收NavBar 選定的那一頁icon標示
            MyName: "",
            spanCharts: false,
            todaydaylineListHeight: 0,
            addClassNo: "", //加入课程的代码
            testData: [], //活动数据
            todayData: [], //今日活动
            finishAct: 0, //活动完成率
            weekTime: [
                {
                    title: this.$t("studentWeb.week.mon"),
                    value: "MON",
                },
                {
                    title: this.$t("studentWeb.week.tue"),
                    value: "TUE",
                },
                {
                    title: this.$t("studentWeb.week.wed"),
                    value: "WED",
                },
                {
                    title: this.$t("studentWeb.week.thu"),
                    value: "THU",
                },
                {
                    title: this.$t("studentWeb.week.fri"),
                    value: "FRI",
                },
                {
                    title: this.$t("studentWeb.week.sat"),
                    value: "SAT",
                },
                {
                    title: this.$t("studentWeb.week.sun"),
                    value: "SUN",
                }
            ],
            recentClass: [], //近期上课
            isLoading: false,
            joinCourse: [], //新加入课程
        };
    },

    methods: {
        //获取新活动信息数据
        getActivityInfo() {
            this.isLoading = true
            let params = {
                userid: this.userInfo.sub,
                userType: "",
                school: this.user.schoolCode
            }
            // 醍摩豆登陆——> roles有teacher
            if (this.userInfo.roles.includes("teacher")) {
                params.userType = "tmdid"
            }
            // 学生账号登陆
            else {
                params.userType = "schoolid"
            }
            this.$api.studentWeb.getActivityInfo(params).then(res => {
                if (res.datas.length) {
                    let data = []
                    for (let item of res.datas) {
                        item.eventType = item.type
                        item.progress = this.timeStatus(item)
                        data.push(item)
                    }
                    this.testData = [...this.testData, ...data]
                    this.testData = this.testData.sort(function (a, b) {
                        return b.startTime - a.startTime //时间正序
                    });
                    this.getTodayAct()
                }
            }).finally(()=>{
                this.isLoading = false
            })
        },
        timeStatus(data) {
            let date = (new Date()).getTime() //当前时间
            if (date >= data.endTime) {
                return 'finish'
            } else {
                return 'going'
            }
        },
        // 今日截至活动
        getTodayAct() {
            let todayAct = []
            let finishNum = 0
            let activity = this._.cloneDeep(this.testData)
            // 当前00:00:00
            let strdDate = (new Date(new Date(new Date().toLocaleDateString()).getTime())).getTime()
            // 当前23:59:59
            let endDate = (new Date(new Date(new Date().toLocaleDateString()).getTime() +24 * 60 * 60 * 1000 - 1)).getTime()
            activity.map(item => {
                if(item.endTime >= strdDate && item.endTime <= endDate && item.taskStatus != 1) {
                    item.todayTime = this.handleTime(item.endTime)
                    todayAct.push(item)
                }
                // taskStatus: 0：未完成，1：已完成，-1：初始状态
                if(item.taskStatus == 1) {
                    finishNum += 1
                }
            })
            this.todayData = todayAct
            this.finishAct = parseInt(finishNum / activity.length * 100)
        },
        handleTime(endTime) {
            let time = new Date(endTime)
            let h = time.getHours()
            let m = time.getMinutes()
            let s = time.getSeconds()
            if(h < 10) {
                h = '0' + h
            }
            if(m < 10) {
                m = '0' + m
            }
            if(s < 10) {
                s = '0' + s
            }
            let toTime = h + ":" + m
            return toTime
        },
        // 课程
        getClassList() {
            let param = {
                userid: this.userInfo.sub,
                school: this.userInfo.azp
            }
            if(this.userInfo.roles.includes("teacher")) {
                param.userType = "tmdid"
            } else {
                param.userType = "schoolid"
            }
            this.$api.studentWeb.getClassList(param).then(res => {
                if(res.courses.length) {
                    this.recentClass = []
                    let list = res.courses
                    list.forEach(item => {
                        if(item.course) {
                            item.course.schedule.forEach((sch, sIn) => {
                                // 有classId，表定课程
                                if(sch.classId == item.stuCourse.classId[0] && item.stuCourse.classId.length) {
                                    this.joinCourse.push({
                                        name: item.course.name,
                                        type: "标准课程",
                                        teacher: sch.teacherName,
                                        time: new Date(item.stuCourse.createTime).toLocaleDateString()
                                    })
                                    // 近期上课，就表示一定要有时间
                                    if(sch.time.length) {
                                        for (let m = 0; m < sch.time.length; m++) {
                                            let data = this.getNewCourse("class", item, sch, sIn, m)
                                            this.recentClass.push(data)
                                        }
                                    }
                                }
                                // 有stulist，临时课程
                                else if (sch.stulist == item.stuCourse.stulist[0] && item.stuCourse.stulist.length) {
                                    if(item.stuCourse.scope == "school") {
                                        this.joinCourse.push({
                                            name: item.course.name,
                                            type: "标准课程",
                                            teacher: sch.teacherName,
                                            time: new Date(item.stuCourse.createTime).toLocaleDateString()
                                        })
                                        if(sch.time.length) {
                                            for (let m = 0; m < sch.time.length; m++) {
                                                let data = this.getNewCourse("class", item, sch, sIn, m)
                                                this.recentClass.push(data)
                                            }
                                        }
                                    } else {
                                        this.joinCourse.push({
                                            name: item.course.name,
                                            type: "个人课程",
                                            teacher: sch.teacherName,
                                            time: new Date(item.stuCourse.createTime).toLocaleDateString()
                                        })
                                        if(sch.time.length) {
                                            for (let m = 0; m < sch.time.length; m++) {
                                                let data = this.getNewCourse("person", item, sch, sIn, m)
                                                this.recentClass.push(data)
                                            }
                                        }
                                    }
                                    
                                }
                            })
                        }
                    })
                    if(this.recentClass.length) {
                        this.findSchoolInfo()
                    }
                    this.joinCourse.reverse()
                }
            })
        },
        getNewCourse(attribute, list, sch, sIn, m) {
            let data = this._.cloneDeep(list.course)
            delete data.schedule
            data.school = list.stuCourse.school
            data.scope = list.stuCourse.scope
            data.classId = sch.classId
            // data.roomId = sch.room
            // data.teacherId = sch.teacherId
            data.notice = sch.notice
            data.stuList = sch.stulist
            data.timeId = sch.time[m].id
            data.timeWeek = sch.time[m].week
            this.weekTime.forEach(item => {
                if(item.value == sch.time[m].week) {
                    data.classTime = item.title
                }
            })
            data.roomName = sch.roomName ? sch.roomName : this.$t("studentWeb.courseContent.noRoom")
            data.teaName = sch.teacherName ? sch.teacherName : this.$t('studentWeb.courseContent.noTeacher')
            data.unique = attribute + list.course.no + sIn + m
            return data
        },
        // 查找班级——匹配对应的时间
        findSchoolInfo() {
            let params = {}
            // 醍摩豆登陆——> roles有teacher
            if (this.userInfo.roles.includes("teacher")) {
                params = {userType: "tmdid"}
            }
            // 学生账号登陆
            else {
                params = {userType: "schoolid"}
            }
            this.$api.studentWeb.getSchoolInfo(params).then(res => {
                if(res.status == 200 && res.school_base) {
                    let timeList = []
                    res.school_base.period.forEach(item => {
                        if(this.recentClass[0].period.id == item.id) {
                            timeList = item.timetable
                        }
                    })
                    if(timeList.length) {
                        this.recentClass.map(course => {
                            timeList.forEach(time => {
                                if(time.id == course.timeId) {
                                    course.time = time.time
                                    course.classTime = course.classTime + "  " + time.time + " (" + time.label + ")"
                                }
                            })
                        })
                    }
                }
            })
        },
        // 点击上课提醒跳转页面
        getCourse(course) {
            this.$router.push({
                name: "courseList",
                params: {
                    course: course
                }
            })
        },

        noData() {
            this.$Message.warning(this.$t("studentWeb.public.notice"))
        },
        setSpanCharts() {
            this.spanCharts = !this.spanCharts
        },
        // 加入课程
        addClass() {
            if(this.addClassNo) {
                let isStu = true
                this.userInfo.roles.map(item => {
                    if(item == "teacher") {
                        isStu = false
                    }
                })
                let req = {
                    stuListNo: this.addClassNo,
                    studentId: "",
                    tmdId: ""
                }
                if(isStu) {
                    req.studentId = this.userInfo.sub
                } else {
                    req.tmdId = this.userInfo.sub
                }
                this.$api.studentWeb.getAddClass(req).then(res => {
                    if(res.status == 0) {
                        // -1 课程编码错误，0加入成功，1参数异常，2重复加入
                        this.$Message.success(this.$t('studentWeb.courseType.success'))
                        this.addClassNo = ""
                        this.getClassList()
                    } else if(res.status == 2) {
                        this.$Message.warning(this.$t('studentWeb.courseType.warning'))
                    } else  if(res.status == -1){
                        this.$Message.warning(this.$t('studentWeb.courseType.error'))
                    } else {
                        this.$Message.error(this.$t('studentWeb.courseType.api'))
                    }
                })
            }
        },

        sentSelectedEventTitle: function (item) {
            this.$router.push({path: "/studentWeb/eventView"})
            //螢幕寬度<767px時，直接關掉sidebar
            if (window.innerWidth <= 768) {
                this.$store.commit("ToggleSidebar", false);
            }
            //改變ItemName的狀態 vuex mutations
            this.$store.commit("ChangeItemName", item);
        },
    },

    created() {
        (this.MyName = this.$t("studentWeb.homeView-title")),
        this.$emit("onNavNo", this.MyNo)
        this.$emit("onNavName", this.MyName)
        this.getActivityInfo()
        this.getClassList()
    },
    mounted() {
        /* if (document.getElementById("tditem0") != "") {
            document.getElementById("tditem0").style.display = "block"
            var item1Height = document.getElementById("tditem0").offsetHeight
            document.getElementById("tditem0").style.display = "none"
        }
        if (document.getElementById("tditem1") != "") {
            document.getElementById("tditem1").style.display = "block"
            var item2Height = document.getElementById("tditem1").offsetHeight
            document.getElementById("tditem1").style.display = "none"
        }
        this.todaydaylineListHeight = item1Height + item2Height + 20 */
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            user: state => state.user,
        })
    }
}
</script>

<style scoped>
@import "~@/assets/student-web/component_styles/home-view.css";
@keyframes born {
    from {
        width: 0;
    }

    to {
        width: finishAct + "%";
    }
}

@keyframes fadein {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}
.no-data-text {
    width: 100%;
    padding: 30px;
    background: #fff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 10px;
    font-size: 16px;
}
</style>
