<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="$t('studentWeb.type.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.title"
                               :class="{'icon-btn-selected': eventTypeCheckers.indexOf(iconBtn.eventType) != -1}"
                               :style="{'display': iconBtn.eventType == 'Preview' || iconBtn.eventType == 'HomeWork' ? 'none' : ''}"
                        >
                            <svg-icon :icon-class="iconBtn.iconClass"
                                      class="innerIcon"
                                      :class="`Icon-${index + 1}`" 
                            />
                            <div class="dev-top" v-if="iconBtn.eventType == 'Preview' || iconBtn.eventType == 'HomeWork'">
                                <span class="develop">{{ $t("studentWeb.public.develop") }}</span>
                            </div>
                        </Radio>
                    </RadioGroup>
                </div>
                <!---按鈕搜尋區(多選)--->
            </div>
            <!--活動清單分頁-->
            <div class="list-block"
                :style="{ height: !hideIconbtn ? '84vh' : '90vh' }">
                <!-- 空 -->
                <div v-show="isListNoItem" class="emptycondition">
                    <svg-icon icon-class="empty-white-box" class="empty-Icon" />
                    <br />
                    {{ $t("studentWeb.empty") }}
                </div>
                <vuescroll>
                    <div v-if="!isListNoItem" style="margin-bottom: 50px">
                        <div :id="`event${item.id}`"
                            class="list-new"
                            @click="sentSelectedEventTitle(item)"
                            :class="{ 'list-item-selected': selectedCondition(item) }"
                            v-for="(item, index) in eventShow"
                            :key="index"
                        >
                            <div class="list-new-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" />
                            </div>
                            <div v-if="item.eventType == 'Exam'" class="list-new-test">
                                <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 isScore" v-show="timeStatus(item) == 'finish'">
                                    得分率：20%
                                </p> -->
                                <p class="list-item-time">
                                    {{ dateFormat(item.startTime) }} ~ {{ dateFormat(item.endTime) }}
                                </p>
                            </div>
                            <div v-if="item.eventType == 'Vote'" class="list-new-test">
                                <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>
                            </div>
                            <div v-if="item.eventType == 'Survey'" class="list-new-test">
                                <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>
                            </div>
                            <div class="list-new-type">
                                <div class="list-new-unDone isAllowRetry" v-show="timeStatus(item) == 'going'">
                                    <span>{{$t("studentWeb.public.going")}}</span>
                                </div>
                                <div class="list-new-unDone" v-show="timeStatus(item) == 'finish'">
                                    <span class="isOvertime">{{$t("studentWeb.public.finish")}}</span>
                                </div>
                                <!-- 暂时不改 -->
                                <!-- <div class="list-new-unDone isWrongPra" v-show="timeStatus(item) == 'finish' && item.eventType == 'Exam'">
                                    <span class="">{{$t("studentWeb.exam.report.wrongPractice")}}</span>
                                </div> -->
                            </div>
                                
                        </div>
                    </div>
                </vuescroll>
                <div class="list-end"></div>
            </div>
        </div>
        {{ scrollListfromInfoPop() }}
    </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex';
    import PreviewProgressPie from "../EventView/PreviewProgressPie";
    export default {
        name: "EventList",
        mounted() {
            this.$EventBus.$off('delNotFound')
            this.$EventBus.$on('delNotFound', id => {
                console.log(id);
                this.delListData(id)
            })
            this.getActivityInfo()
            this.selectedCondition(this.getItemTitle);
            if (this.getIsSelectedNow == false) {
                this.predealMockdatafirstItem();
            }
            this.scrollList();
        },
        data() {
            return {
                searchEmpty: false,
                eventTypeCheckers: "", //筛选的
                typeNametoIcon: [
                    {
                        eventType: "Preview",
                        title: this.$t('studentWeb.type.preview'),
                        iconClass: "selflearninginTime",
                    },
                    {
                        eventType: "Exam",
                        title: this.$t('studentWeb.type.exam'),
                        iconClass: "test",
                    },
                    {
                        eventType: "HomeWork",
                        title: this.$t('studentWeb.type.homework'),
                        iconClass: "doc",
                    },
                    {
                        eventType: "Vote",
                        title: this.$t('studentWeb.type.vote'),
                        iconClass: "vote",
                    },
                    {
                        eventType: "Survey",
                        title: this.$t('studentWeb.type.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) {
                this.predealMockdatafirstItem()
                let list = this.eventShow.filter(item => item.name.indexOf(value) >= 0)
                if (!list.length) {
                    this.isListNoItem = true;
                }
                this.eventShow = list
                /* 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; */
            },
        },
        computed: {
            ...mapState({
                studentProfile: state => state.user.studentProfile,
                schoolCode: state => state.user.schoolCode,
                userInfo: state => state.userInfo,
            }),
            ...mapGetters([
                "getItemTitle",
                "getIsSelectedNow",
                "getisFromInfoPoptoScroll",
                "getFilterType",
                "getFinishedItem",
                "getFinishedItemTime"
            ])
        },
        methods: {
            //获取活动信息数据
            getActivityInfo() {
                this.eventList.length = 0
                this.isListNoItem = true;

                let params = {}
                // 醍摩豆登陆——> roles有teacher
                if (this.$store.state.userInfo.roles.includes("teacher")) {
                    params = {
                        userid: this.userInfo.sub,
                        userType: "tmdid",
                        school: this.schoolCode
                    }
                }
                // 学生账号登陆
                else {
                    params = {
                        userid: this.userInfo.sub,
                        userType: "schoolid",
                        school: this.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() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '
                var H = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ":"
                var Min = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
                var S = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()) + " "
                return Y + M + D + H + Min;
            },
            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
                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.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 == "进行中") {
                    return (
                        item.progress == "going"
                    );
                    this.hideIconbtn = false;
                    return item.isDone == false;
                } else if (status == "已完成") {
                    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);
                localStorage.setItem("Item", JSON.stringify(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.getisFromInfoPoptoScroll == true) {
                    //當從通知操作進行捲動時，將篩選條件清空
                    this.selectedEventStatusNow = this.$t('studentWeb.event.allStatus');
                    this.eventTypeCheckers = "";
                    let targetItem = document.getElementById(
                        `event${this.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.getIsSelectedNow == true &&
                    this.getItemTitle.id == item.id
                ) {
                    return true;
                } else return false;
            },
            // 删除页面上不不存在的数据
            delListData(id) {
                if(this.eventList) {
                    for(let i = 0; i < this.eventList.length; i++) {
                        if(this.eventList[i].id == id) {
                            this.eventList.splice(i, 1)
                            break
                        }
                    }
                    this.predealMockdatafirstItem()
                }
            },

            /* =======未调用======== */
            //取得目前滑鼠座標
            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.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.getIsSelectedNow == false &&
                        this.defaultFirstItem != ""
                    ) {
                        this.sentSelectedEventTitle(this.defaultFirstItem);
                    }
                    this.finishedListNoItem = false;
                    this.unfinishedListNoItem = false;
                }
            },
            eventypeSelected: function (type) {
                if (this.getFilterType == type) return true;
                else return false;
            },
            scrollList() {
            },
            showTheCurrentTab() {
                if (
                    (this.finishedListNoItem == false && this.getItemTitle.isDone == true)
                    || this.getFinishedItem.includes(this.getItemTitle.eventID)
                )
                    return "tab2";
                else return "tab1";
            },
            finishedcondition(item) {
                if (this.getFinishedItem.includes(item.eventID) == true) {
                    this.havejustfinishedItem = true;
                    return true;
                } else return false;
            },
            finishedItemtime(item) {
                if (this.getFinishedItem.includes(item.eventID) == true) {
                    let timeIndex = this.getFinishedItem.indexOf(
                        item.eventID
                    );
                    return this.getFinishedItemTime[timeIndex];
                }
            },
        },
    };
</script>

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

<style lang="less" scoped>
.icon-selector{
    .ivu-radio-wrapper{
        overflow: hidden;
    }
}
.dev-top{
    .develop{
        position: absolute;
        top: 1px;
        right: -13px;
        font-size: xx-small;
        color: #fff;
        padding: 2px 5px;
        z-index: 99;
        transform: scale(0.7) rotate(45deg);
    }

    &::after{
        position: absolute;
        content: " ";
        right: 0px;
        top: -4px;
        z-index: 0;
        width: 33px;
        height: 20px;
        background-color: #64AE16;
        transform: skewY(45deg);
    }
}
</style>
