<template>
    <div class="question-bank">
        <div class="top">
            <div class="top-left flex-items">
                <span class="subject-title only-line-1">试题查看</span>
            </div>
        </div>
        <div class="main">
            <!-- 左侧菜单树 -->
            <div class="main-left">
                <div class="bordr-bottom-gray p-8 font-bold">
                    目录：
                </div>
                <div class="bordr-bottom-gray p-8 only-line-1 chapter-title">
                    <!-- <a-tooltip>
                        <template slot="title">
                            点击更改目录
                        </template> -->
                    <span class="only-line-1">{{record.target}}</span>
                    <!-- </a-tooltip> -->
                </div>
                <div class="bordr-bottom-gray p-8 font-bold">
                    试题（共{{questionData.length}}题）：
                </div>
                <div class="nav-list">
                    <div :class="['nav-item',{'nav-active':index==activeNum?true:false}]"
                        v-for="(item,index) in questionData.length" @click="changeActiveNum(index)" :key="index">{{item}}</div>
                </div>
            </div>
            <!-- 右侧试题框 -->
            <div class="main-right">
                <!-- 题目列表 -->
                <div class="question-list">
                    <div>
                        <a-button style="margin-left: 16px;margin-top:8px;" type="primary" @click="delMore">
                            删除
                        </a-button>
                        <span class="question-check-all">
                            <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">全选</a-checkbox>
                        </span>
                    </div>
                    <a-spin :spinning="spinning">
                        <template v-if="questionData.length>0">
                            <div class="question-item m16" v-for="(item,index) in questionData" :key="item.id"
                                :id="'index'+index">
                                <QuestionItem :ref="'QuestionItem'+index" :index="index" :data="item" :details="true"
                                    @callBack="_QuestionResolveTaskGetTaskQuestions">
                                    <template slot-scope="scope">
                                        <div class="flex-align bordr-bottom-gray p-8">
                                            <div>
                                                <span class="m-r8">
                                                    <a-checkbox :checked="checkedData[index].select" @change="(e)=>onChange(e,item,index)"></a-checkbox>
                                                </span>
                                                <span class="m-r16">{{index+1}}.</span>
                                                <span class="m-r36">题型：
                                                    <span
                                                        v-if="item.disciplineQuestionTypeName">{{item.disciplineQuestionTypeName}}</span>
                                                    <span style="color:red" v-else>未解析到题型，请手动修改题型</span>
                                                </span>
                                                <span class="m-r36">难度：{{toStr(item.difficulty)}}</span>
                                            </div>
                                            <div v-if="record.state==2">
                                                <a-popover class="m-r16" placement="bottom">
                                                    <template slot="content">
                                                        <div class="flex-column">
                                                            <span v-if="questionType.length>0" class="blue-hover"
                                                                style="line-height: 26px;"
                                                                v-for="(v,indexv) in questionType" :key="indexv"
                                                                @click="qusetionTypeChange(v,item,index)">{{v.name}}</span>
                                                            <span v-if="questionType.length==0"
                                                                style="color:red">无题型，请在基础数据中添加</span>
                                                        </div>
                                                    </template>
                                                    <a>修改题型</a>
                                                </a-popover>
                                                <a class="m-r16" @click="toEdit(item,index)">编辑</a>
                                                <a class="m-r16" @click="delQuestion(index)">删除</a>
                                            </div>
                                        </div>
                                    </template>
                                </QuestionItem>
                            </div>
                        </template>
                        <a-empty v-if="questionData.length===0" />
                    </a-spin>
                </div>
                <!-- 底部分页 -->
                <div class="paging-box">
                    <a-button v-if="record.state==2" :loading="loading" type="primary" class="m-r16"
                        @click="sureImport">确认导入</a-button>
                    <!-- <a-button type="primary" class="m-r16">重新导入</a-button> -->
                    <a-button class="m-r16" @click="goBack">取消</a-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import { QuestionResolveTaskGetTaskQuestions, QuestionResolveAffirmTaskQuestion, DisciplineQuestionTypeGetList } from '@/api/api'
    import QuestionItem from '@/components/Questions/QuestionItem'
    export default {
        components: {
            QuestionItem
        },
        data() {
            return {
                loading: false,
                spinning: false,
                activeNum: 0,
                taskID: '',
                record: {},
                checkedKeys: [],
                questionData: [],
                questionType: [],
                checkedData: [],
                indeterminate:false,
                checkAll: false
            }
        },
        mounted() {
            this.record = JSON.parse(this.$route.query.record);
            console.log(this.record, 'this.record')
            this.taskID = this.$route.query.taskID;
            this._DisciplineQuestionTypeGetList();

        },
        methods: {
            onCheckAllChange(e){
                const self = this;
                self.checkAll=e.target.checked;
                self.checkedKeys=[]
                self.checkedData.forEach(item=>{
                    item.select=e.target.checked;
                    if(e.target.checked){
                        self.checkedKeys.push(item.id);
                    }
                });
                self.indeterminate=false;
            },
            setCheckAllState(){
                const self = this;
                const selectCount= self.checkedData.filter(item=> item.select===true).length;
                self.indeterminate=selectCount>0&&selectCount<self.checkedData.length;
                self.checkAll = selectCount === self.checkedData.length;
            },
            toStr(num) {
                let str = ''
                switch (num) {
                    case 0: str = '容易';
                        break;
                    case 1: str = '较易';
                        break;
                    case 2: str = '中等';
                        break;
                    case 3: str = '较难';
                        break;
                    case 4: str = '困难';
                        break;
                }
                return str;
            },
            //获取学科细分题型
            _DisciplineQuestionTypeGetList() {
                let data = {
                    disciplineId: this.record.disciplineId || ''
                }
                DisciplineQuestionTypeGetList(data).then(res => {
                    console.log(res, '学科细分题型')
                    this.questionType = res;
                    this._QuestionResolveTaskGetTaskQuestions();
                })
            },
            //确认导入
            sureImport() {
                const self = this;
                this.loading = true;
                let params = {
                    taskId: this.taskID
                }
                let data = [];
                try {
                    this.questionData.forEach(item => {
                        if (!item.disciplineQuestionTypeId) {
                            this.$message.error('您还有题未设置题型，请完成设置！')
                            throw Error()
                        }
                        let obj = {
                            resoleTaskQuestionId: item.id,
                            disciplineQuestionTypeId: item.disciplineQuestionTypeId,
                            difficulty: item.difficulty,
                            knowledgePointList: self.record.targetType==1? [self.record.targetId] : [],//知识点
                            ariseTime: ''
                        }
                        data.push(obj)
                    })
                } catch (err) {
                    this.loading = false;
                    return;
                }
                console.log(data, 'data')
                QuestionResolveAffirmTaskQuestion(data, params).then(res => {
                    this.$message.success('导入成功')
                    this.loading = false;
                    this.record.state = 4
                }).catch(err => {
                    this.loading = false;
                })
            },
            //获取试题
            _QuestionResolveTaskGetTaskQuestions() {
                const self = this;
                this.spinning = true;
                let data = {
                    id: this.taskID
                }
                QuestionResolveTaskGetTaskQuestions(data).then(res => {
                    console.log(res, '导入的试题')
                    this.questionData = res.map(item => {
                        let arr = this.questionType.filter(v => v.id == item.disciplineQuestionTypeId);
                        if (arr.length > 0) {
                            item.questionCategory = arr[0].questionCategory;
                        }
                        self.checkedData.push({id: item.id,select:false});
                        return item;
                    });
                    this.spinning = false;
                }).catch(err => {
                    this.spinning = false;
                })
            },
            changeActiveNum(num) {
                this.activeNum = num;
                let views = this.$el.querySelector(`#index${num}`);
                console.log(views, 'views', num)
                if (views) views.scrollIntoView();
            },
            //修改题型
            qusetionTypeChange(v, item, index) {
                console.log(v, 'v')
                console.log(item, 'item')
                item._disciplineQuestionTypeName = item.disciplineQuestionTypeName; // 记录原来的值，当放弃编辑的时候数据要变回旧值
                item._disciplineQuestionTypeId = item.disciplineQuestionTypeId;
                item._questionCategory = item.questionCategory;
                item.disciplineQuestionTypeName = v.name;
                item.disciplineQuestionTypeId = v.id;
                item.questionCategory = v.questionCategory;
                this.toEdit(item, index, true);
            },
            toEdit(item, index, clear = false) {
                console.log(item, 'item toEdit')
                if (!item.hasOwnProperty('questionCategory')) {
                    this.$message.error('当前题目未设置题型，请先设置题型')
                    return;
                }
                this.$refs['QuestionItem' + index][0].toEdit(1, clear);
            },
            delQuestion(index) {
                let _this = this;
                this.$confirm({
                    okText: '确认',
                    cancelText: '取消',
                    mask: false,
                    title: `您确认要删除此题吗?`,
                    onOk() {
                        _this.$nextTick(() => {
                            _this.questionData.splice(index, 1);
                            _this.checkedData.splice(index, 1);
                            _this.setCheckAllState();
                        })
                        console.log(_this.questionData, '_this.questionData')
                    }
                });
            },
            goBack() {
                this.$router.go(-1);
            },
            onChange(e, data,index) {
                const self = this;
                let state = e.target.checked,
                    num = this.checkedKeys.indexOf(data.id);
                if (state) {
                    if (num === -1) {
                        this.checkedKeys.push(data.id)
                    }
                } else {
                    if (num > -1) {
                        this.checkedKeys.splice(num, 1)
                    }
                }
                self.checkedData[index].select=state;
                self.setCheckAllState();
            },
            delMore() {
                const self = this;
                const selectCount=self.checkedKeys.length;// self.checkedData.filter(item=> item.select===true).length;
                if (selectCount === 0) {
                    this.$message.error('请选择需要操作的题！')
                    return;
                }
                this.$confirm({
                    okText: '确认',
                    cancelText: '取消',
                    mask: false,
                    title: `您确认要删除这"${selectCount}"题吗?`,
                    onOk() {
                        self.$nextTick(() => {
                            self.questionData = self.questionData.filter(item => {
                                let id = item.id;
                                return self.checkedKeys.indexOf(id) == -1;
                            })
                            self.checkedData = self.checkedData.filter(item => {
                                let id = item.id;
                                return self.checkedKeys.indexOf(id) == -1;
                            })
                            self.checkedKeys = [];
                            self.setCheckAllState();
                        })
                    }
                });

            }
        }
    }
