<template>
    <div class="jyzx-ques">
        <div
            style="
                width: 50%;
                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"
                        v-for="(item, index) in listShow"
                        :key="index"
						@click="sentSelectedEventTitle(item, index)"
						:class="{
						    'list-item-selected': activeIndex == index,
						}"
                    >
                        <div class="list-new-icon">
                            <svg-icon icon-class="quesnaire" />
                        </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 style="font-size: 16px;">{{ item.name }}</span>
                            </p>
                            <p class="list-item-time" style="color: #9d9d9d;font-weight: 500;margin: 5px 0;">
                                {{ $t("jyzx.activity.startTime") }}： {{ dateFormat(item.createTime) }}
                                <!--{{ dateFormat(item.endTime) }}-->
                            </p>
                        </div>
                        <!-- <div class="list-new-type">
                            <div class="list-new-unDone isAllowRetry"  v-if="!alreadyAnswered"  style="background-color: #19b177 ">
                                <span>{{ $t("jyzx.activity.incomplete") }}</span>
                            </div>
                            <div class="list-new-unDone isAllowRetry" v-if="alreadyAnswered" style="background-color:#969696">
                                <span>{{ $t("jyzx.common.complete") }}</span>
                            </div>
                        </div> -->
                    </div>
                </div>
            </vuescroll>
        </div>
        <div class="ques-option">
            <div
                style="height: 100%"
				  v-if="listShow.length"
            >
                <vuescroll>
                    <div>
                        <!-- 已提交 -->
                        <div v-if="alreadyAnswered" style="text-align: center; padding-top: 15%;">
                            <Icon type="md-checkmark-circle-outline" color="#00ad6c" size="80"/>
                            <p style="font-size: 30px; color:#00ad6c; font-weight: 600; margin:20px;">{{ $t('survey.studentWeb.already') }}</p>
                        </div>
                        <!-- 活动结束 -->
                        <div v-if="!alreadyAnswered && surveyInfo.progress === 'finish'" style="text-align: center; padding-top: 15%;">
                            <Icon type="md-stopwatch" color="#00ad6c" size="80"/>
                            <p style="font-size: 30px; color:#00ad6c; font-weight: 600; margin:20px;">{{ $t('survey.studentWeb.overtime') }}</p>
                        </div>
                    </div>
                    <!-- <EmptyData v-if="!Object.keys(surveyInfo).length" :top="-100"></EmptyData> -->
                    <div style="margin-bottom: 100px"  v-if="surveyInfo.progress !== 'finish' && !alreadyAnswered">
                        <p class="servey-title">
                            <span class="school-gade" style="background: #a2b02e" v-show="surveyInfo.owner == 'area'">{{ $t("jyzx.common.typeArea") }}</span>
                            <span class="school-gade" style="background: #ff9900" v-show="surveyInfo.owner == 'school'">{{ $t("jyzx.common.typeSch") }}</span>
                            {{ surveyInfo.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="surveyInfo.description"></span>
                            </p>
                        </div>
                        <!-- 内容 -->
                        <div class="title-rect-group">
                            <h2 class="title-rect-name">
                                {{ $t("survey.studentWeb.content") }}
                            </h2>
                        </div>
                        <br />
                        <!-- 问卷内容 -->
                        <div
                            v-for="(item, index) in surveyInfo.items"
                            :key="index"
                            class="survey-item"
                        >
                            <div style="display: flex; font-weight: bold">
                                <span>{{ index + 1 }}. </span>
                                <span v-html="item.question"></span>({{typeList[item.type]}})<span></span>
                            </div>
                            <!-- 非问答 -->
                            <div v-if="item.type !== 'subjective' && submitArr.length">
                                <div
                                    class="unitTestBtn"
                                    v-for="(option, optionIndex) in item.option"
                                    :key="optionIndex"
                                >
                                    <div
                                        class="unitTestbg"
                                        @click="onOptionClick(item, index, option.code)"
                                        :style="{
                                            backgroundColor: submitArr[index].includes(option.code) ? '#24b880' : 'transparent',
											color: submitArr[index].includes(option.code) ? '#ffffff' : '#000',	
                                        }"
                                    >
                                        {{ option.code }}.
                                        <span v-html="option.value" style="margin-left: 10px"></span>
                                    </div>
                                </div>
                            </div>
                            <!-- 问答 -->
                            <div v-if="item.type === 'subjective' && submitArr.length">
                                <Input
                                    v-model="submitArr[index][0]"
                                    type="textarea"
                                    :rows="8"
                                    :placeholder="$t('studentWeb.exam.inputAnswers')"
                                />
                            </div>
                            <Divider v-if="index != surveyInfo.items.length - 1" />
                        </div>
                        <br />
                        <br />
                        <button class="uploadBtn" @click="submitMessage()">
                            <svg-icon icon-class="quesnaire" class="uloadBtn-icon" />
                            <span>{{ $t("survey.studentWeb.submit") }}</span>
                        </button>
                    </div>
                </vuescroll>
            </div>
            
        </div>
    </div>
</template>

<script>
    import BlobTool from '@/utils/blobTool.js';
export default {
    data(vm) {
        return {
            typeList: {
                single: vm.$t("survey.questionaire.single"),
                multiple: vm.$t("survey.questionaire.multiple"),
                judge: vm.$t("survey.questionaire.judge"),
                subjective: vm.$t("survey.questionaire.subjective"),
            },
            listShow: [],
            surveyInfo: {},
			activeIndex:0,
            submitArr: [], //填写的数据
            questionnaireId:'', //问卷id
			curSurvey:null,
            alreadyAnswered: false, //提交状态
        }
    },
        created() {
            this.getquestionnaire()
            //this.sentSelectedEventTitle(this.listShow[0])
    },
    methods: {
        //获取当前教师的问卷名称
        getquestionnaire() {
            this.$api.jyzx.getAllActivity({type: "Survey"}).then(
                res => {
                    this.listShow = res.datas.filter(i => i.sType !== 'train').reverse()
                    if (this.listShow.length != 0) {
                        this.sentSelectedEventTitle(this.listShow[0])
                        this.activeIndex = 0
                    }
                },
            )
        },
        // 获取blob里的问卷内容
        getBlobItems(qnItem) {
            return new Promise(async (resolve, reject) => {
                let blobHost = this.$tools.getBlobHost()
                let cntr = qnItem.scope === 'school' ? qnItem.school : qnItem.code.replace('Survey-','')
                let sasString = await this.$tools.getBlobSas(cntr)
                let fullIndexJsonPath = blobHost + '/' + cntr + qnItem.blob + sasString
                // 根据试卷的Blob地址 去读取JSON文件
                let promiseArr = []
				// 如果是区级
				if(qnItem.owner === 'area'){
					blobHost = this.$store.state.user.osblob_uri
					sasString = { sas : '?' + this.$store.state.user.osblob_sas }
				}
                let indexJson = JSON.parse(await this.$tools.getFile(blobHost + qnItem.blob + sasString.sas))
                if(indexJson.slides.length) {
                    for (let item of indexJson.slides) {
                        promiseArr.push(new Promise(async (r, j) => {
                            try {
                                let itemJson = JSON.parse(await this.$tools.getFile(blobHost + item + sasString.sas))
                                r(itemJson)
                            } catch (e) {
                                j(e)
                            }
                        }))
                    }
                    Promise.all(promiseArr).then(result => {
                        resolve(result)
                    }).catch(err => {
                        reject(err)
                    })
                }else{
                    resolve([])
                }
                
            })
        },
        // 获取blob里的问卷信息
        getBlobJsonFile(indexJsonUrl) {
            return new Promise(async (resolve, reject) => {
                try {
                    let itemJson = JSON.parse(await this.$tools.getFile(indexJsonUrl))
                    resolve(itemJson)
                } catch(e) {
                    this.$Message.error(this.$t('studentWeb.queNaire.fileErr'))
                    reject(e)
                }
            })
        },
        // 展示当前活动
        async sentSelectedEventTitle(item, index) {
            this.alreadyAnswered = false
			this.activeIndex = index
            this.questionnaireId = item.id
			this.curSurvey = item
            this.submitArr = []
            let params = {
                "id": item.id,
                "code": item.scode
            }
			let isAnswerd = await this.isAnswerd(params)
            if(!isAnswerd) {
                this.$api.jyzx.getSurveyInfo(params).then(
                    async res => {
                        if (res) {
                            if(res.status == 404) {
                                this.$Modal.confirm({
                                    title: "问卷已被删除，是否删除此条记录？",
                                    okText: "删除",
                                    cancelText: "取消",
                                    onOk: () => {
                                        this.delActivity(item)
                                    }
                                })
                            } else if(res.status == 200) {
                                this.surveyInfo = res.survey
                                this.surveyInfo.items = await this.getBlobItems(res.survey)
                                this.submitArr = []
                                this.surveyInfo.items.forEach(i => {
                                    this.submitArr.push([])
                                })
                                this.$forceUpdate()
                            }
                        }
                    }
                )
            } else {
                this.alreadyAnswered = true
            }
        },
        // 删除不存在的问卷
        delActivity(item) {
            let param = {
                "id": item.id,
                "code": item.code,
                "role": "teacher"
            }
            this.$api.jyzx.delActivity(param).then(res => {
                if(res) {
                    if(res.status == 200) {
                        this.$Message.success('问卷已删除！')
                        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
                        }
                        console.log(listIndex);
                        this.sentSelectedEventTitle(this.listShow[listIndex], listIndex)
                    }
                }
            })
        },
        // 判断当前学生是否已作答该问卷
        isAnswerd(params){
            return new Promise((r,j) => {
                this.$api.studentWeb.isAnswerd(params).then(async res => {
                    r(res.answered)
                })
            })
        },
        // 提交问卷
        submitMessage() {
			if(this.submitArr.some(i => i === '' || i.length === 0)){
				this.$Message.warning(this.$t("jyzx.activity.message2"))
				return
			}
            this.$api.jyzx.answerSurvey(
                {
                    "userid": this.$store.state.userInfo.TEAMModelId,
                    "code": this.surveyInfo.code,
                    "id": this.surveyInfo.id,
                    "record": this.submitArr
                }
            ).then(
                res => {
					this.$Message.success(this.$t("jyzx.activity.success2"))
					this.getquestionnaire()
                },
                error => {
                }
            )
        },
        // 非问答的答案
        onOptionClick(item, index, code) {
			/* if(this.curSurvey.time !== 0){
				this.$Message.warning(this.$t("jyzx.activity.message3"))
				return
			} */
            if (this.submitArr[index].includes(code)) {
                this.submitArr[index].splice(this.submitArr[index].indexOf(code), 1)
            } else {
                if (item.type !== "multiple") {
                    this.submitArr[index] = []
                    this.submitArr[index].push(code)
                } else {
                    this.submitArr[index].push(code)
                }
            }
            this.$forceUpdate()
        },
        // 获取年月日
        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}`
        },
        
    },
}
</script>

<style lang="less" scoped>
.jyzx-ques {
    display: flex;
    height: 100%;
	// font-family: 'NotoSerif', '微软正黑体', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Sans-serif;

    .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: 22px;
            margin-right: 20px;
            clear: both;
        }
        &-type {
            width: 15%;
            display: flex;
            justify-content: center;
            flex-direction: column;

            .isAllowRetry {
                color: #fff;
                background-color: #64ae16;
                border: none;
            }

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

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

        .servey-title{
            font-size: 25px;
            font-weight: bold;
        }

        .survey-item {
            margin: 0% 3%;
            .ivu-input {
                margin: 10px 0;
                border-color: #9c9c9c;
            }
        }

        .unitTestBtn {
            display: block !important;
            margin: 0px;
            width: 100% !important;

            .unitTestbg {
                cursor: pointer;
                padding: 10px;
                background-color: #fff;
                border-radius: 4px;
                border: 1px solid #8f8f8f;
                margin-top: 10px;
                display: flex;
            }

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

            input[type="checkbox"]:checked ~ .unitTestbg,
            input[type="radio"]:checked ~ .unitTestbg {
                background-color: #24b880 !important;
                border: none;
                color: #fff;
                font-weight: bolder;
            }
        }

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

            .option-wrapper {
                margin-bottom: 15px;
                display: flex;
                align-items: center;
                // font-weight: 600;

                .ivu-checkbox {
                    margin-right: 5px;
                }
            }
        }
    }
}
</style>