<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 />
        <div>
            <!--超时-->
            <div v-if="this.$store.getters.getItemTitle.endTime <= '2020.02.10'">
                <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 v-if="!showResult">
                <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>
                <BillBoardandLightBox :activityData="voteInfo" :voteRes="voteResData" />
                <div class="vote-title">
                    <div class="title-rect-group">
                        <!-- <div class="title-rect" /> -->
                        <h2 class="title-rect-name">{{ $t("studentWeb.vote.bollotbox") }}</h2>
                        <p v-if="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>
                    <Button v-show="isResult" style="float:right;margin-top:-30px" size="small" type="success" @click="showRes">
                        <span style="margin-left:5px">{{$t("studentWeb.vote.voteRes")}}</span>
                    </Button>
                </div>
                <!-- 投票内容 -->
                <div class="question-box"><span v-html="voteInfo.description"></span></div>
                <div>
                    <div class="checkAnswer" v-for="(item, index) in voteInfo.options" :key="index">
                        <label class="testBtn">
                            <input type="checkbox" :value="item" v-model="voteChecked" @click="getVote(item)" />
                            <div class="testbg">
                                <div class="vote-info">
                                    <span style="display:flex;margin-right:5px">{{item.code}}.<span v-html="item.value"></span></span>
                                </div>
                                <InputNumber v-model="item.count"
                                             :formatter="value => `${value}` +$t('studentWeb.vote.tickets')"
                                             :parser="value => value.replace($t('studentWeb.vote.tickets'), '')"
                                             :min="0"
                                             v-if="voteInfo.repeat"
                                             @on-change="setVoteNum(item)"
                                             :disabled="!voteStatus">
                                </InputNumber>
                            </div>
                        </label>
                    </div>
                </div>
                <Button :disabled="!isVote" size="large" type="success" @click="submitMessage()">
                    <svg-icon icon-class="vote" class="uploadBtn-icon" />
                    <span style="margin-left:5px">{{ $t("studentWeb.vote.submitBVote") }}</span>
                </Button>
                <span class="clickbutnoChoosehint"
                      v-if="clickbutnoChoose == true && voteChecked == ''">{{ $t("studentWeb.vote.note") }}</span>
                <span v-if="isOverCount" style="margin-top:5px;margin-left:15px;color:red">{{$t("studentWeb.vote.warning2")}}</span>

            </div>
        </div>
        <!-- 投票结果 -->
        <div class="voteResults" v-if="showResult">
            <h3 class="voteResultsMainRow ">
                {{ $t("studentWeb.vote.voteResult") }}
            </h3>
            <div class="question-box">
                <span style="display:block;width:90%" v-html="voteInfo.description"></span>
                <Button style="float:right;margin-top:0px" size="small" type="success" @click="showRes">
                    <span style="margin-left:5px">{{$t("studentWeb.vote.voteRecord")}}</span>
                </Button>
            </div>
            <div v-for="(item,index) in voteInfo.options" :key="index">
                <div class="voteResultsItem">
                    <p style="display:flex">{{ item.code }}.<span v-html="item.value"></span></p>
                </div>
            </div>
            <div align="center">
                <VoteResultChart :voteData="voteData" :voteList="voteList" />
            </div>
        </div>
    </div>
</template>

