<template>
    <div>
        <loading :active.sync="isLoad"
                 :is-full-page="fullPage"
                 background-color="#000"
                 :opacity="opacity">
            <template slot="default">
                <svg-icon icon-class="loader" class="loader-icon" />
            </template>
        </loading>
        <div class="course-list"
            :class="{ courselistEn: this.$store.getters.getCurrentLaguage == 'en-us' }"
        >
            <!--課程加入成功-->
            <div class="warmMessage"
                v-if=" this.$store.getters.getMycID.coureseMessageOpen == true &&
                        this.$store.getters.getMycID.addSuccess == true "
            >
                <div class="messageCard animate__animated animate__fadeInDown">
                    <div>
                        <h3>課程加入成功</h3>
                        <svg-icon icon-class="addCourseSuc" class="addCourseIcon" />

                        <h3>
                            <span class="typeMark">{{ this.$store.getters.getMycID.myCourseID[  this.$store.getters.getMycID.myCourseID.length - 1 ] }}</span>
                            <span>新加課程名稱</span>
                        </h3>
                        <p>可於左側課程清單檢視課程簡介</p>
                    </div>
                </div>
            </div>

            <!--課程已經加入-->
            <div class="warmMessage"
                v-if="this.$store.getters.getMycID.coureseMessageOpen == true &&
                    this.$store.getters.getMycID.addSuccess == 'exist'"
            >
                <div class="messageCard animate__animated animate__fadeInDown">
                    <div>
                        <h3>課程已經加入</h3>
                        <svg-icon icon-class="addCoursefail" class="addCourseIcon" />
                        <p>可於左側課程清單檢視該課程簡介</p>
                    </div>
                </div>
            </div>

            <!--課程加入失敗-->
            <div class="warmMessage"
                v-if="this.$store.getters.getMycID.coureseMessageOpen == true &&
                    this.$store.getters.getMycID.addSuccess == false"
            >
                <div class="messageCard animate__animated animate__fadeInDown">
                    <div>
                        <h3>課程加入失敗</h3>
                        <svg-icon icon-class="addCoursefail" class="addCourseIcon" />
                        <p>查無所輸入代碼之課程，或該課程您未獲教師授權參與</p>
                    </div>
                </div>
            </div>

            <div class="list">
                <ul class="list-block">
                    <Tabs :value="onlyStu ? (this.$store.getters.getMycID.addSuccess == true ? 'tab2' : 'tab1') : 'tab2' ">
                        <!-- 表定课程 -->
                        <TabPane :label="$t('studentWeb.defaultClass')"
                                name="tab1"
                                :align="currentView=='table'?'center':'left'"
                                v-if="onlyStu"
                        >
                            <!-- <div class="listViewBtn" @click="changeView('list')" :class="{chooseView:currentView=='list'}">
                                <svg-icon icon-class="list-text" />
                            </div>
                            <div class="tableViewBtn" @click="changeView('table')" :class="{chooseView:currentView=='table'}">
                                <svg-icon icon-class="table" />
                            </div> -->

                            <div class="list-table">
                                <Table :columns="courseTime"
                                        border
                                        :data="timeTable"
                                        v-show="currentView == 'table'"
                                        :disabled-hover="true"
                                >
                                    <!-- 时间 -->
                                    <template slot-scope="{ row }" slot="time">
                                        <p class="list-name">{{ row.time }}</p>
                                        <p>{{ row.label }}</p>
                                    </template>
                                    <!-- 周一 -->
                                    <template slot-scope="{ row }" slot="Mon">
                                        <div v-for="(item, index) in row.fixList" :key="index">
                                            <div v-if="item.timeWeek == 'MON'"
                                                class="table-item"
                                                @click="clickCell(row, index)"
                                                :class="{'table-item-selected': selectedCondition(item) }"
                                            >
                                                <p class="list-name">{{ item.name}}</p>
                                                <p>({{ item.teaName}})</p>
                                            </div>
                                        </div>
                                    </template>
                                    <!-- 周二 -->
                                    <template slot-scope="{ row }" slot="Tue">
                                        <div v-for="(item, index) in row.fixList" :key="index">
                                            <div v-if="item.timeWeek == 'TUE'"
                                                class="table-item"
                                                @click="clickCell(row, index)"
                                                :class="{'table-item-selected': selectedCondition(item) }"
                                            >
                                                <p class="list-name">{{ item.name}}</p>
                                                <p>({{ item.teaName}})</p>
                                            </div>
                                        </div>
                                    </template>
                                    <!-- 周三 -->
                                    <template slot-scope="{ row }" slot="Wed">
                                        <div v-for="(item, index) in row.fixList" :key="index">
                                            <div v-if="item.timeWeek == 'WED'"
                                                class="table-item"
                                                @click="clickCell(row, index)"
                                                :class="{'table-item-selected': selectedCondition(item) }"
                                            >
                                                <p class="list-name">{{ item.name}}</p>
                                                <p>({{ item.teaName}})</p>
                                            </div>
                                        </div>
                                    </template>
                                    <!-- 周四 -->
                                    <template slot-scope="{ row }" slot="Thu">
                                        <div v-for="(item, index) in row.fixList" :key="index">
                                            <div v-if="item.timeWeek == 'THU'"
                                                class="table-item"
                                                @click="clickCell(row, index)"
                                                :class="{'table-item-selected': selectedCondition(item) }"
                                            >
                                                <p class="list-name">{{ item.name}}</p>
                                                <p>({{ item.teaName}})</p>
                                            </div>
                                        </div>
                                    </template>
                                    <!-- 周五 -->
                                    <template slot-scope="{ row }" slot="Fri">
                                        <div v-for="(item, index) in row.fixList" :key="index">
                                            <div v-if="item.timeWeek == 'FRI'"
                                                class="table-item"
                                                @click="clickCell(row, index)"
                                                :class="{'table-item-selected': selectedCondition(item) }"
                                            >
                                                <p class="list-name">{{ item.name}}</p>
                                                <p>({{ item.teaName}})</p>
                                            </div>
                                        </div>
                                    </template>
                                </Table>
                            </div>

                            <!-- 表定 -->
                            <!-- <li class="list-item"
                                v-for="(item, index) in fixList"
                                @click="sentSelectedEventTitle(item)"
                                :class="{ 'list-item-selected': unique == item.unique }"
                                :key="index"
                                v-show="currentView == 'list'"
                            >
                                <ul>
                                    <li class="list-item-info">
                                        <p class="list-item-title">
                                            <span class="list-item-typeMark">{{ item.no }}</span>
                                            {{ item.name }}
                                        </p>
                                    </li>
                                </ul>
                            </li> -->
                        </TabPane>
                        <!-- 临时课程 -->
                        <TabPane :label="$t('studentWeb.tempClass')" name="tab2">
                        <!--剛加入的課程-->
                        <!-- <li
                            class="list-item"
                            @click="
                            sentSelectedEventTitle(
                                courseList[courseList.length - index - 2]
                            )
                            "
                            :class="{
                            'list-item-selected': selectedCondition(
                                courseList[courseList.length - index - 2]
                            ),
                            }"
                            v-for="(item,
                            index) in this.$store.getters.getMycID.myCourseID
                            .slice()
                            .reverse()"
                            :key="`c+${index}`"
                        >
                            <ul>
                            <li class="list-item-info">
                                <p class="list-item-title">
                                <span class="list-item-typeMark">{{ item }}</span>
                                {{ "新加課程名稱" }}
                                </p>
                            </li>
                            </ul>
                        </li> -->
                        <!--剛加入的課程-->
                            <div v-if="personList.length">
                                <!-- <div v-for="(item, index) in timeTable" :key="index"> -->
                                    <li
                                        class="list-item"
                                        v-for="(person, num) in personList"
                                        :class="{'list-item-selected': selectedCondition(person)}"
                                        @click="clickCell(person, num, 'list')"
                                        :key="`j+${num}`"
                                    >
                                        <ul>
                                            <li class="list-item-info">
                                                <p class="list-item-title">
                                                    <span class="list-item-typeMark">{{ person.no }}</span>
                                                    {{ person.name }}（{{ person.teaName }}）
                                                </p>
                                            </li>
                                        </ul>
                                    </li>
                                <!-- </div> -->
                            </div>
                            <div v-else class="list-item-no">
                                {{ $t('studentWeb.courseContent.noCourse') }}
                            </div>
                        </TabPane>
                    </Tabs>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/vue-loading.css";
