<template>
    <div class="ev-list-container" style="width: 98%; margin: 0 auto">
        <!-- 筛选部分 -->
        <div class="filter-wrap">
            <div class="filter-item">
                <span class="filter-title">来源:</span>
                <RadioGroup v-model="filterOrigin" type="button" @on-change="filterOriginChange">
                    <Radio :label="userId">个人题库</Radio>
                    <Radio :label="schoolCode" v-if="hasSchool">校本题库</Radio>
                </RadioGroup>
            </div>
            <div class="filter-item" v-show="filterOrigin == schoolCode">
                <span class="filter-title">学段:</span>
                <RadioGroup v-model="filterPeriod" type="button" @on-change="filterPeriodChange">
                    <Radio v-for="(item, index) in periodList" :key="index" :label="index">{{ item.name }}</Radio>
                </RadioGroup>
            </div>
            <div class="filter-item" v-show="filterOrigin == schoolCode">
                <span class="filter-title">年级:</span>
                <CheckboxGroup v-model="filterGrade" border @on-change="filterGradeChange">
                    <Checkbox lable="all">全部</Checkbox>
                    <Checkbox v-for="(item, index) in gradeList" :key="index" :label="index">{{ item }}</Checkbox>
                </CheckboxGroup>
            </div>
            <div class="filter-item" v-show="filterOrigin == schoolCode">
                <span class="filter-title">科目:</span>
                <CheckboxGroup v-model="filterSubject" border @on-change="filterSubjectChange">
                    <Checkbox lable="all">全部</Checkbox>
                    <Checkbox v-for="(item, index) in subjectList" :key="index" :label="item.id">{{ item.name }}</Checkbox>
                </CheckboxGroup>
            </div>
            <div class="filter-item">
                <span class="filter-title">题型:</span>
                <CheckboxGroup v-model="filterType" border @on-change="filterTypeChange">
                    <Checkbox label="all">全部</Checkbox>
                    <Checkbox label="single">单选</Checkbox>
                    <Checkbox label="multiple">多选</Checkbox>
                    <Checkbox label="judge">判断</Checkbox>
                    <Checkbox label="complete">填空</Checkbox>
                    <Checkbox label="subjective">问答</Checkbox>
                    <Checkbox label="compose">综合</Checkbox>
                </CheckboxGroup>
            </div>
            <div class="filter-item">
                <span class="filter-title">难度:</span>
                <CheckboxGroup v-model="filterDiff" border @on-change="filterDiffChange">
                    <Checkbox label="all">全部</Checkbox>
                    <Checkbox v-for="(item, index) in exersicesDiff" :key="index" :label="index + 1">{{ item }}</Checkbox>
                </CheckboxGroup>
            </div>
            <div class="filter-item">
                <span class="filter-title">层次:</span>
                <CheckboxGroup v-model="filterField" border @on-change="filterFieldChange">
                    <Checkbox label="all">全部</Checkbox>
                    <Checkbox :label="1">知识</Checkbox>
                    <Checkbox :label="2">理解</Checkbox>
                    <Checkbox :label="3">应用</Checkbox>
                    <Checkbox :label="4">分析</Checkbox>
                    <Checkbox :label="5">综合</Checkbox>
                    <Checkbox :label="6">评鉴</Checkbox>
                </CheckboxGroup>
            </div>
            <div class="filter-item">
                <span class="filter-title">排序:</span>
                <RadioGroup v-model="filterSort" type="button" @on-change="filterSortChange">
                    <Radio label="createTime">
                        新增时间
                        <Icon type="md-arrow-round-down" />
                    </Radio>
                    <Radio label="useCount">
                        使用次数
                        <Icon type="md-arrow-round-down" />
                    </Radio>
                </RadioGroup>
            </div>
        </div>
        <!-- 筛选部分结束 -->
        <!-- 题目列表部分 -->
		<Loading :top="100" v-show="dataLoading" hideMask></Loading>
        <div v-if="exerciseList.length === 0" class="no-data-text">
            <img src="@/assets/icon/no_data_evaluation.png" width="120" />
            <span style="margin-top: 15px; color: #808080">暂无数据</span>
        </div>
        <div class="content-wrap" ref="mathJaxContainer" v-else>
            <div class="exercise-item" v-for="(item, index) of exerciseList" :key="index" @click="onQuestionToggle(index, item.id, $event)">
                <!-- 题干部分 -->
                <div class="item-question">
                    <div>
                        <div class="item-question-order">
                            {{ pageSize * (pageNum - 1) + index + 1 }} :
                        </div>
                        <div class="item-question-text" v-html="item.question" @click="onRichTextClick($event)"></div>
                    </div>
                    <span class="item-btn-toggle">
                        <Icon :type="
                              collapseList.indexOf(index)>
                            -1
                            ? 'ios-arrow-dropup'
                            : 'ios-arrow-dropdown'
                            " />
                    </span>
                </div>
                <!-- 选项部分 -->
                <div v-for="(option, optionIndex) in item.option" :key="optionIndex" class="item-options">
                    <div class="item-option-content">
                        <div class="item-option-order">
                            {{ String.fromCharCode(64 + parseInt(optionIndex + 1)) }} :
                        </div>
                        <div class="item-option-text" v-html="option.value" @click="onRichTextClick($event)"></div>
                    </div>
                </div>
                <transition name="slide">
                    <div v-show="collapseList.indexOf(exerciseList.indexOf(item)) > -1" class="toggle-area">
                        <div v-if="item.type !== 'compose'">
                            <!-- 答案展示部分 -->
                            <div class="item-explain">
                                <span class="explain-title">【答ㅤ案】</span>
                                <div class="item-explain-details">
                                    <!-- 问答题答案 -->
                                    <div v-if="item.type === 'subjective' || item.type === 'complete'">
                                        <span v-for="(answer, index) in item.answer" :key="index" v-html="item.answer.length ? answer : '未设置答案'"></span>
                                    </div>
                                    <!-- 其余题型答案 -->
                                    <div v-else>
                                        <span :class="[item.type === 'complete' ? 'item-answer-item' : '',]" v-for="(answer, index) in item.answer" :key="index">{{ answer }}</span>
                                    </div>
                                </div>
                            </div>
                            <!-- 解析部分 -->
                            <div class="item-explain">
                                <span class="explain-title">【解ㅤ析】</span>
                                <div class="item-explain-details" @click="onRichTextClick($event)">
                                    <span v-html="item.explain || '暂无解析'"></span>
                                </div>
                            </div>
                            <!-- 知识点部分 -->
                            <div class="item-explain">
                                <span class="explain-title">【知识点】</span>
                                <div class="item-explain-details">
                                    <span v-if="!item.points">暂未绑定知识点</span>
                                    <div v-else>
                                        <span v-for="(point, index) in item.points" class="item-point-tag" :key="index">
                                            {{ point }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 如果是综合题 则加载子题渲染组件 -->
                        <div v-else>
                            <BaseChild :children="item.children"></BaseChild>
                        </div>
                    </div>
                </transition>
                <!-- 底部题目操作栏 -->
                <div class="item-tools">
                    <span class="item-tools-info">题型：{{ exersicesType[item.type] }}</span>
                    <span class="item-tools-info">难度：{{ exersicesDiff[item.level - 1] }}</span>
                    <span class="item-tools-info">使用次数：{{ item.usageCount || 0 }} 次</span>

                    <Button type="text" @click.stop="chooseExercise(item)" :icon="ids.indexOf(item.id) > -1 ? 'md-remove' : 'md-add'" style="margin-right: 10px">
                        {{ids.indexOf(item.id) > -1 ? '移除' : '选题'}}
                    </Button>
                </div>
            </div>
        </div>

        <!-- 底部分页区域 -->
        <Page :total="totalNum" show-sizer show-total :page-size="pageSize" :current="pageNum" @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="[5, 10, 15, 20]" />
    </div>
</template>
<script>
import blobTool from "@/utils/blobTool.js";

export default {
    data() {
        return {
            userId: "",
            schoolCode: "",
            dataLoading: false,
            exerciseList: [],
            schoolInfo: {},
            exersicesType: this.$GLOBAL.EXERCISE_TYPES(),
            exersicesDiff: this.$GLOBAL.EXERCISE_DIFFS(),
            exersicesField: this.$GLOBAL.EXERCISE_LEVELS(),
            diffColors: ["#32CF74", "#E8BE15", "#F19300", "#EB5E00", "#D30000"],
            filterType: ["all"],
            filterOrigin: "",
            filterDiff: ["all"],
            filterField: ["all"],
            filterSort: "createTime",
            filterPeriod: 0,
            filterGrade: [false],
            filterSubject: [false],
            totalNum: 0,
            pageSize: 10,
            pageNum: 1,
            currentPage: 1,
            collapseList: [],
            periodList: [],
            gradeList: [],
            subjectList: [],
            filterParams: {},
            allPointList: [],
            originData: [],
            playAudioModal: false,
            playVideoModal: false,
            curAudioSrc: "",
            curAudioName: "",
            curVideoSrc: "",
            curVideoName: "",
            selectItems: []
        };
    },
    created() {
        this.getSchoolInfo()
    },
    methods: {
        /**挑选试题 */
        chooseExercise(item) {
            if(this.ids.indexOf(item.id) == -1){
                this.selectItems.push(item) //添加题目
            }else{
                for(let i = 0; i < this.selectItems.length; i++){
                    if(this.selectItems[i].id == item.id){
                        this.selectItems.splice(i,1) //移除
                        break
                    }
                }
            }
            this.$emit('chooseQuChange',this.selectItems)
        },
        /* 音频弹窗切换事件 */
        onAudioModalChange(val) {
            if (!val) {
                this.$refs.audioPlayer.onCloseAudio();
            }
        },

        /* 视频弹窗切换事件 */
        onVideoModalChange(val) {
            if (!val) {
                this.$refs.videoPlayer.onCloseAudio();
            }
        },

        /* 音频点击播放事件 */
        onRichTextClick(e) {
            // e.stopPropagation()
            let sasString = JSON.parse(
                decodeURIComponent(localStorage.getItem("user_profile"))
            ).blob_sas;
            // console.log(JSON.parse(decodeURIComponent(localStorage.getItem('school_profile'))))
            if (e.srcElement.classList[0] === "richText-audio") {
                this.playAudioModal = true;
                this.curAudioSrc = e.srcElement.dataset.url;
                this.curAudioName = e.srcElement.dataset.name;
            } else if (e.srcElement.classList[0] === "richText-video") {
                this.playVideoModal = true;
                this.curVideoSrc =
                    e.srcElement.dataset.url.split("?")[0] + "?" + sasString;
                console.log(this.curVideoSrc);
                this.curVideoName = e.srcElement.dataset.name;
            }
        },

        /** 获取区班校信息 */
        getSchoolInfo() {
            this.dataLoading = true;
            this.$store.dispatch("user/getSchoolProfile").then((res) => {
                let schoolBaseInfo = res.school_base;
                if (schoolBaseInfo) {
                    this.schoolInfo = schoolBaseInfo;
                    this.schoolCode = schoolBaseInfo.id;
                    this.userId = this.$store.state.userInfo.TEAMModelId;
                    this.filterOrigin = this.$store.state.userInfo.TEAMModelId;
                    this.periodList = schoolBaseInfo.period;
                    console.log('periodList:', this.periodList)
                    if (schoolBaseInfo.period.length) {
                        this.gradeList = schoolBaseInfo.period[0].grades;
                        this.subjectList = schoolBaseInfo.period[0].subjects;
                    }
                    this.doFilter();
                }
            });
        },

        /* 获取BLOB所有试题LIST */
        async getBlobOrigin() {
            // 获取初始化Blob需要的数据
            let sasData = await this.$tools.getPrivateSas();
            //初始化Blob
            let containerClient = new blobTool(
                sasData.url,
                sasData.name,
                sasData.sas,
                "private"
            );
            // 等待blob的返回结果
            containerClient
                .listBlob({
                    prefix: "paper",
                })
                .then(
                    (res) => {
                        console.log(res);
                    },
                    (err) => {
                        this.$Message.error("API Error");
                    }
                );
        },

        /** 执行筛选条件获取数据 */
        doFilter() {
            this.dataLoading = true;
            this.collapseList = []; // 所有详情都收起来
            /** 定义查询接口的参数规格 */
            this.filterParams = {
                // '@CURRPAGE': this.pageNum,
                // '@PAGESIZE': this.pageSize,
                "@DESC": this.filterSort,
                code: this.filterOrigin,
                periodId: this.filterOrigin == this.schoolCode ? [this.periodList[this.filterPeriod].id] : [],
                "gradeIds[*]": this.filterOrigin == this.schoolCode ? this.deleteFalse(this.filterGrade).map(i => i + '') : [],
                subjectId: this.filterOrigin == this.schoolCode ? this.deleteFalse(this.filterSubject) : [],
                level: this.deleteFalse(this.filterDiff),
                type: this.deleteFalse(this.filterType),
                field: this.deleteFalse(this.filterField),
                scope: this.curScope,
            };
            this.getExerciseList(this.filterParams);
        },

        /**
         * 获取最新题库列表
         * @param data
         */
        async getExerciseList(data) {
            let that = this;
            this.$api.newEvaluation.FindExerciseList(data).then(async (res) => {
                let list = res.items;
                /* 获取试题总数 */
                this.totalNum = res.items.length;
                /* 查找当前页面所有知识点ID换名称 */
                // this.getPointsByIds(this.getPointIds(list)).then(res => {
                // 	this.allPointList = res
                // })
                this.exerciseList = list;
                this.originData = list;
                this.pageChange(1);

                setTimeout(() => {
                    that.dataLoading = false;
                }, 1000);
            });
        },

        /**
         * 拿到当前页面所有知识点集合
         * @param arr
         */
        getPointIds(arr) {
            let ids = [];
            arr.forEach((i) => {
                ids = ids.concat(i.points);
            });
            return [...new Set(ids)];
        },

        /**
         * 根据知识点id集合换取知识点对象集合
         * @param ids
         */
        getPointsByIds(ids) {
            if (typeof ids[0] !== "string") {
                ids = ids.map((item) => item.id);
            }
            return new Promise((r, j) => {
                if (ids.length) {
                    this.$api.knowledge
                        .FindKnowledgebyId(ids)
                        .then((res) => {
                            if (!res.error && res.result.data.length) {
                                r(res.result.data);
                            } else {
                                r([]);
                            }
                        })
                        .catch((err) => {
                            j(err);
                        });
                } else {
                    r([]);
                }
            });
        },

        /**
         * 题干展开与收缩
         * @param index
         * @param id
         */
        onQuestionToggle(index, id, e) {
            let curClassName = e.target.className;
            console.log(curClassName);
            if (
                curClassName === "item-tools" ||
                curClassName === "richText-video" ||
                curClassName === "richText-audio"
            )
                return;
            e.stopPropagation();
            let listIndex = this.collapseList.indexOf(index);
            if (listIndex > -1) {
                this.collapseList.splice(listIndex, 1);
            } else {
                this.collapseList.push(index);
                let exerciseItemDom = e.path.filter(
                    (i) => i.className === "exercise-item"
                );
            }

            this.$emit("toggleChange", this.collapseList);
        },

        /**
         * 筛选学段条件
         * @param val
         */
        filterPeriodChange(val) {
            // this.filterPeriod = this.periodList[val].periodCode
            this.gradeList = this.schoolInfo.period[val].grades;
            this.subjectList = this.schoolInfo.period[val].subjects;
            this.filterGrade = [false];
            this.filterSubject = [false];
            this.doFilter();
        },

        /**
         * 筛选年级
         * @param val
         */
        filterGradeChange(val) {
            if (val.length > 1 && val.indexOf(false) === 0) {
                this.filterGrade.splice(val.indexOf(false), 1);
            } else if (val.indexOf(false) > -1 || val.length === 0) {
                this.filterGrade = [false];
            }
            this.doFilter();
        },

        /**
         * 筛选科目
         * @param val
         */
        filterSubjectChange(val) {
            if (val.length > 1 && val.indexOf(false) === 0) {
                this.filterSubject.splice(val.indexOf(false), 1);
            } else if (val.indexOf(false) > -1 || val.length === 0) {
                this.filterSubject = [false];
            }
            this.doFilter();
        },

        /**
         * 根据题库加载题目
         * @param val
         */
        filterOriginChange(origin) {
            this.filterOrigin = origin;
            this.doFilter();
        },

        /**
         * 筛选题型
         * @param val
         */
        filterTypeChange(val) {
            if (val.length > 1 && val.indexOf("all") === 0) {
                this.filterType.splice(val.indexOf("all"), 1);
            } else if (val.indexOf("all") > -1 || val.length === 0) {
                this.filterType = ["all"];
            }
            this.doFilter();
        },

        /**
         * 筛选难度
         * @param val
         */
        filterDiffChange(val) {
            if (val.length > 1 && val.indexOf("all") === 0) {
                this.filterDiff.splice(val.indexOf("all"), 1);
            } else if (val.indexOf("all") > -1 || val.length === 0) {
                this.filterDiff = ["all"];
            }
            this.doFilter();
        },

        /**
         * 筛选认知层次
         * @param val
         */
        filterFieldChange(val) {
            if (val.length > 1 && val.indexOf("all") === 0) {
                this.filterField.splice(val.indexOf("all"), 1);
            } else if (val.indexOf("all") > -1 || val.length === 0) {
                this.filterField = ["all"];
            }
            this.doFilter();
        },

        /**
         * 排序条件更换
         * @param val
         */
        filterSortChange(val) {
            this.doFilter();
        },

        /**
         * 删除筛选条件里面的False值与All值
         * @param arr
         */
        deleteFalse(arr) {
            let list = JSON.parse(JSON.stringify(arr));
            list.forEach((item, index) => {
                if ((!item || item === "all") && item !== 0 ) list.splice(index, 1);
            });
            return list;
        },

        /**
         * 切换页码操作
         * @param page
         */
        async pageChange(page) {
            this.pageNum = page;
            let start = this.pageSize * (page - 1);
            let end = this.pageSize * page;
            // 拿到当前页码需要展示的数据
            let simpleList = this.originData.slice(start, end);
            try {
                // 执行试题换取完整JSON数据
                this.exerciseList = await this.$evTools.getFullItem(simpleList);
                this.currentPage = page;
            } catch (e) {
                console.log(e);
            }
        },

        /**
         * 切换每页显示数量
         * @param val
         */
        pageSizeChange(val) {
            this.pageSize = val;
            this.pageChange(1);
        },

    },
    mounted() {
        // 公式渲染
        this.$nextTick(() => {
            // window.MathJax.Hub.Queue([
            //     "Typeset",
            //     MathJax.Hub,
            //     this.$refs.mathJaxContainer,
            // ]);
        });
    },
    computed: {
        headers() {
            let hd = {};
            hd["Authorization"] = "Bearer " + localStorage.getItem("token");
            return hd;
        },
        curScope() {
            return this.filterOrigin === this.$store.state.userInfo.schoolCode ?
                "school" :
                "private";
        },
        hasSchool() {
            return this.$store.state.userInfo.hasSchool;
        },
        //已选题目的id
        ids() {
            return this.selectItems.map(item => {
                return item.id
            })
        }
    },
};
</script>
<style scoped lang="less">
@import "./ExerciseList.less";
</style>

<style>
.circle {
    border: solid 1px red;
    background-color: red;
    border-radius: 50%;
    width: 50px;
    height: 50px;
}

.slide-enter-active {
    transition: all 0.3s ease;
}

.slide-leave-active {
    transition: all 0.3s ease;
}

.slide-enter,
.slide-leave-to {
    transform: translateY(10px);
    opacity: 0;
}
.filter-item .ivu-checkbox{
    display: none;
}
</style>
