<template>
    <div class="vote">
        <div v-if="WarmMessageisOpen" class="warmMessage ">
            <div class="messageCard animate__animated animate__fadeInDown ">
                <h2>{{ $t("studentWeb.vote.voteSuccess") }}</h2>
                <svg-icon icon-class="votefinished" class="votefinished-icon" />
                <p>{{ $t("studentWeb.vote.voteDes") }}</p>
            </div>
        </div>
        <EventBasicInfo :info="nowActive" :times="voteTimes" />
        <div>
            <!-- <div> -->
                <!--超时-->
                <div v-show="!isVote && !isVoteOK">
                    <br />
                    <div class="dec animate__animated animate__bounceInLeft">
                        <svg-icon icon-class="handonHint" class="warm-icon" />
                        <span class="warm-hint">{{ $t("studentWeb.vote.timeoutHint") }}</span>
                    </div>
                </div>
                <!-- <div class="load-box">
                    <Load :active.sync="isLoad"
                        background-color="#000">
                        <template slot="default">
                            <svg-icon icon-class="loader" class="loader-icon" />
                        </template>
                    </Load>
                </div> -->
                <Loading v-show="isLoad" bgColor="rgba(0, 0, 0, 0.3)"></Loading>
                <BillBoardandLightBox :activityData="voteInfo" :voteRes="voteResData" />
                <!-- 投票结果 -->
                <div class="voteResults" v-if="showResult">
                    <div class="vote-title">
                        <div class="title-rect-group">
                            <h2 class="title-rect-name">{{ $t("studentWeb.vote.voteResult") }}</h2>
                        </div>
                    </div>
                    <div align="center">
                        <VoteResultChart :voteData="voteData" :voteList="voteList" />
                    </div>
                </div>
                <div class="vote-title">
                    <div class="title-rect-group">
                        <h2 class="title-rect-name">{{ $t("studentWeb.vote.bollotbox") }}</h2>
                        <p v-if="!isVoteOK && (voteInfo.times != 'once' || voteInfo.repeat)" style="margin-left:15px;margin-top:2px">
                            {{ $t("studentWeb.vote.surplusTickets")}}
                            <span style="font-size:16px">{{ voteCount }}</span>
                            <span> {{ $t("studentWeb.vote.tickets")}} </span>
                        </p>
                    </div>
                </div>
                <div class="vote-option">
                    <!-- 只投一次 -->
                    <CheckboxGroup v-model="voteChecked" v-if="voteInfo.times == 'once' && !voteInfo.repeat" class="option-group" @on-change="controlNum">
                        <Checkbox border
                            :label="item.code"
                            v-for="(item, index) in voteInfo.options"
                            :key="index"
                            class="option-wrapper"
                            :disabled="!isVote"
                        >
                            {{ item.code }}、<span v-html="item.value" @click="showImg($event)"></span>
                        </Checkbox>
                    </CheckboxGroup>
                    <!-- 重复投票 -->
                    <div v-else>
                        <div v-for="(item, index) in voteInfo.options"
                            :key="index"
                            :class="['option-repeat', {'action-rep': item.count}]"
                        >
                            {{ item.code }}、
                            <InputNumber v-model="item.count"
                                        controls-outside
                                        :min="0"
                                        :max="!voteInfo.repeat ? 1 : Infinity"
                                        :formatter="value => `${value}` +$t('studentWeb.vote.tickets')"
                                        :disabled="!isVote || isVoteOK"
                            ></InputNumber>
                            <span v-html="item.value" @click="showImg($event)"></span>
                        </div>
                    </div>
                </div>
                <div v-if="!showResult">
                    <Button :disabled="isVoteOK" size="large" type="success" @click="submitMessage()">
                        <svg-icon icon-class="vote" class="uploadBtn-icon" />
                        <span style="margin-left:5px">{{ isVoteOK ? $t("studentWeb.vote.submitOKVote") : $t("studentWeb.vote.submitBVote") }}</span>
                    </Button>
                    <span class="clickbutnoChoosehint"
                        v-if="clickbutnoChoose == true && voteChecked == ''">{{ $t("studentWeb.vote.note") }}</span>
                    <span v-if="isOverCount && !isVoteOK" style="margin-top:5px;margin-left:15px;color:red">{{$t("studentWeb.vote.warning2")}}</span>
                </div>
            <!-- </div> -->
        </div>
        <!--图片放大显示-->
        <Modal v-model="imgPreview.show" width="95">
            <img :src="imgPreview.img" style="width: 100%" />
        </Modal>
    </div>
