<template>
    <div class="event-list">
        <div class="list">
            <!--活動搜尋與篩選區域-->
            <div class="event-selector-block">
                <div class="search">
                    <div class="search-btn" @click="openSearch = !openSearch">
                        <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(item)" v-for="(item,index) in $t('studentWeb.state')" :key="index">
                                <DropdownItem>{{ item.status }}</DropdownItem>
                            </div>
                        </DropdownMenu>
                    </Dropdown>
                </div>
                <!---按鈕搜尋區(多選)--->
                <div class="icon-selector" v-if="hideIconbtn == false">
                    <RadioGroup v-model="eventTypeCheckers"
                                class="icon-selector-group"
                                @on-change="predealMockdatafirstItem()"
                    >
                        <div class="icon-btn"
                             @click="selectAllType()"
                             title="All"
                             :class="{'icon-btn-selected': eventTypeCheckers == ''}">
                            <svg-icon icon-class="alltext" class="innerIcon Icon-0" />
                        </div>
                        <Radio :label="iconBtn.eventType"
                               v-for="(iconBtn, index) in typeNametoIcon"
                               :key="index"
                               class="icon-btn"
                               :title="iconBtn.eventType"
                               :class="{'icon-btn-selected': eventTypeCheckers.indexOf(iconBtn.eventType) != -1}"
                        >
                            <svg-icon :icon-class="iconBtn.iconClass"
                                      :title="iconBtn.eventType"
                                      class="innerIcon"
                                      :class="`Icon-${index + 1}`" />
                        </Radio>
                    </RadioGroup>
                </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.id}`"
                     class="list-item"
                     @click="sentSelectedEventTitle(item)"
                     :class="{ 'list-item-selected': selectedCondition(item) }"
                     v-for="(item, index) in eventShow"
                     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 == 'Survey'" 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.owner == 'school' ? $t('studentWeb.public.schoolExam'):$t('studentWeb.public.privateExam')}}</span>
                                <span>{{ item.name }}</span>
                            </p>
                            <p class="list-item-time">
                                {{ dateFormat(item.startTime) }} ~ {{ dateFormat(item.endTime) }}
                            </p>
                            <!-- <p class="list-item-time" v-show="timeStatus(item) == 'finish'">
                                得分率：20%
                            </p> -->
                        </li>
                        <li class="list-item-info"
                            v-if="item.eventType == 'Vote'">
                            <p class="list-item-title">
                                <span class="list-item-typeMark">{{item.owner == 'school' ? $t('studentWeb.public.schoolVote'):$t('studentWeb.public.privateVote')}}</span>
                                <span>{{ item.name }}</span>
                            </p>
                            <p class="list-item-time">
                                {{ dateFormat(item.startTime) }} ~ {{ dateFormat(item.endTime) }}
                            </p>
                        </li>
                        <li class="list-item-info"
                            v-if="item.eventType == 'Survey'">
                            <p class="list-item-title">
                                <span 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">
                                {{ dateFormat(item.startTime) }} ~ {{ dateFormat(item.endTime) }}
                            </p>
                        </li>
                        <li class="list-item-unDone" v-show="timeStatus(item) == 'going'">
                            <div class="isAllowRetry">{{$t("studentWeb.public.going")}}</div>
                        </li>
                        <li class="list-item-unDone" v-show="timeStatus(item) == 'finish'">
                            <div class="isOvertime">{{$t("studentWeb.public.finish")}}</div>
                        </li>
                        <!-- <li class="list-item-unDone" v-show="timeStatus(item) == 'finish' && item.eventType == 'Exam'">
                            <div class="">{{$t("studentWeb.exam.report.wrongPractice")}}</div>
                        </li> -->
                    </ul>
                </div>
                <div class="list-end"></div>
            </div>
        </div>
        {{ scrollListfromInfoPop() }}
    </div>
</template>

<script>
    import PreviewProgressPie from "../EventView/PreviewProgressPie";
    export default {
        name: "EventList",
        mounted() { 
            this.getActivityInfo()
            this.selectedCondition(this.$store.getters.getItemTitle);
            if (this.$store.getters.getIsSelectedNow == false) {
                this.predealMockdatafirstItem();
            }
            this.scrollList();
        },
        data() {
            return {
                searchEmpty: false,
                eventTypeCheckers: "", //筛选的
                typeNametoIcon: [
                    {
                        eventType: "Preview",
                        title: "Preview",
                        iconClass: "selflearninginTime",
                    },
                    {
                        eventType: "Exam",
                        iconClass: "test",
                    },
                    {
                        eventType: "HomeWork",
                        iconClass: "doc",
                    },
                    {
                        eventType: "Vote",
                        iconClass: "vote",
                    },
                    {
                        eventType: "Survey",
                        iconClass: "quesnaire",
                    },
                ],
                isListNoItem: false, //清單為空
                eventList: [], //活动数据
                eventShow: [], //展示的活动数据
                eventPageType: ["Learn", "Exam", "HomeWork", "Vote", "Survey"], //本頁出現的類型
                selectedEventStatusNow: this.$t('studentWeb.event.allStatus'), //下拉框活动状态
                openSearch: false, //打開搜尋器
                search: "",
                hideIconbtn: false,

                activityType: this.$t('studentWeb.state'),
                havejustfinishedItem: false, //無剛完成的數據情況，清單項目變動將會影響空白狀態之呈現
                finishedListNoItem: false, //無數據之情況
                unfinishedListNoItem: false,
                alreadyScrolltimes: 0,
                mockdata: "",
                defaultFirstItem: "",
                dateTime: Date.parse(new Date())
            };
        },
        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: {
            //获取活动信息数据
            getActivityInfo() {
                this.eventList.length = 0
                this.isListNoItem = true;
                if (this.$store.state.user.studentProfile.classinfo.id !== "") {
                    let classInfo = [this.$store.state.user.studentProfile.classinfo.id]
                    if (this.$store.state.user.studentProfile.courses.length) {
                        for (let item of this.$store.state.user.studentProfile.courses) {
                            classInfo.push(item.id)
                        }
                    }
                    let params = {
                        userid: this.$store.state.userInfo.sub,
                        userType: "schoolid",
                        school: this.$store.state.user.schoolCode
                    }
                    this.$api.studentWeb.getActivityInfo(params).then(res => {
                        if (res) {
                            let data = []
                            for (let item of res.datas) {
                                item.eventType = item.type
                                item.progress = this.timeStatus(item)
                                data.push(item)
                            }
                            this.eventList = [...data]
                            this.eventList = this.eventList.sort(function (a, b) {
                                return b.startTime - a.startTime //时间正序
                            });
                            this.eventShow = [...this.eventList]
                            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;
            },
            timeStatus(data) {
                let date = (new Date()).getTime() //当前时间
                if (date >= data.endTime) {
                    return 'finish'
                } else {
                    return 'going'
                }
            },
            sentEventStatus(status) {
                if (status == "reMake" || status == "reExam") {
                    this.eventTypeCheckers = "";
                }
                this.selectedEventStatusNow = status.status;
                this.predealMockdatafirstItem();
            },
            // 状态 + 类型筛选
            predealMockdatafirstItem() {
                //選中第一個
                let currentfilterArray = [];
                this.eventShow.length = 0
                console.log(this.eventTypeCheckers);
                for (let i = 0; i < this.eventList.length; i++) {
                    if (this.eventPageType.includes(this.eventList[i].eventType)) {
                        // 沒有篩選類型+沒有篩選狀態的情況
                        if (this.eventTypeCheckers == "") {
                            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.length !== 0) {
                    this.eventShow = [...currentfilterArray]
                    this.isListNoItem = false;
                    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") {
                    return (
                        item.progress == "going"
                    );
                    this.hideIconbtn = false;
                    return item.isDone == false;
                } else if (status == "finish") {
                    return (
                        item.progress == "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();
            },
            // 展示活动
            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);
            },
            selectedCondition(item) {
                if (
                    this.$store.getters.getIsSelectedNow == true &&
                    this.$store.getters.getItemTitle.id == item.id
                ) {
                    return true;
                } else return false;
            },

            /* =======未调用======== */
            //取得目前滑鼠座標
            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);
            },
            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;
            },
            scrollList() {
            },
            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>
