<template>
    <div class="event-list">
        <div class="list">
            <!--活動搜尋與篩選區域-->
            <div class="event-selector-block">
                <!---搜尋--->
                <div class="search">
                    <div class="search-btn" @click="showSearch()">
                        <svg-icon icon-class="search"
                                  class="searchIcon"
                                  :class="{ openSearch: openSearch }" />
                    </div>
                    <div class="search-wrapper" :class="{ openSearch: openSearch }">
                        <Input type="text" v-model="search" :placeholder="$t('studentWeb.public.search')" clearable />
                    </div>
                </div>
                <!---搜尋--->
                <!--下拉選單-->
                <div>
                    <Dropdown>
                        <a href="javascript:void(0)" class="list-title">
                            <span >{{ selectedEventStatusNow }}</span>
                            <Icon type="ios-arrow-down"></Icon>
                        </a>
                        <DropdownMenu slot="list">
                            <div @click="sentEventStatus('all')">
                                <DropdownItem>{{ $t("studentWeb.event.allStatus") }}</DropdownItem>
                            </div>
                            <div @click="sentEventStatus('unFinsish')">
                                <DropdownItem>{{ $t("studentWeb.event.unFinished") }}</DropdownItem>
                            </div>
                            <div @click="sentEventStatus('finish')">
                                <DropdownItem>{{ $t("studentWeb.event.Fineshed") }}</DropdownItem>
                            </div>
                            <div @click="sentEventStatus('overTime')">
                                <DropdownItem>{{ $t("studentWeb.event.Timeout") }}</DropdownItem>
                            </div>
                            <div @click="sentEventStatus('reExam')">
                                <DropdownItem divided>{{ $t("studentWeb.event.makeupExam") }}</DropdownItem>
                            </div>
                            <div @click="sentEventStatus('reMake')">
                                <DropdownItem>{{ $t("studentWeb.event.makeupHw") }}</DropdownItem>
                            </div>
                        </DropdownMenu>
                    </Dropdown>
                </div>
                <!---->
                <!---按鈕搜尋區(多選)--->
                <ul class="icon-selector" v-if="hideIconbtn == false">
                    <li class="icon-btn"
                        @click="selectAllType()"
                        :class="{'icon-btn-selected': eventTypeCheckers == ''}">
                        <svg-icon icon-class="alltext" class="innerIcon Icon-0" />
                    </li>
                    <label v-for="(iconBtn, index) in typeNametoIcon" :key="index">
                        <input type="checkbox"
                               :value="iconBtn.eventType"
                               v-model="eventTypeCheckers"
                               @change="predealMockdatafirstItem()" />
                        <li class="icon-btn">
                            <svg-icon :icon-class="iconBtn.iconClass"
                                      class="innerIcon"
                                      :class="`Icon-${index + 1}`" />
                        </li>
                    </label>
                </ul>
                <!---按鈕搜尋區(多選)--->
            </div>
            <!--活動搜尋與篩選區域-->
            <!--活動清單分頁-->
            <div class="list-block"
                :style="{ height: hideIconbtn == false ? '84vh' : '90vh' }">
                <div v-show="isListNoItem == true" class="emptycondition">
                    <svg-icon icon-class="empty-white-box" class="empty-Icon" />
                    <br />
                    {{ $t("studentWeb.empty") }}
                </div>
                <div :id="`event${item.eventID}`"
                    class="list-item"
                    @click="sentSelectedEventTitle(item)"
                    :class="{ 'list-item-selected': selectedCondition(item) }"
                    v-for="(item, index) in eventList"
                    v-if="isListNoItem == false"
                    :key="index">
                    <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="multiTest" />
                            <svg-icon v-if="item.eventType == 'vote'" icon-class="vote" />
                            <svg-icon v-if="item.eventType == 'que'"
                                      icon-class="quesnaire" />
                        </li>
                        <li class="list-item-info"
                            v-if="item.eventType == 'exam'">
                            <p class="list-item-title">
                                <span class="list-item-typeMark">{{item.scope == 'school' ? $t('studentWeb.public.schoolExam'):$t('studentWeb.public.privateExam')}}</span>
                                <span class="list-item-typeMark"
                                      v-if="getCurrentLang() == 'en'">{{ transTypetoEn(item.eventType) }}</span>
                                <span>{{ item.name }}</span>
                            </p>
                            <p class="list-item-time">
                                {{ dateFormat(item.startTime) }} ~ {{ dateFormat(item.endTime) }}
                            </p>
                        </li>
                            <!--<div>已交卷</div>-->
                        <li class="list-item-unDone" v-show="item.progress == 'going'">
                            <div class="isAllowRetry">{{$t("studentWeb.public.going")}}</div>
                        </li>
                        <li class="list-item-unDone" v-show="item.progress == 'finish'">
                            <div class="isOvertime">{{$t("studentWeb.public.finish")}}</div>
                        </li>
                    </ul>
                </div>
                <div class="list-end"></div>
            </div>
        </div>
        <!--活動清單分頁-->
        {{ scrollListfromInfoPop() }}
    </div>