<script>
    import EventBasicInfo from "../../EventBasicInfo";
    import BillBoardandLightBox from "../../EventView/BillBoardandLightBox";
    import VoteResultChart from "./VoteResultChart";
    import Load from "vue-loading-overlay";
    export default {
        name: "Vote",
        components: {
            EventBasicInfo,
            VoteResultChart,
            BillBoardandLightBox,
            Load
        },
        mounted() {
            this.getVoteInfo()
            this.WarmMessageisOpen = false;
            this.voteChecked = [];
            this.clickbutnoChoose = false;
        },
        data() {
            return {
                isHintNextItem: false,
                voteChecked: [],
                WarmMessageisOpen: false,
                clickbutnoChoose: false,
                voteInfo: {}, //投票信息
                voteRes: {},
                voteResData: [],
                isVote: false,
                voteStatus:false,
                voteNum: 0,
                showResult: false, //显示投票结果
                chooseVoteRes: {},
                isLoad: false,
                isResult: false,
                isOverCount: false,
                voteData: [],
                voteList: []
            };
        },
        methods: {
            //获取个人投票结果数据
            getVoteRecord() {
                if (this.$store.getters.getItemTitle.id) {
                    this.voteRes = {}
                    let params = {
                        "id": this.$store.getters.getItemTitle.id,
                        "code": this.$store.getters.getItemTitle.scode,
                        "userid": this.$store.state.userInfo.sub
                    }
                    this.$api.studentWeb.getVoteResult(params).then(res => {
                        if (res) {
                            this.voteRes = res
                            this.timeStatus(this.voteInfo, this.voteRes)
                            this.voteResData = this.voteRes.records.sort((a, b) => {
                                return b > a
                            })
                            this.isLoad = false
                        }
                    })
                }
            },
            //获取活动投票结果数据
            getVoteInfo() {
                if (this.$store.getters.getItemTitle.id) {
                    let params = {
                        "id": this.$store.getters.getItemTitle.id,
                        "code": this.$store.getters.getItemTitle.scode
                    }
                    this.isLoad = true
                    this.$api.studentWeb.getVoteInfo(params).then(res => {
                        if (res) {
                            this.showResult = false
                            this.isResult = false
                            for (let item of res.vote.options) {
                                item.count = 0
                            }
                            this.voteInfo = res.vote
                            if (res.vote.progress == "finish") {
                                this.getVoteRecord()
                                this.getVoteRes()
                                this.isResult = true
                            } else {
                                this.getVoteRecord()
                            }
                        }
                    })
                }
            },
           async getVoteRes() {
                if (this.voteInfo.recordUrl !== "") {
                    let data = await this.getBlobItems(this.voteInfo)
                    this.setData(data[0])
                }
            },
            // 获取blob里的试题数据
            getBlobItems(qnItem) {
                let key = this.voteInfo.code.split('-')
                let code = key[key.length - 1]
                return new Promise(async (resolve, reject) => {
                    let blobHost = 'https://teammodelstorage.blob.core.chinacloudapi.cn/' + code
                    // 根据试卷的Blob地址 去读取JSON文件
                    let sasString = qnItem.scope === 'private' ? await this.$tools.getPrivateSas(code) : await this.$tools.getSchoolSas(code)
                    let promiseArr = []
                        promiseArr.push(new Promise(async (r, j) => {
                            try {
                                let itemJson = JSON.parse(await this.$tools.getFile(blobHost + qnItem.recordUrl + sasString.sas))
                                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;
                    })
                    for (let item of code) {
                        this.voteData.push({
                            value: item.count,
                            itemStyle: { color: "#00AD6C" },
                        })
                        this.voteList.push(item.code)
                    }
                }
            },
            //排序
            compare(val1, val2){
                return val1.code.toLowerCase() < val2.code.toLowerCase()
             },
            showRes() {
                this.showResult = !this.showResult
            },
            //获取投票结果
            getVote(data) {
                if (!this.voteInfo.repeat) {
                    this.voteChecked.length = 0
                    this.voteChecked.push(data)
                }
            },
            //处理时间结构
            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;
            },
            //获取当前时间状态
            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));
                }
                return edate;
            },
            //投票活动的时间状态 data投票活动信息 time 已投票数据
            timeStatus(data, time) {
                let date = (new Date()).getTime() //当前时间
                let status = false //判断当前活动是否继续进行投票
                let dataTime = ''
                if (time.records.length) {
                    time.records = time.records.sort((a, b) => {
                        return b.time - a.time //时间正序
                    });
                    dataTime = time.records[0].time
                }
                this.isVote = false
                let inDate = new Date(date)
                let year = inDate.getFullYear()
                let month = inDate.getMonth()
                //时间范围内 已投票
                if (date <= data.endTime && date >= data.startTime && time.records.length > 0) {
                    switch (data.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 = 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 <= data.endTime && date >= data.startTime && time.records.length == 0) {
                    status = true
                } else {
                    status = false
                }
                this.voteStatus = status
                this.isVote = status
                return status
            },

            setVoteNum(data) {
                if (this.isOverCount) {
                    data.count = 0
                }
            },
            submitMessage() {
                this.clickbutnoChoose = false;
                if (this.voteChecked.length) {
                    let params = {
                        "id": this.$store.getters.getItemTitle.id,
                        "code": this.$store.getters.getItemTitle.scode,
                        "option": {}
                    }
                    for (let item of this.voteChecked) {
                        if (this.voteInfo.repeat) {
                            params.option[item.code] = item.count
                        } else {
                            params.option[item.code] = 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'))
                        }
                    })
                    this.voteChecked = []
                } else if (this.voteChecked == "") {
                    this.clickbutnoChoose = true;
                }
            },
            cancelPreview() {
                this.isHintNextItem = false;
            },
        },
        computed: {
            listData() {
                return this.$store.getters.getItemTitle.id;
            },
            voteCount() {
                if (this.voteInfo.voteNum !== undefined) {
                    let num = 0
                    this.isVote = true
                    this.isOverCount = false
                    for (let item of this.voteInfo.options) {
                        if (item.count !== null) {
                            num += item.count
                        }
                    }
                    if (num > this.voteInfo.voteNum) {
                        this.isOverCount = true
                        this.isVote = false
                        return 0
                    }
                    return this.voteInfo.voteNum - num
                }
            }
        },
        watch: {
            $route: {
                handler() {
                    this.isVote = false
                    this.showResult = false
                    this.isExamDown = false
                    this.voteInfo = {}
                    this.getVoteInfo()
                },
                deep: true
            },
            //判断投票数量是否有变化
            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
            }
        },
    };
</script>

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