<template>
    <div class="component-questionnaire">
        <!-- 问卷的基本操作栏 -->
        <p class="qn-title">{{currentQn.name}}</p>
        <p class="qn-description" v-html="currentQn.description"></p>
        <div class="qn-item-box">
            <div v-if="items.length === 0" class="no-data-text">
                <img src="@/assets/icon/no_data.svg" width="120" />
                <span style="margin-top:15px;color:#808080">{{ $t('survey.questionaire.noItemData') }}</span>
            </div>
            <!-- 问卷题目单元 -->
            <draggable class="list-group" tag="div" v-model="items" v-bind="dragOptions" @start="drag = true" @end="onDragEnd" v-else>
                <transition-group type="transition" :name="!drag ? 'flip-list' : null">
                    <div class="qn-item" v-for="(item,index) in items" :key="index">
                        <Icon v-if="isExam" :type="answerStatus[index] ? 'md-checkmark' : 'md-close'" :color="answerStatus[index] ? '#19be6b' : '#ed4014'" class="answer-status-icon"/>
                        <div class="qn-item-content">
                            <!-- 题干 -->
                            <p class="qn-stem">
                                <span style="color: red;" v-show="item.required">* </span>
                                <span>{{ index + 1 }}. </span>
                                <span v-html="item.question"></span>
                                <span>( {{ typeList[item.type] }} )</span>
                            </p>
                            <!-- 单选题-选项 -->
                            <span v-if="answer[index]">
                                <RadioGroup v-model="answer[index][0]" v-if="item.type === 'single' || item.type === 'judge'">
                                    <Radio v-for="(option,optionIndex) in item.option" :key="optionIndex" :label="option.code" disabled>
                                        <span>
                                            {{getSimpleText(option.value)}}
                                        </span>
                                    </Radio>
                                </RadioGroup>
                                <!-- 多选题-选项 -->
                                <CheckboxGroup v-model="answer[index]" v-else-if="item.type === 'multiple'">
                                    <Checkbox v-for="(option,optionIndex) in item.option" :key="optionIndex" :label="option.code" disabled>
                                        <span>
                                            {{getSimpleText(option.value)}}
                                        </span>
                                    </Checkbox>
                                </CheckboxGroup>
                                <!-- 客观题 -->
                                <div v-else-if="item.type === 'subjective'">
                                    <p v-if="answer[index]">{{answer[index].join('')}}</p>
                                </div>
                            </span>
                            <p v-show="isExam" v-if="item.answer" class="standard-answer">参考答案：{{item.answer.join('')}}</p>
                            <!-- <span v-else>
                                <RadioGroup v-model="answer[index]" v-if="item.type === 'single' || item.type === 'judge'">
                                    <Radio v-for="(option,optionIndex) in item.option" :key="optionIndex" :label="option.code" disabled>
                                        <span>
                                            {{getSimpleText(option.value)}}
                                        </span>
                                    </Radio>
                                </RadioGroup>
                            </span> -->

                        </div>
                        <!-- <div class="qn-item-charts" v-if="currentQn.progress === 'finish' && item.type !== 'subjective'">
							<BaseMiniBar :barId="'minibar' + index" :barData="item.result || []"></BaseMiniBar>
						</div> -->
                    </div>
                </transition-group>
            </draggable>
        </div>
    </div>
</template>
<script>
import draggable from "vuedraggable"
export default {
    components: {
        draggable,
    },
    props: ["survey", "answer"],
    data(vm) {
        return {
            isExam:false,
            answerStatus: [],
            curIndexList: [],
            curItem: null,
            isUpdate: false,
            barData: [],
            editIndex: null,
            editable: false,
            isShowAnalysis: false,
            isShowAllAnalysis: false,
            addModal: false,
            drag: false,
            radioModel: '',
            multipleModel: [],
            items: [],
            itemAnswers: [],
            curType: '',
            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')
            }
        };
    },
    created() { },
    methods: {
        // 拖拽完成之后
        onDragEnd() {
            this.drag = false
        },

        async getFullSurvey(surveyItem) {
            this.items = await this.getBlobItems(surveyItem)
            console.log(this.items)
            // 如果是评测需要判断作答对错(只有客观题)
            if (this.survey.code.includes('TrExam') && this.answer) {
                this.isExam = true
                this.answerStatus = new Array(this.items.length)
                this.items.forEach((item, index) => {
                    let flag = true
                    if (item.answer.length == this.answer[index].length) {
                        this.answer[index].forEach(a => {
                            if (!item.answer.includes(a)) {
                                flag = false
                            }
                        })
                    } else {
                        flag = false
                    }
                    this.answerStatus[index] = flag
                })
            }
        },

        // 提取富文本内容中的文本
        getSimpleText(html) {
            var r = /<(?!img|video|audio).*?>/g;
            return html.replace(r, "").replace(/&nbsp;/g, '　');
        },


        // 获取blob里的试题数据
        getBlobItems(qnItem) {
            return new Promise(async (resolve, reject) => {
                console.log(qnItem);
                // 根据试卷的Blob地址 去读取JSON文件
                // let blobHost = JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri
                let sasString = await this.$tools.getSchoolSas()
                let blobHost = qnItem.owner === 'area' ? this.$store.state.user.osblob_uri : JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri
                console.log('blob地址',blobHost)
                let sas = qnItem.owner === 'area' ?  ('?' + this.$store.state.user.osblob_sas) : sasString.sas
                let promiseArr = []
                let indexJson = await this.getBlobJsonFile(qnItem.owner, qnItem.blob)
                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 + sas))
                                r(itemJson)
                            } catch (e) {
                                j(e)
                            }
                        }))
                    }
                    Promise.all(promiseArr).then(result => {
                        resolve(result)
                    }).catch(err => {
                        reject(err)
                    })
                } else {
                    resolve([])
                }

            })
        },

        // 获取blob里的试题数据
        getBlobJsonFile(owner, url) {
            return new Promise(async (resolve, reject) => {
                // let blobHost = scope === 'private' ? JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri : JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri
                // // 根据试卷的Blob地址 去读取JSON文件
                // let sasString = scope === 'private' ? await this.$tools.getPrivateSas() : await this.$tools.getSchoolSas()

                let sasString = await this.$tools.getSchoolSas()
                let blobHost = owner === 'area' ? this.$store.state.user.osblob_uri : JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri
                let sas = owner === 'area' ?  ('?' + this.$store.state.user.osblob_sas) : sasString.sas
                try {
                    let itemJson = JSON.parse(await this.$tools.getFile(blobHost + url + sas))
                    resolve(itemJson)
                } catch (e) {
                    reject(e)
                }
            })
        },
    },
    computed: {
        dragOptions() {
            return {
                animation: 200,
                group: "description",
                disabled: this.currentQn.progress !== 'pending',
                ghostClass: "ghost"
            };
        }
    },
    watch: {
        survey: {
            handler(n, o) {
                if (n) {
                    console.log('问卷或评测数据', n)
                    this.currentQn = n
                    this.getFullSurvey(n)
                }
            },
            immediate: true,
            deep: true
        },
        answer: {
            handler(n, o) {
                if (n) {
                    console.log('作答数据', n)
                }
            },
            deep: true,
            immediate: true
        }

    }
};
</script>

<style lang="less" scope>
@import "./SurveyDetail.less";
</style>