</template>

<script>
    import { Random } from "mockjs";
    import PreviewProgressPie from "../EventView/PreviewProgressPie";


    export default {
        name: "EventList",
        mounted() {
            this.getPaper()
            this.selectedCondition(this.$store.getters.getItemTitle);
            if (this.$store.getters.getIsSelectedNow == false) {
                this.predealMockdatafirstItem();
            }
            this.scrollList();
        },

        data() {
            return {
                searchEmpty: false,
                eventTypeCheckers: [],
                finishedListNoItem: false, //無數據之情況
                unfinishedListNoItem: false,
                havejustfinishedItem: false, //無剛完成的數據情況，清單項目變動將會影響空白狀態之呈現
                typeNametoIcon: [
                    {
                        eventType: "preview",
                        iconClass: "selflearninginTime",
                    },
                    {
                        eventType: "exam",
                        iconClass: "test",
                    },
                    {
                        eventType: "homeWork",
                        iconClass: "doc",
                    },
                    {
                        eventType: "vote",
                        iconClass: "vote",
                    },
                    {
                        eventType: "que",
                        iconClass: "quesnaire",
                    },
                ],

                mockdata: "",
                eventPageType: ["preview", "exam", "homeWork", "vote", "que"], //本頁出現的類型
                openSearch: false, //打開搜尋器
                search: "",
                alreadyScrolltimes: 0,
                defaultFirstItem: "",
                selectedEventStatusNow: this.$t('studentWeb.event.allStatus'),
                hideIconbtn: false,
                isListNoItem: false, //清單為空
                eventList: []
            };
        },

        components: { PreviewProgressPie },
        watch: {
            search: function (value) {
                let countfit = 0;
                for (let i = 0; i < this.eventList.length; i++) {
                    if (
                        this.eventPageType.includes(this.eventList[i].eventType) &&
                        this.eventList[i].eventType.includes(value) &&
                        value != ""
                    ) {
                        if (
                            this.eventTypeCheckers != "" &&
                            this.eventTypeCheckers.includes(this.eventList[i].eventType) == false
                        ) {
                            countfit += 0;
                        } else {
                            countfit++;
                        }
                    } else if (
                        this.eventList[i].name.includes(value) == false &&
                        value != ""
                    ) {
                        countfit += 0;
                    }

                }
                if (countfit == 0 && value != "") {
                    this.isListNoItem = true;
                } else this.isListNoItem = false;
            },
        },
        methods: {
            getPaper() {
                this.eventList.length = 0
                this.isListNoItem = true;
                if (this.$store.state.user.studentProfile.classinfo.id !== "") {
                    let params = {
                        'id': this.$store.state.user.studentProfile.classinfo.id,
                        'studentId': this.$store.state.userInfo.sub
                    }
                    this.eventList = []
                    this.$api.studentWeb.FindExamPaper(params).then(res => {
                        let data = []
                        for (let item of res.props) {
                            let code = item.code.split('-')
                            if (code[0] == 'Exam') {
                                item.eventType = 'exam'
                                data.push(item)
                            }
                        }
                        this.eventList = data.sort(function (a, b) {
                            return b.startTime - a.startTime //时间正序
                        });
                        this.isListNoItem = false
                    })
                }
            },
            dateFormat(timestamp) {
                var date = new Date(timestamp)
                var Y = date.getFullYear() + '-'
                var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
                var D = date.getDate() + ' '
                return Y + M + D;
            },
            retryCondition(item) {
                return (
                    item.endTime <= "2020.02.10" &&
                    item.allowRetryNow == true &&
                    item.isDone == false
                );
            },
            getCurrentLang() {
                return localStorage.getItem("lang");
            },
            transTypetoEn(type) {
                if (type == "vote") return "Vote";
                else if (type == "exam") return "Exam";
                else if (type == "homework") return "Homework";
                else if (type == "preview") return "Preview";
            },
            //取得目前滑鼠座標
            getCursorPosition() {
                var x = 0;
                var y = 0;
                if (!e) var e = window.event;
                if (e.pageX || e.pageY) {
                    x =
                        e.pageX -
                        document.documentElement.scrollLeft -
                        document.body.scrollLeft;
                    y =
                        e.pageY -
                        document.documentElement.scrollTop -
                        document.body.scrollTop;
                } else if (e.clientX || e.clientY) {
                    //for IE
                    x = e.clientX;
                    y = e.clientY;
                }

                return { x: x, y: y }; //posx posy就是游標的X,Y值了
            },
            //取得座標
            getPosition(element) {
                var x = 0;
                var y = 0;

                while (element) {
                    x += element.offsetLeft - element.scrollLeft + element.clientLeft;
                    y += element.offsetTop - element.scrollLeft + element.clientTop;
                    element = element.offsetParent;
                }

                return { x: x, y: y };
            },

            //將目前所滑過的投票項目之高度回傳到$store
            sentVoteResulthover(status) {
                var hoverItem = {
                    status: status,
                    itemIDHeignt: this.getCursorPosition().y,
                };

                this.$store.commit("voteResulthover", hoverItem);
            },
            randomScore: function () {
                return Random.integer(70, 96);
            },
            sentEventStatus(status) {
                if (status == "reMake" || status == "reExam") {
                    this.eventTypeCheckers = [];
                }
                this.selectedEventStatusNow = status;
                this.predealMockdatafirstItem();
            },
            predealMockdatafirstItem() {
                //選中第一個
                let currentfilterArray = [];
                for (let i = 0; i < this.eventList.length; i++) {
                    //沒有篩選類型+沒有篩選狀態的情況
                    if (this.eventPageType.includes(this.eventList[i].eventType)) {
                        if (
                            this.eventTypeCheckers == ""
                            //&&
                            //this.selectedEventStatusNow == "所有活動狀態"
                        ) {
                            currentfilterArray.push(this.eventList[i]);
                        }
                        //沒篩選類型+有篩選狀態的情況
                        else if (
                            this.eventTypeCheckers == "" &&
                            this.dropDownShowCondition(
                                this.selectedEventStatusNow,
                                this.eventList[i]
                            )
                        ) {
                            currentfilterArray.push(this.eventList[i]);
                        }
                        //有篩選類型+有篩選狀態的情況
                        else if (
                            this.eventTypeCheckers != "" &&
                            this.eventTypeCheckers.includes(this.eventList[i].eventType) &&
                            this.dropDownShowCondition(
                                this.selectedEventStatusNow,
                                this.eventList[i]
                            )
                        ) {
                            currentfilterArray.push(this.eventList[i]);
                        }
                    }
                }
                if (currentfilterArray != "") {

                    this.isListNoItem = false;
                    this.sentSelectedEventTitle(currentfilterArray[0]);
                    document.querySelectorAll(".event-list .list-block")[0].scrollBy({
                        top: -document.querySelectorAll(".event-list .list-block")[0]
                            .scrollHeight,
                        behavior: "smooth",
                    });
                } else this.isListNoItem = true; //清單空值樣式配置
            },
            dropDownShowCondition(status, item) {
                if (status == "reMake") {
                    this.hideIconbtn = true;

                    return (
                        item.endTime <= "2020.02.10" &&
                        item.eventType == "homework" &&
                        item.allowRetryNow == true &&
                        item.isDone == false
                    );
                } else if (status == "reExam") {
                    this.hideIconbtn = true;

                    return (
                        item.endTime <= "2020.02.10" &&
                        item.eventType == "exam" &&
                        item.allowRetryNow == true &&
                        item.isDone == false
                    );
                } else if (status == "unFinish") {
                    this.hideIconbtn = false;
                    return item.isDone == false;
                } else if (status == "finish") {
                    this.hideIconbtn = false;
                    return item.isDone == true;
                } else if (status == "overTime") {
                    this.hideIconbtn = false;
                    return (
                        (item.isDone == false &&
                            item.endTime <= "2020.02.10" &&
                            item.allowRetryNow == false) ||
                        (item.isDone == false &&
                            item.endTime <= "2020.02.10" &&
                            item.eventType == "vote") ||
                        (item.isDone == false &&
                            item.endTime <= "2020.02.10" &&
                            item.eventType == "preview")
                    );
                } else {
                    this.hideIconbtn = false;
                    return true;
                }
            },
            selectAllType() {
                this.eventTypeCheckers = [];
                this.predealMockdatafirstItem();
            },
            showSearch() {
                this.openSearch = !this.openSearch;
            },
            sentEvenType(eventype) {
                this.$store.commit("ChangeFilterType", eventype);
                if (this.$store.getters.getFilterType == "all") {
                    let filterListFinished = [],
                        filterListUnFinished = [];
                    for (let i = 0; i < this.mockdata.length; i++) {
                        if (
                            this.mockdata[i].isDone == true &&
                            this.eventPageType.includes(this.mockdata[i].eventType)
                        ) {
                            filterListFinished.push(this.mockdata[i]);
                        }
                    }
                    for (let j = 0; j < this.mockdata.length; j++) {
                        if (
                            this.mockdata[j].isDone == false &&
                            this.eventPageType.includes(this.mockdata[j].eventType)
                        ) {
                            filterListUnFinished.push(this.mockdata[j]);
                        }
                    }
                    this.defaultFirstItem = filterListUnFinished[0];
                    if (
                        this.$store.getters.getIsSelectedNow == false &&
                        this.defaultFirstItem != ""
                    ) {
                        this.sentSelectedEventTitle(this.defaultFirstItem);
                    }
                    this.finishedListNoItem = false;
                    this.unfinishedListNoItem = false;
                }
            },
            eventypeSelected: function (type) {
                if (this.$store.getters.getFilterType == type) return true;
                else return false;
            },

            sentSelectedEventTitle(item) {
                this.$router.push({
                    path: "/studentWeb/eventView",
                    query: {
                        id: item.id,
                        type: item.eventType
                    }
                })
                this.$store.commit("SetPaperInfo", item)
                //螢幕寬度<767px時，直接關掉sidebar
                if (window.innerWidth <= 768) {
                    this.$store.commit("ToggleSidebar", false);
                }
                //改變ItemName的狀態 vuex mutations
                this.$store.commit("ChangeItemName", item);
                //重置問卷
                this.$store.commit('resetSurvey', true)
                //重置預習活動
                this.$store.commit("PassPhaseTest", 0);
                this.$store.commit("ChangeCurrentPhase", 0);
                this.$store.commit("ChangeCurrentSelectedReadingName", 1);
                this.$store.commit("ToggleSentCurrentphase", false);
                this.$store.commit("SetCurrentQuestionNo", 0);
                this.$store.commit("SetTrytestCount", [0, 0, 0]);
            },

            scrollListfromInfoPop() {
                if (this.$store.getters.getisFromInfoPoptoScroll == true) {
                    //當從通知操作進行捲動時，將篩選條件清空
                    this.selectedEventStatusNow = this.$t('studentWeb.event.allStatus');
                    this.eventTypeCheckers = [];
                    let targetItem = document.getElementById(
                        `event${this.$store.getters.getItemTitle.eventID}`
                    );
                    let scrollList = document.querySelectorAll(
                        ".event-list .list-block"
                    )[0];

                    if (scrollList !== undefined) {
                        let scrollvalue = 0;
                        if (targetItem.offsetTop > 600) {
                            scrollvalue = targetItem.offsetTop - 128;
                        } else if (targetItem.offsetTop < 600) {
                            scrollvalue = -scrollList.scrollHeight;
                        }
                        scrollList.scrollTo({
                            top: scrollvalue,
                            behavior: "smooth",
                        });
                    }
                }
                this.$store.commit("SetisFromInfoPoptpScroll", false);
            },

            scrollList() {
                //let targetItem = document.getElementById(
                //    `event${this.$store.getters.getItemTitle.eventID}`
                //);
                //if (targetItem.style.display == "none") {
                //    targetItem.style.display = "block";
                //}
                //console.log(
                //    this.$store.getters.getScrollvalue,
                //    document.getElementById(
                //        `event${this.$store.getters.getItemTitle.eventID}`
                //    ).offsetTop
                //);
                //document.querySelectorAll(".event-list .list-block")[0].scrollBy({
                //    //畫面中有多個tabpane，指定為event-list中的進行捲動
                //    top: targetItem.offsetTop > 600 ? targetItem.offsetTop - 128 : 0,
                //    behavior: "smooth",
                //});
            },

            selectedCondition(item) {
                if (
                    this.$store.getters.getIsSelectedNow == true &&
                    this.$store.getters.getItemTitle.name == item.name
                ) {
                    return true;
                } else return false;
            },
            showTheCurrentTab() {
                if (
                    (this.finishedListNoItem == false &&
                        this.$store.getters.getItemTitle.isDone == true) ||
                    this.$store.getters.getFinishedItem.includes(
                        this.$store.getters.getItemTitle.eventID
                    )
                )
                    return "tab2";
                else return "tab1";
            },
            finishedcondition(item) {
                if (this.$store.getters.getFinishedItem.includes(item.eventID) == true) {
                    this.havejustfinishedItem = true;
                    return true;
                } else return false;
            },
            finishedItemtime(item) {
                if (this.$store.getters.getFinishedItem.includes(item.eventID) == true) {
                    let timeIndex = this.$store.getters.getFinishedItem.indexOf(
                        item.eventID
                    );
                    return this.$store.getters.getFinishedItemTime[timeIndex];
                }
            },
        },
    };
</script>

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