import { mapGetters, mapState } from 'vuex';
export default {
    name: "CourseList",
    components: {
        Loading
    },
    data() {
        return {
            isLoad: false,
            fullPage: true,
            opacity: 0.6,
            currentView: 'table',
            onlyStu: true, //是不是学生
            courseTime: [
                {
                    title: this.$t("studentWeb.week.time"),
                    slot: "time",
                    width: "140"
                },
                {
                    title: this.$t("studentWeb.week.mon"),
                    slot: "Mon",
                    width: "115"
                },
                {
                    title: this.$t("studentWeb.week.tue"),
                    slot: "Tue",
                    width: "115"
                },
                {
                    title: this.$t("studentWeb.week.wed"),
                    slot: "Wed",
                    width: "115"
                },
                {
                    title: this.$t("studentWeb.week.thu"),
                    slot: "Thu",
                    width: "115"
                },
                {
                    title: this.$t("studentWeb.week.fri"),
                    slot: "Fri",
                    width: "115"
                },
                {
                    title: this.$t("studentWeb.week.sat"),
                    // slot: "Fri",
                    width: "100"
                },
                {
                    title: this.$t("studentWeb.week.sun"),
                    // slot: "Fri",
                    width: "100"
                }
            ],
            courseList: this.$api.studentWeb.courseList, //moke数据
            fixList: [], //表定课程
            personList: [], //临时课程
            nowClassInfor: {},
            timeTable: [], //页面所有的课程
            unique: '',
        };
    },
    props: {
        period: {
            type: Array,
            default: []
        },
        teaList: {
            type: Array,
            default: []
        }
    },
    created() {
        this.userInfo.roles.map(item => {
            if(item == "teacher") {
                this.onlyStu = false
            }
        })
        this.getClassList()
    },
    mounted () {
        this.selectedCondition(this.getItemTitle)
    },
    methods: {
        getClassList() {
            this.isLoad = true
            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) {
                    // 表定课程
                    var fixList = []
                    // 临时课程
                    var personList = []
                    var list = res.courses
                    list.forEach(item => {
                        if(item.course) {
                            item.course.schedule.forEach(sch => {
                                // 有classId，表定课程
                                if(sch.classId == item.stuCourse.classId[0]) {
                                    if(sch.time.length > 0) {
                                        for (let m = 0; m < sch.time.length; m++) {
                                            let data = this.getNewCourse("class", item, sch, m)
                                            fixList.push(data)
                                        }
                                    }
                                    else {
                                        let datanoTime = this.getNewCourse("class", item, sch)
                                        fixList.push(datanoTime)
                                    }
                                }
                                // 有stulist，临时课程
                                else if (sch.stulist) {
                                    if(sch.time.length) {
                                        for (let m = 0; m < sch.time.length; m++) {
                                            let data = this.getNewCourse("person", item, sch, m)
                                            personList.push(data)
                                        }
                                    }
                                    // 没有时间
                                    else {
                                        let data = this.getNewCourse("person", item, sch)
                                        personList.push(data)
                                    }
                                }
                            })
                        }
                    })
                    this.fixList = fixList
                    this.personList = personList
                    this.getClassTime()
                }
            }).finally(()=>{
                this.isLoad = false
            })
            
        },
        // 课程的相关信息(attribute: "class/person")
        getNewCourse(attribute, subject, schedule, m) {
            let data = this._.cloneDeep(subject.course)
            delete data.schedule
            data.school = subject.stuCourse.school
            data.scope = subject.stuCourse.scope
            data.classId = schedule.classId
            data.roomId = schedule.room
            data.teacherId = schedule.teacherId
            data.notice = schedule.notice
            data.stuList = schedule.stulist
            if(m !== undefined) {
                data.timeId = schedule.time[m].id
                data.timeWeek = schedule.time[m].week
                // 拼接得到一个唯一的标识
                data.unique = attribute + subject.course.no + schedule.time[m].week + schedule.time[m].id + m + Math.floor(Math.random() * 10000)
            }
            // 没有时间的情况
            else {
                data.timeId = 0
                data.timeWeek = 0
                data.unique = attribute + subject.course.no + Math.floor(Math.random() * 100000000)
            }
            data.teaName = this.$t('studentWeb.courseContent.noTeacher')
            // 获取老师名单
            if(this.teaList.length > 0) {
                this.teaList.forEach(item => {
                    if(item.id == data.teacherId) {
                        data.teaName = item.name
                    }
                })
            }
            return data
        },
        // 处理上课时间
        getClassTime() {
            // 学生登陆
            if(this.onlyStu) {
                this.timeTable = this.period.find(item => {
                    return item.id == this.studentProfile.classinfo.periodId
                }).timetable
                this.timeTable.forEach(item => {
                    let newfixlist = []
                    let notime = [] //没有时间的标准课程
                    this.fixList.forEach(fix => {
                        if(fix.timeId == item.id && fix.timeId) {
                            newfixlist.push(fix)
                        }
                        // 没有时间的标准课程
                        else if (!fix.timeId) {
                            notime.push(fix)
                        }
                    })
                    item.fixList = newfixlist
                    item.noTime = notime
                })
                // 个人课程
                this.personList.forEach(per => {
                    if(per.timeId) {
                        this.timeTable.forEach(item => {
                            if(per.timeId == item.id) {
                                per.time = item.time
                            }
                        })
                    }
                })
            }
            // 醍摩豆登陆
            else if (this.personList.length) {
                // 年级id 存在
                if(this.personList[0].period.id != undefined) {
                    this.timetable = this.period.find(item => {
                        return item.id == this.personList[0].period.id
                    }).timetable
                    this.timeTable.forEach(item => {
                        let newpersonList = []
                        this.personList.forEach(per => {
                            if(per.timeId == item.id && per.timeId) {
                                newpersonList.push(per)
                            } else if (!per.timeId) {
                                newpersonList.push(per)
                            }
                        })
                        item.personList = newpersonList
                    })
                }
                // 年级id 不存在
                else {
                    this.timeTable = [{
                        personList: []
                    }]
                    this.personList.forEach(per => {
                        this.timeTable[0].personList.push(per)
                    })
                }
            }
        },
        // 点击单节课，显示基本信息
        /* row：timeTable的某一个
           index：fixList/personList中的当前这一数据的下标
           type：传'list'就是临时课程，不传就是表定课程
        */
        clickCell(row, index, type) {
            this.nowClassInfor = this._.cloneDeep(row)
            if(type) {
                this.nowClassInfor.course = this._.cloneDeep(row)
            } else {
                this.nowClassInfor.course = this._.cloneDeep(row.fixList[index])
            }
            this.unique = this.nowClassInfor.course.unique
            this.sentSelectedEventTitle(this.nowClassInfor)
        },
        changeView(type) {
            this.currentView = type
        },
        selectedCondition(item) {
            if(Object.keys(this.getItemTitle).length) {
                if (this.getItemTitle.course.id == item.id
                    && this.getItemTitle.course.teacherId == item.teacherId
                    && this.getItemTitle.course.timeId == item.timeId
                    && this.getItemTitle.course.timeWeek == item.timeWeek
                    && this.getItemTitle.course.roomId == item.roomId
                ) {
                    console.log(11111);
                    return true;
                } else return false;
            }
        },
        // 跳转到当前课程
        sentSelectedEventTitle: function (item) {
            // 改變ItemName的狀態 vuex mutations
            this.$store.commit("ChangeItemName", item);
            // 螢幕寬度<767px時，直接關掉sidebar
            if (window.innerWidth <= 991) {
                this.$store.commit("ToggleSidebar", false);
            }
        },
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            studentProfile: state => state.user.studentProfile
        }),
        ...mapGetters(["getItemTitle"])
    }
};
</script>

<style scoped>
@import "~@/assets/student-web/component_styles/course-list.css";
</style>