</script>

<style scoped lang="less">
    .question-bank {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
    }

    .top {
        width: 100%;
        height: 64px;
        border-bottom: 1px solid rgba(232, 232, 232, 1);
        display: flex;
        position: relative;
        box-sizing: border-box;
    }

    .top-left {
        width: 240px;
        height: 100%;
        padding: 16px;
        font-size: 20px;
        color: #333333;
        /* position: relative; */
    }

    .subject-icon {
        margin-right: 8px;
        cursor: pointer;
    }

    .subject-icon:hover {
        color: rgb(24, 144, 255);
    }

    .top-left:hover .subject-select-box {
        max-height: 1000px;
        display: block;
        overflow-y: auto;
        /* opacity: 1; */
    }

    .subject-select-box {
        font-size: 14px;
        width: 100%;
        max-height: 0px;
        position: absolute;
        top: 64px;
        left: 0;
        background-color: #fff;
        z-index: 99;
        transition: all 1s;
        /* opacity: 0; */
        /* display: none; */
        overflow: hidden;
    }

    .subject-title {
        flex: 1
    }

    .top-right {
        padding: 24px;
        flex: 1;
    }

    .main {
        display: flex;
        width: 100%;
        position: relative;
        height: calc(100% - 64px);
    }

    .main-left {
        width: 240px;
        height: 100%;
        border-right: 1px solid rgba(232, 232, 232, 1);
        overflow-y: auto;
    }

    /deep/.ant-tabs-nav .ant-tabs-tab {
        padding: 8px 16px;
        margin: 0;
    }

    /deep/.ant-tabs-bar {
        margin: 0;
    }

    .main-right {
        flex: 1;
        width: 100%;
        height: 100%;
        background-color: #f2f2f2;
        position: relative;
        overflow-y: hidden;
    }

    .paging-box {
        width: 100%;
        height: 50px;
        background-color: #fff;
        position: absolute;
        bottom: 0;
        right: 0;
        display: flex;
        flex-direction: row-reverse;
        align-items: center;
    }

    .question-list {
        flex: 1;
        width: 100%;
        height: calc(100% - 50px);
        overflow-y: auto;
        background-color: #ffffff;
        position: absolute;
    }

    .question-check-all{
        position: absolute;
        right: 16px;
        top: 16px;
    }

    .chapter-title {
        cursor: pointer;
    }

    .chapter-title:hover {
        color: #40a9ff;
    }

    .nav-list {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
    }

    .nav-item {
        cursor: pointer;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f2f2f2;
        margin-right: 8px;
        margin-bottom: 8px;
    }

    .nav-item:hover {
        color: #40a9ff;
    }

    .nav-active {
        background-color: #1890ff;
        color: #fff;
    }

    .nav-active:hover {
        color: #fff;
    }

    .question-item {
        background-color: #fff;
        border: 1px solid #f2f2f2;
    }
</style>