</template>

<script>
    import EventBasicInfo from "../../EventBasicInfo";
    import BillBoardandLightBox from "../../EventView/BillBoardandLightBox";
    import VoteResultChart from "./VoteResultChart";
    import Loading from '@/common/Loading.vue'
    // import Load from "vue-loading-overlay";
    import { mapGetters } from 'vuex';
    export default {
        name: "Vote",
        components: {
            EventBasicInfo,
            VoteResultChart,
            BillBoardandLightBox,
            Loading
        },
        mounted() {
            this.getVoteInfo()
            this.WarmMessageisOpen = false;
            this.voteChecked = [];
            this.clickbutnoChoose = false;
        },
        data() {
            return {
                voteChecked: [], //多选——单次
                numChecked: 0, //多选——重复
                WarmMessageisOpen: false,
                clickbutnoChoose: false, //没有选中选项
                voteInfo: {}, //投票信息
                voteResData: [], //投票结果的数据
                isVote: false, //不可以投票
                isVoteOK: false, //已经投票
                showResult: false, //显示投票结果
                isLoad: false,
                isOverCount: false,
                voteData: [], //投票结果的数据
                voteList: [], //投票结果的 X轴
                imgPreview: {
                    img: "",
                    show: false
                },
                voteTimes: null, //投票周期
            };
        },
        methods: {
            // 获取个人投票结果数据
            getVoteRecord() {
                if (this.getItemTitle.id) {
                    this.voteResData = []
                    let params = {
                        "id": this.getItemTitle.id,
                        "code": this.getItemTitle.scode,
                        "userid": this.$store.state.userInfo.sub
                    }
                    this.$api.studentWeb.getVoteResult(params).then(res => {
                        if (res) {
                            this.timeStatus(this.voteInfo, res.records)
                            if(res.records.length) {
                                let time = (new Date()).getTime()
                                if(this.voteInfo.endTime > time) {
                                    if(this.voteInfo.times == "once") {
                                        this.isVoteOK = true
                                    }
                                    // 每天
                                    else if(this.voteInfo.times == "day") {
                                        // 最近一次投票的时间 < 当天凌晨，则表示当天还没有投票
                                        let strdDate = (new Date(new Date(new Date().toLocaleDateString()).getTime())).getTime()
                                        // 最新一条记录在最前面
                                        this.isVoteOK = res.records[0].time < strdDate ? false : true
                                    }
                                    // 每周
                                    else if(this.voteInfo.times == "week") {
                                        let days = new Date().getDay() || 7
                                        //显示周一
                                        let MondayTime = (new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1 - days)).getTime()
                                        this.isVoteOK = res.records[0].time < MondayTime ? false : true
                                    }
                                    // 每月
                                    else if(this.voteInfo.times == "month") {
                                        // 每个月第一天
                                        let firstDay = (new Date()).setDate(1)
                                        firstDay = new Date(new Date(firstDay).toLocaleDateString()).getTime()
                                        this.isVoteOK = res.records[0].time < firstDay ? false : true
                                    }
                                } else {
                                    this.isVoteOK = true
                                }
                                this.voteResData = res.records
                                if(this.isVoteOK) {
                                    if(this.voteInfo.times != "once" || this.voteInfo.repeat) {
                                        // 累计当前学生在所有投票轮次的每个选项投票数量
                                        this.voteInfo.options.forEach(i => {
                                            i.count = this.doCountTotal(res.records, i.code)
                                        })
                                    }
                                    // 单次、不能重复投票
                                    else {
                                        for(let key in res.records[0].opt) {
                                            this.voteChecked.push(key)
                                        }
                                    }
                                }
                            }
                        }
                    }).finally(() => {
                        this.isLoad = false
                    })
                }
            },
            // 获取某个选项在投票结果的投票数量
            doCountTotal(arr, code) {
                let result = 0
                arr.forEach(i => {
                    if(i.opt[code]) {
                        result += i.opt[code]
                    }
                })
                // 未投票的选项会显示NaN
                if(Number.isNaN(result)) {
                    result = 0
                }
                return result
            },
            //获取活动投票结果数据
            getVoteInfo() {
                this.isOverCount = false
                this.clickbutnoChoose = false
                this.isVoteOK = false
                if (this.getItemTitle.id) {
                    let params = {
                        "id": this.getItemTitle.id,
                        "code": this.getItemTitle.scode
                    }
                    this.isLoad = true
                    this.$api.studentWeb.getVoteInfo(params).then(res => {
                        if (res) {
                            if(res.status == 404) {
                                this.isLoad = false
                                this.$Modal.confirm({
                                    title: this.$t("studentWeb.vote.delTitle"),
                                    okText: this.$t("studentWeb.vote.delOk"),
                                    cancelText: this.$t("studentWeb.vote.delCancel"),
                                    onOk: () => {
                                        this.delActivity()
                                    }
                                })
                            }
                            else if(res.status == 200) {
                                this.showResult = false
                                for (let item of res.vote.options) {
                                    item.count = 0
                                }
                                this.voteInfo = res.vote
                                this.voteTimes = this.getVoteType(res.vote.times)
                                this.voteChecked.length = 0
                                if (res.vote.progress == "finish") {
                                    // 投票结束，获取Blob来展示投票结果
                                    this.getVoteRes()
                                    this.isVote = false
                                }
                                this.getVoteRecord()
                            }
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                }
            },
            async getVoteRes() {
                if (this.voteInfo.recordUrl !== "") {
                    let data = await this.getBlobItems(this.voteInfo)
                    this.setData(data[0])
                }
            },
            // 获取投票周期
            getVoteType() {
                if(this.voteInfo != undefined) {
                    if(this.voteInfo.times == "once") {
                        return this.$t("studentWeb.vote.type.once")
                    }
                    else if(this.voteInfo.times == "day") {
                        return this.$t("studentWeb.vote.type.day")
                    }
                    else if(this.voteInfo.times == "week") {
                        return this.$t("studentWeb.vote.type.week")
                    }
                    else if(this.voteInfo.times == "month") {
                        return this.$t("studentWeb.vote.type.month")
                    }
                    else if(this.voteInfo.times == "year") {
                        return this.$t("studentWeb.vote.type.year")
                    }
                }
            },
            // 放大图片
            showImg(e) {
                this.imgPreview = {
                    img: "",
                    show: false
                }
                if (e.target.tagName == 'IMG') {
                    this.imgPreview.img = e.target.src
                    this.imgPreview.show = true
                }
            },
            // 删除不存在的投票
            delActivity() {
                let roles = ""
                if(this.$store.state.userInfo.roles.indexOf('student') > -1) {
                    roles = 'student'
                } else {
                    roles = 'teacher'
                }
                let param = {
                    'id': this.getItemTitle.id,
                    'code': this.getItemTitle.code,
                    "role": roles
                }
                this.$api.studentWeb.delActivity(param).then(res => {
                    if(res) {
                        if(res.status == 200) {
                            this.$Message.success(this.$t("studentWeb.vote.delSuccess"))
                            this.$EventBus.$emit('delNotFound', this.getItemTitle.id)
                            this.$store.commit("ChangeItemName", {})
                        }
                    }
                }).finally(()=>{
                    this.isLoad = false
                })
            },
            // 获取blob里的试题数据
            getBlobItems(qnItem) {
                return new Promise(async (resolve, reject) => {
                    // blobHost例子：https://teammodelstorage.blob.core.chinacloudapi.cn/
                    let blobHost = this.$tools.getBlobHost()
                    let code = qnItem.scope === 'private' ? qnItem.creatorId : qnItem.school
                    // 授权
                    let sas = await this.$tools.getBlobSas(code)
                    let itemFullPath = blobHost + '/' + code + qnItem.recordUrl + sas
                    // 根据试卷的Blob地址 去读取JSON文件
                    let promiseArr = []
                    promiseArr.push(new Promise(async (r, j) => {
                        try {
                            let itemJson = JSON.parse(await this.$tools.getFile(itemFullPath))
                            r(itemJson)
                        } catch (e) {
                            j(e)
                        }
                    }))
                    Promise.all(promiseArr).then(result => {
                        resolve(result)
                    }).catch(err => {
                        reject(err)
                    })
                })
            },
            // 准备图表数据
            setData(data) {
                this.voteData = []
                this.voteList = []
                if (data.options.length) {
                    let code = []
                    code = data.options.sort((a, b) => {
                        return (a.code < b.code) ? -1 : (a.code > b.code) ? 1 : 0;
                    })
                    let colorList = ["#73a373", "#73b9bc", "#7289ab", "#e69d87"]
                    let i = 0
                    for (let item of code) {
                        if(i == colorList.length) {
                            i = 0
                        }
                        this.voteData.push({
                            value: item.count,
                            itemStyle: { color: colorList[i] },
                        })
                        this.voteList.push(item.code)
                        i++
                    }
                }
                else {
                    for (let item of this.voteInfo.options) {
                        this.voteData.push({
                            value: 0
                        })
                        this.voteList.push(item.code)
                    }
                }
                this.showResult = true
            },
            // 获取当前时间状态
            getDates(day, type) {
                let zdate = new Date();
                let edate
                if (type == 1) {
                    // 星期一
                    edate = new Date(zdate.getTime() - (day * 24 * 60 * 60 * 1000));
                } else {
                    // 星期天
                    edate = new Date(zdate.getTime() + (day * 24 * 60 * 60 * 1000));
                }
                // edate = Sun Aug 15 2021 16:02:51 GMT+0800 (中国标准时间)
                return edate;
            },
            // 投票活动的时间状态 data投票活动信息 time 已投票数据
            timeStatus(info, records) {
                let date = (new Date()).getTime() //当前时间戳
                let status = false //判断当前活动是否继续进行投票
                let dataTime = '' //开始时间
                if (records.length) {
                    records = records.sort((a, b) => {
                        return b.time - a.time //时间正序
                    });
                    dataTime = records[0].time
                }
                this.isVote = false
                let year = new Date().getFullYear()
                let month = new Date().getMonth()
                //时间范围内 已投票
                if (date <= info.endTime && date >= info.startTime && records.length > 0) {
                    switch (info.times) {
                        case 'day':
                            let daySart = new Date(new Date(new Date().toLocaleDateString()).getTime()).getTime()
                            let dayEnd = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1).getTime()
                            if (dataTime <= daySart || dataTime >= dayEnd) {
                                status = true
                            }
                            break;
                        //是否为本周
                        case 'week':
                            let curWeek = new Date().getDay(); //获取当前星期几
                            let monday = this.getDates((curWeek), 1).getTime(); //计算出星期一
                            let sunday = this.getDates((7 - curWeek), 2).getTime(); //计算出星期天
                            if (dataTime <= sunday || dataTime >= sunday) {
                                status = true
                            }
                            break;
                        //是否为本月
                        case 'month':
                            let firstDay = new Date(year, month, 1).getTime()
                            let lastDay = new Date(year, month + 1, 1).getTime() - 1
                            if (dataTime <= firstDay || dataTime >= lastDay) {
                                status = true
                            }
                            break;
                        //是否为本年
                        case 'year':
                            let firstYear = new Date(year, 0, 1).getTime()
                            let lastYear = new Date(year + 1, 0, 0).getTime()
                            if (dataTime <= firstYear || dataTime >= lastYear) {
                                status = true
                            }
                            break;
                        default:
                    }
                }
                //在时间范围内 未投票
                else if (date <= info.endTime && date >= info.startTime && records.length == 0) {
                    status = true
                } else {
                    status = false
                }
                this.isVote = status
                return status
            },
            // 多选框改变时
            controlNum(arr) {
                if(arr.length > this.voteInfo.voteNum && this.voteInfo.voteNum > 1) {
                    this.isOverCount = true
                } else {
                    this.isOverCount = false
                }
            },
            submitMessage() {
                // 未投票
                if(!this.voteChecked.length) {
                    this.clickbutnoChoose = true;
                }
                // 超出票数
                else if (this.voteChecked.length > this.voteInfo.voteNum || this.numChecked > this.voteInfo.voteNum) {
                    this.$Message.warning(this.$t("studentWeb.vote.warning2"))
                }
                else {
                    let params = {
                        "id": this.getItemTitle.id,
                        "code": this.getItemTitle.scode,
                        "option": {}
                    }
                    for (let item of this.voteChecked) {
                        if (this.voteInfo.times != "once" || this.voteInfo.repeat) {
                            params.option[item.code] = item.count
                        } else {
                            params.option[item] = 1
                        }
                    }
                    this.$api.studentWeb.sendVoteResult(params).then(res => {
                        if (res.msgid == 1) {
                            this.WarmMessageisOpen = true;
                            this.getVoteInfo()
                            setTimeout(() => {
                                this.WarmMessageisOpen = false;
                            }, 1000);
                        } else {
                            this.$Message.warning(this.$t('studentWeb.vote.warning'))
                        }
                    })
                }
            },
        },
        computed: {
            ...mapGetters([
                "getItemTitle",
            ]),
            nowActive() {
                return this.getItemTitle
            },
            voteCount() {
                if (this.voteInfo.voteNum !== undefined) {
                    let num = 0
                    this.isOverCount = false
                    for (let item of this.voteInfo.options) {
                        if (item.count !== null) {
                            num += item.count
                        }
                    }
                    this.numChecked = num
                    if (num > this.voteInfo.voteNum) {
                        this.isOverCount = true
                        return 0
                    }
                    return this.voteInfo.voteNum - num
                }
            }
        },

        watch: {
            nowActive: {
                handler() {
                    this.isVote = false
                    this.showResult = false
                    this.isExamDown = false
                    this.voteInfo = {}
                    this.getVoteInfo()
                }
            },
            //判断投票数量是否有变化
            voteInfo: {
                handler() {
                    if (this.voteInfo.name !== undefined) {
                        let arr = []
                        for (let item of this.voteInfo.options) {
                            if (item.count > 0) {
                                arr.push(item)
                            }
                        }
                        this.voteChecked = [...new Set(arr)]
                    }
                },
                deep: true
            },
            voteChecked: {
                handler(n, o) {
                    if(this.voteInfo.voteNum == 1) {
                        // 只有一票
                        if(o.length && n.length > 1) {
                            let i = n.findIndex(item => {
                                return item == o[0]
                            })
                            n.splice(i, 1)
                        }
                    }
                }
            }
        },
    };
</script>

<style scoped>
    @import "~@/assets/student-web/component_styles/vote.css";
</style>
<style lang="less" scoped>
.vote {
    .imgDolg {
        width: 100vw;
        height: 100vh;
        position: fixed;
        z-index: 9999;
        background-color: rgba(140, 134, 134, 0.6);
        top: 0;
        left: 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .imgDolg img {
        width: 60%;
        border: 1px solid #eee;
        // height: 95%;
    }

    .imgDolg #imgDolgClose {
        position: fixed;
        top: 35px;
        cursor: pointer;
        right: 17%;
        font-size: 50px;
        color: white;
    }
}
</style>