<template>
    <div class="jyzx-vote">
        <div
            style="
                width: 35%;
                background-color: #fff;
                border-right: 1px solid rgba(0, 0, 0, 0.1);
            "
        >
            <vuescroll>
                <EmptyData v-if="!listShow.length" :top="100"></EmptyData>
                <div style="margin-bottom: 50px" v-else>
                    <div
                        :id="`event${item.id}`"
                        class="list-new"
                        @click="sentSelectedEventTitle(item, index)"
                        :class="{'list-item-selected': item.id == voteInfo.id,}"
                        v-for="(item, index) in listShow"
                        :key="index"
                    >
                        <div class="list-new-icon">
                            <svg-icon icon-class="vote" />
                        </div>
                        <div class="list-new-test">
                            <p>
                                <span class="list-item-title"
                                    style="display: inline-block; background: #a2b02e;"
                                    v-show="item.owner == 'area'"
                                >{{ $t("jyzx.common.area") }}</span>
                                <span class="list-item-title"
                                    style="display: inline-block; background: #FF9900;"
                                    v-show="item.owner == 'school'"
                                >{{ $t("jyzx.common.school") }}</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" v-if="item.progress == 'finish'">
                                <span class="isOvertime">{{ $t("studentWeb.public.finish") }}</span>
                            </div>
                            <div class="list-new-unDone isAllowRetry" v-else>
                                <span>{{ $t("studentWeb.public.going") }}</span>
                            </div>
                            
                        </div> -->
                    </div>
                </div>
            </vuescroll>
        </div>
        <div style="width: 75%; background-color: #fff;overflow: auto;padding-bottom: 40px;">
            <EmptyData v-if="!Object.keys(voteInfo).length" :top="-100"></EmptyData>
            <div class="vote-option" v-else>
                <div class="billboard-and-LightBox">
                    <p>
                        <span class="school-gade" style="background: #a2b02e" v-show="voteInfo.owner == 'area'">{{ $t("jyzx.common.typeArea") }}</span>
                        <span class="school-gade" style="background: #ff9900" v-show="voteInfo.owner == 'school'">{{ $t("jyzx.common.typeSch") }}</span>
                        {{ voteInfo.name }}
                    </p>
                    <div class="title-rect-group">
                        <h2 class="title-rect-name">
                            {{ $t("studentWeb.billboard.description") }}
                        </h2>
                    </div>
                    <div class="dec">
                        <p>
                            <span v-html="voteInfo.description"></span>
                        </p>
                    </div>
                    <div class="title-rect-group">
                        <h2 class="title-rect-name">{{ $t("jyzx.activity.voteArea") }}</h2>
                        <span v-show="voteInfo.voteNum > 1">{{ $t("jyzx.activity.haveVoteNum") }}：{{ voteCount }}</span>
                    </div>
                </div>
                <div>
                    <!-- 只投一次 -->
                    <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>
                <Button
                    :disabled="isVoteOK"
                    size="large"
                    type="success"
                    @click="submitMessage()"
					style="margin-top: 20px;"
                >
                    <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 class="warnText" v-show="isOverCount && !isVoteOK">{{ $t("jyzx.activity.numExce") }}</span>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
			radioCheck:'',
            listShow: [], //列表
            voteIndex: 0,
            voteInfo: {}, //投票
            voteChecked: [], //多选——单次
            numChecked: 0, //多选——重复
            isOverCount: false,
            clickbutnoChoose: false, //没有选中选项
            isVote: false,
            isVoteOK: false, //已经投票
            haveVoteNum: 0,
        }
    },
    created() {
        this.getList()
    },
    methods: {
        // 获取投票列表
        getList() {
            let req = {
                type: "Vote"
            }
            this.$api.jyzx.getAllActivity(req).then((res) => {
                if (res.datas.length) {
                    res.datas.reverse()
                    this.listShow = res.datas
                    this.sentSelectedEventTitle(
                        this.listShow[this.voteIndex],
                        0
                    )
                }
            })
        },
        // 展示当前活动
        sentSelectedEventTitle(item, index) {
            this.isVoteOK = false
            // this.isVote = item.time !== 0 ? false : true
            this.voteIndex = index
            this.voteInfo = {}
            this.voteChecked = []
            let req = {
                // tId: this.$store.state.userInfo.TEAMModelId,
                code: item.scode,
                id: item.id,
            }
            this.$api.jyzx.getVoteInfo(req).then((res) => {
                if(res.status == 404) {
                    this.$Modal.confirm({
                        title: this.$t("studentWeb.vote.delTitle"),
                        okText: this.$t("studentWeb.vote.delOk"),
                        cancelText: this.$t("studentWeb.vote.delCancel"),
                        onOk: () => {
                            this.delActivity(item)
                        }
                    })
                }
                else if(res.status == 200) {
                    for (let item of res.vote.options) {
                        item.count = 0
                    }
                    this.voteInfo = res.vote
                    this.voteChecked.length = 0
                    this.haveVoteNum = this.voteInfo.voteNum
                    if (res.vote.progress == "finish") {
                        // 投票结束，获取Blob来展示投票结果
                        // this.getVoteRes()
                        this.isVote = false
                    }
                    this.getVoteRecord()
                }
            })
        },
        // 获取个人投票结果数据
        getVoteRecord() {
            this.voteResData = []
            let params = {
                "id": this.voteInfo.id,
                "code": this.voteInfo.code,
                "userid": this.$store.state.userInfo.TEAMModelId
            }
            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
        },
        // 投票活动的时间状态 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
        },
        async getVoteRes() {
            if (this.voteInfo.recordUrl !== "") {
                let data = await this.getBlobItems(this.voteInfo)
                this.setData(data[0])
            }
        },
        // 获取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)
                })
            })
        },
        // 删除不存在的投票
        delActivity(item) {
            let param = {
                code: item.code,
                id: item.id,
                role: "teacher"
            }
            this.$api.jyzx.delActivity(param).then(res => {
                if(res) {
                    if(res.status == 200) {
                        this.$Message.success(this.$t("studentWeb.vote.delSuccess"))
                        let listIndex = null
                        this.listShow.forEach((list, index) => {
                            if(list.id == item.id) {
                                listIndex = index
                            }
                        })
                        this.listShow.splice(listIndex, 1)
                        if(listIndex == this.listShow.length) {
                            listIndex = 0
                        }
                        this.sentSelectedEventTitle(this.listShow[listIndex], listIndex)
                    }
                }
            }).finally(()=>{
            })
        },
        //获取投票结果
        getVote(data) {
            if (this.voteInfo.voteNum <= 1) {
                this.voteChecked.length = 0
                this.voteChecked.push(data)
            }
        },

        // 多选框改变时
        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 = {
                    code: this.voteInfo.code,
                    id: this.voteInfo.id,
                    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.jyzx.sendVoteResult(params).then((res) => {
                    if (res.msgid == 1) {
                        this.$Message.success(this.$t("jyzx.activity.success2"))
                        this.getList()
						this.radioCheck = ''
						this.voteChecked = []
                    }
                })
            }
        },
        dateFormat(timestamp) {
            let date = new Date(timestamp)
            let Y = date.getFullYear()
            let M = date.getMonth()
            let D = date.getDate()
            let H = date.getHours()
            let MIN = date.getMinutes()
            return `${Y}-${M < 9 ? "0" + (M + 1) : M + 1}-${D} ${
                H < 10 ? "0" + H : H
            }:${MIN < 10 ? "00" : MIN}`
        },
    },
    computed: {
        voteCount() {
            if (this.voteInfo.voteNum !== undefined) {
                let num = 0
                this.isOverCount = false
                // 不重复
                if(!this.voteInfo.repeat) {
                    num = this.voteChecked.length
                } else {
                    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: {
        //判断投票数量是否有变化
        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 lang="less" scoped>
.jyzx-vote {
    display: flex;
    height: 100%;

    .school-gade{
        vertical-align: middle;
        font-size: 14px;
        color: #fff;
        // background-color: #F97C57;
        padding: 3px 5px;
        border-radius: 8px;
        margin-right: 5px;
        font-weight: normal;
    }

    .list-item-selected {
        background: linear-gradient(-270deg, #fafafa, #d4ede1);
        color: #03966a;
        cursor: pointer;
        width: 100%;
    }
    .list-new {
        display: flex;
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        padding: 15px 20px 15px 25px;
        cursor: pointer;

        .list-item-title{
            display: inline-block;
            width: 20px;
            height: 20px;
            line-height: 20px;
            border-radius: 10px;
            // background-color: #F97C57;
            font-size: 12px;
            text-align: center;
            color: #fff;
            margin-right: 5px;
        }

        &-icon {
            width: 10%;
            margin-right: 30px;
            .svg-icon {
                width: 40px;
                height: 40px;
            }
        }
        &-test {
            width: 70%;
            font-weight: bolder;
            font-size: 14px;
            // line-height: 40px;
            margin-right: 20px;
            clear: both;
        }
        &-type {
            width: 20%;
            display: flex;
            justify-content: center;
            flex-direction: column;

            .isAllowRetry {
                color: #fff;
                background-color: #19B177;
                border: none;
            }

            .list-new-unDone {
                font-size: 10px;
                font-weight: bolder;
                padding: 5px;
                border-radius: 4px;
                text-align: center;
                border: 1px solid;
            }
        }
    }

    .vote-option {
        width: 100%;
        background-color: #fff;
        padding-left: 50px;
        padding-top: 40px;

        .billboard-and-LightBox > p:first-child{
            font-size: 25px;
            font-weight: bold;
        }

        .title-rect-group {
            span {
                margin-left: 10px;
            }
        }
        .checkAnswer {
            display: block;
            margin-top: 20px;
            margin-left: 0px;

            .testBtn {
                margin: 20px 0px;
                position: relative;
                z-index: 2;
                font-weight: bolder;
                padding-left: 20px;
                cursor: pointer;

                input[type="checkbox"] {
                    visibility: hidden;
                    margin-left: -10px;

                    &:checked {
                        ~ .testbg {
                            background-color: #24b880 !important;
                            border: none;

                            span {
                                color: #fff;
                                font-weight: bolder;
                            }
                        }
                    }
                }
            }

            .testbg {
                cursor: pointer;
                background-color: #fff;
                position: relative;
                height: auto;
                top: -31px;
                padding: 10px;
                z-index: 1;
                display: flex;
                border-radius: 4px;
                border: 1px solid rgb(197, 197, 197);
            }
        }

        .option-group {
            display: flex;
            flex-direction: column;

            .option-wrapper {
                margin:15px 0 5px 0;
                display: flex;
                align-items: center;
                padding: 20px 10px;
                border: 1px solid #ccc;
                border-radius: 5px;

                & > span {
                    margin-left: 5px;
                }

                .ivu-checkbox{
                    margin-right: 5px;
                }
            }
        }

        .option-repeat{
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            padding: 15px 10px;
            border-radius: 4px;

            .ivu-input-number {
                margin-right: 15px;
                width: 120px;
            }
        }

        .action-rep{
            background-color: #19BE6B;
            color: #fff;
        }

        .warnText {
            color: red;
            margin-left: 10px;
        }
    }
}
</style>
<style lang="less">
.option-group {
    .ivu-checkbox,
    .ivu-radio {
        display: none;
    }
    .ivu-checkbox-wrapper-checked.ivu-checkbox-border,
    .ivu-radio-wrapper-checked.ivu-radio-border {
        background: #24b880;
        border-color: #24b880;
        color: #fff;
    }
}
</style>