<template>
    <div class="question-bank">
        <div class="top">
            <div class="top-left flex-items">
                <a-icon type="menu-fold" class="subject-icon" @click="handleShowSubjectSelect" />
                <template>
                    <span
                        class="subject-title only-line-1"><a href="#" @click="handleShowSubjectSelect">{{activeSubject.educationCategory}}{{activeSubject.name}}</a></span>
                    <!-- 科目选择 -->
                    <div class="subject-select-box" v-bind:class="{'subject-select-box-show':isShowSubjectSelect}" @mouseleave="isShowSubjectSelect=false">
                        <div class="type-group">
                            <!-- <myListSelect v-for="(value,key) in $store.state.baseInfo.SubjectsGroup" :title="key" :data="value" :needAll="false" /> -->
                            <MultiListSelect v-if="activeSubject.id" :data="$store.state.baseInfo.SubjectsArr"
                                :needAll="false" :defaultSelect="[activeSubject.id]" @callBack="subjectCallBack" />
                        </div>
                    </div>
                </template>
            </div>
            <div class="top-right flex-align">
                <div>
                    <a-button :disabled="!ChapterId&&KnowledgePointIdList.length==0" class="m-r8"
                        @click="QuestionImport">试题导入</a-button>
                    <a-button :loading="templateLoading" :disabled="!activeSubject.id" class="m-r8" type="primary"
                        @click="GetQuestionTemplate">
                        获取下载模板</a-button>
                    <a-button type="primary" @click="toPath('intelligencePaper')">智能组题</a-button>
                </div>
                <a-input-search style="width:400px;" placeholder="搜索题干" enter-button @search="onSearch" />
            </div>
        </div>
        <div class="main">
            <!-- 左侧菜单树 -->
            <div class="main-left">
                <a-tabs default-active-key="1" @change="callback">
                    <a-tab-pane key="1" tab="章节">
                        <ChapterTree ref="ChapterTree" :activeSubject="activeSubject" @getQuestion="getQuestion"
                            @clearPoints="clearPoints" />
                    </a-tab-pane>
                    <a-tab-pane key="2" tab="知识点" force-render>
                        <PointsTree ref="PointsTree" :activeSubject="activeSubject" @getQuestion="getQuestion"
                            @clearChapter="clearChapter" />
                    </a-tab-pane>
                </a-tabs>
            </div>
            <!-- 右侧试题框 -->
            <div class="main-right">
                <!-- 题目列表 -->
                <div class="question-list">
                    <!-- 难度 ，题型筛选 -->
                    <!-- <div> -->
                    <myListSelect title="试题难度" :data="difficultyList" :defaultSelect="activeDifficulty"
                        :replaceFields="replaceFields" @callBack="difficultyCallBack" v-model="activeDifficulty" />
                    <myListSelect title="试题题型" :data="questionTypeList" @callBack="questionTypeCallBack"
                        :defaultSelect="activeQuestionType" v-model="activeQuestionType" />
                    <a-spin :spinning="spinning">
                        <template>
                            <div v-if="questionData.length>0" class="question-item m16"
                                v-for="(item,index) in questionData" :key="item.id">
                                <QuestionItem :ref="'QuestionItem'+index" :data="item">
                                    <template slot-scope="scope">
                                        <div class="flex-align bordr-bottom-gray p-8">
                                            <div>
                                                <span class="m-r36">题型：{{item.disciplineQuestionType}}</span>
                                                <span class="m-r36">难度：{{item.difficulty}}</span>
                                            </div>
                                            <div class="flex">
                                                <span v-if="item.questionConvertState!=0">
                                                    <a-icon type="undo" class="blue-hover m-r8" @click="_QuestionGetList"/></span>
                                                <template v-if="item.questionConvertState!=0">
                                                    <a-tooltip>
                                                        <template slot="title" v-if="item.questionConvertState>1">
                                                            {{item.convertFailMessage}}
                                                        </template>
                                                        <div class="flex m-r8" style="display: block;">
                                                            <span>替换状态：</span>
                                                            <span style="color:orange"
                                                                v-if="item.questionConvertState==1">转换中</span>
                                                            <span style="color:red"
                                                                v-if="item.questionConvertState==2">转换失败</span>
                                                            <span style="color:red"
                                                                v-if="item.questionConvertState==3">解析替换失败</span>
                                                        </div>
                                                    </a-tooltip>
                                                </template>
                                                <a-upload :showUploadList="false"
                                                    :customRequest="(data)=>customRequest(data,item.id,index)">
                                                    <a class="m-r16">上传替换</a>
                                                </a-upload>
                                                <a class="m-r16" @click="questionDown(item)">下载</a>
                                                <a class="m-r16" @click="toEdit(item,index)">纠错</a>
                                                <a class="m-r16" @click="toggle(index)">详情</a>
                                                <a class="m-r16" @click="addToTest(item)" v-show="!item.inbox">加入试卷</a>
                                                <a class="m-r16" @click="delFromTest(item)" v-show="item.inbox">移出试卷</a>
                                            </div>
                                        </div>
                                    </template>
                                </QuestionItem>
                            </div>
                            <a-empty v-if="questionData.length===0" />
                        </template>
                    </a-spin>

                    <!-- </div> -->

                <!-- 底部分页 -->
                <div class="paging-box">
                    <!-- <a-pagination size="small" :pagination="pagination" :total="50" show-size-changer
                        show-quick-jumper /> -->
                    <oPagination :pagination="pagination" @change="handleChange" />
                </div>
                </div>
            </div>
        </div>
        <!-- 试题导入模态框 -->
        <QuestionImport ref="QuestionImport" />
        <!-- 试卷蓝抽屉 -->
        <div class="basket" @click="showDrawer">
            <div class="basket-inner">
                <div v-if="$store.state.storage.testBox.length>0" class="basket-dot">{{dotNum}}</div>
                试题篮
            </div>
        </div>
        <TestBasket ref="TestBasket" />
    </div>
</template>

<script>
    import { myPagination } from '@/mixins/myPagination.js'
    import ChapterTree from './components/ChapterTree.vue'
    import PointsTree from './components/PointsTree.vue'
    import myListSelect from '@/components/myListSelect.vue'
    import MultiListSelect from '@/components/MultiListSelect.vue'
    import QuestionImport from './components/QuestionImport.vue'
    import TestBasket from './components/TestBasket.vue' //试题蓝
    import QuestionItem from '@/components/Questions/QuestionItem'
    import oPagination from '@/components/myPagination'
    import { download, getFileID, getQueryString } from '@/utils/tools'
    import { QuestionGetList, DisciplineQuestionTypeGetList, GetQuestionTemplate, QuestionGetQuestionDoc, QuestionReplace } from '@/api/api'

    export default {
        mixins: [myPagination],
        components: {
            ChapterTree,
            PointsTree,
            myListSelect,
            QuestionImport,
            TestBasket,
            QuestionItem,
            MultiListSelect,
            oPagination
        },
        data() {
            return {
                spinning: false,
                templateLoading: false,
                replaceFields: [
                    ['id', 'value']
                ],
                activeSubject: {},//当前学科
                difficultyList: [],//难度列表
                activeDifficulty: [''],//当前难度
                questionTypeList: [],//学科题型
                activeQuestionType: [''],//当前题型
                questionData: [],//试题列表
                ChapterId: '',//选中的章节id
                KnowledgePointIdList: [],//选中的知识点
                KeyWord: '',//查询关键字

                isShowSubjectSelect:false,
            }
        },
        created() {
            this.$store.dispatch('GetDifficulty', true).then(res => {
                this.difficultyList = res;
                console.log(this.difficultyList, 'this.difficultyList')
            })
            this.$store.dispatch('DisciplineGetList', true).then(res => {
                if (res.length > 0) {
                    this.activeSubject = res[0].data.length > 0 ? res[0].data[0] : {};
                    this.$refs.ChapterTree._TextbookGetList(this.activeSubject);
                    this._DisciplineQuestionTypeGetList();
                }
            })
                //console.log(this.$store.state.baseInfo.SubjectsArr, '$store.state.baseInfo.SubjectsArr')

        },
        computed: {
            dotNum() {
                let num = this.$store.state.storage.testBox.length > 99 ? '99+' : this.$store.state.storage.testBox.length
                return num
            },
            textBox() {
                return this.$store.state.storage.testBox
            }
        },
        watch: {
            textBox(nVal) {
                console.log(nVal, 'nVal')
                this.questionData = this.questionData.map(item => {
                    let arr = nVal.filter(v => v.id == item.id);
                    if (arr.length > 0) {
                        item.inbox = true;
                    } else {
                        item.inbox = false;
                    }
                    return item;
                })
            }
        },
        mounted() {
          this.checkSoruceToken()
        },
        methods: {
          checkSoruceToken(){
          const query= getQueryString('token')
            if(query){
              const sourceToken= localStorage.getItem("sourceToken")
              localStorage.setItem("isSource", '1')
              //console.log('checkSoruceToken',query,sourceToken,sourceToken===query)
              if(sourceToken!==query){
                this.$router.push({ name: 'login' })
              }
            }
          },
            customRequest(data, id, index) {
                console.log(index, 'index')
                this.$refs['QuestionItem' + index][0].showLoading(true);
                getFileID(data.file).then(res => {
                    let values = {
                        questionId: id,
                        fileId: res
                    }
                    console.log(values, 'values')
                    QuestionReplace(values).then(res => {
                        console.log(res, '替换成功')
                        this.$message.success('替换成功');
                        this.$refs['QuestionItem' + index][0].showLoading(false);
                        this._QuestionGetList();
                    }).catch(err => {
                        this.$refs['QuestionItem' + index][0].showLoading(false);
                    })
                }).catch(err => {
                    this.$refs['QuestionItem' + index][0].showLoading(false);
                })
            },
            //下载单道试题
            questionDown(record) {
                console.log(record, 'record')
                let data = {
                    id: record.id
                }
                QuestionGetQuestionDoc(data).then(res => {
                    download(res, '试题.docx')
                })
            },
            //下载导入模板
            GetQuestionTemplate() {
                this.templateLoading = true;
                let data = {
                    disciplineId: this.activeSubject.id
                }
                GetQuestionTemplate(data).then((res) => {
                    download(res, '试题标记说明举例.docx')
                    this.templateLoading = false;
                }).catch(err => {
                    this.templateLoading = false;
                })
            },
            //试题蓝-移除试题
            delFromTest(item) {
                item.inbox = false;
                let testBox = this.$storage.get('testBox');
                let index = testBox.findIndex(v => v.id == item.id)
                console.log(index, 'index')
                testBox.splice(index, 1);
                this.$storage.set('testBox', testBox);
                console.log(this.$store.state.storage.testBox, '$store.state.storage.testBox')
            },
            //增加试题到试题蓝
            addToTest(item) {
                item.inbox = true;
                console.log(item, 'item')
                let testBox = this.$storage.get('testBox');
                testBox.push(item);
                this.$storage.set('testBox', testBox);
                console.log(this.$storage.get('testBox'), 'localStorage.getItem(key)')
                console.log(this.$store.state.storage.testBox, '$store.state.storage.testBox')
            },
            clearChapter() {
                this.$nextTick(() => {
                    this.$refs.ChapterTree.clearChapter();
                })
            },
            clearPoints() {
                this.$nextTick(() => {
                    this.$refs.PointsTree.clearPoints();
                })
            },
            //回调
            getQuestion(data = {}) {
                this.ChapterId = data.ChapterId || '';
                this.KnowledgePointIdList = data.KnowledgePointIdList || []
                this.pagination.current = 1;
                this._QuestionGetList();
                console.log(this.ChapterId, 'this.ChapterId');
                console.log(this.KnowledgePointIdList, 'this.KnowledgePointIdList');
            },
            //试题列表
            _QuestionGetList(params = {}) {
                this.spinning = true;
                let data = {
                    DisciplineId: this.activeSubject.id,//学科id 666
                    DisciplineQuestionTypeId: this.activeQuestionType[0],//学科细分题型Id 666
                    Difficulty: this.activeDifficulty[0], //666
                    IsActive: null,
                    KnowledgePointIdList: this.KnowledgePointIdList,//知识点id
                    ChapterId: this.ChapterId,//章节id
                    IncludeChildChapter: true,//是否包括子章节(默认包括)
                    IncludeAncestor: false,//是否包括父级知识点(默认不包括)
                    KeyWord: this.KeyWord,//关键字
                    SkipCount: (this.pagination.current - 1) * this.pagination.pageSize,
                    MaxResultCount: this.pagination.pageSize,
                    ...params
                }
                QuestionGetList(data).then(res => {
                    console.log(res, '试题列表')
                    let testBox = this.$storage.get('testBox');
                    this.questionData = res.items.map(item => {
                        let arr = testBox.filter(v => v.id == item.id);
                        if (arr.length > 0) {
                            item.inbox = true;
                        } else {
                            item.inbox = false;
                        }
                        return item;
                    })
                    this.pagination.total = res.totalCount;
                    this.spinning = false;
                }).catch(err => {
                    this.spinning = false;
                })
            },
            //获取学科题型
            _DisciplineQuestionTypeGetList() {
                this.activeQuestionType = [''];
                let data = {
                    disciplineId: this.activeSubject.id//学科题型
                }
                DisciplineQuestionTypeGetList(data).then(res => {
                    console.log(res, '学科题型')
                    this.questionTypeList = res;
                })
            },
            //难度回调  
            difficultyCallBack(data) {
                console.log(data, '难度回调')
                this.activeDifficulty = [data[0]];
                this._QuestionGetList();
            },
            //题型回调
            questionTypeCallBack(data) {
                console.log(data, '题型回调')
                this.activeQuestionType = [data[0]];
                this._QuestionGetList();
            },
            toggle(index) {
                this.$refs['QuestionItem' + index][0].toggle();
            },
            toEdit(item, index) {
                this.$refs['QuestionItem' + index][0].toEdit(2);
            },
            onSearch(val) {
                this.KeyWord = val;
                const pager = { ...this.pagination };
                pager.current = 1;
                this.pagination = pager;
                this._QuestionGetList();
            },
            callback(key) {
                console.log(key);
            },
            //试题导入
            QuestionImport() {
                this.$refs.QuestionImport.showModal()
            },
            toPath(path) {
                this.$router.push({
                    name: path,
                })
            },
            showDrawer() {
                this.$refs.TestBasket.showDrawer()
            },
            //学科点击回调
            subjectCallBack(data) {
                console.log(data, '选中的学科')
                this.activeDifficulty = [''];
                this.activeSubject = data;
                this._DisciplineQuestionTypeGetList();
            },
            //分页change
            handleChange(pagination) {
                this._QuestionGetList();
            },
            handleShowSubjectSelect(e){
                e.preventDefault();
                this.isShowSubjectSelect=!this.isShowSubjectSelect;
            }
        }
    }
</script>

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

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

    .top-left {
        width: 240px;
        height: 100%;
        border-right: 1px solid rgba(232, 232, 232, 1);
        padding: 16px;
        font-size: 20px;
        color: #333333;
        /* position: relative; */
    }

    .top-left .subject-title a{color:#333333}

    .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.subject-select-box-show {
        max-height: 1000px;
        display: block;
        overflow-y: auto;
    }

    .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;
    }

    .type-group {
        padding: 8px;
        background-color: #fff;
    }

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

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

    .basket {
        position: absolute;
        right: 0;
        top: 45%;
        width: 36px;
        word-break: break-all;
        color: #fff;
        background-color: #40a9ff;
        border-radius: 2px;
        text-align: center;
        cursor: pointer;
        letter-spacing: 5px;
    }

    .question-item {
        background-color: #fff;
    }

    .basket-inner {
        flex: 1;
        padding: 10px 0;
        padding-left: 8px;
        position: relative;
    }

    .basket-dot {
        background-color: red;
        border-radius: 8px;
        min-width: 20px;
        padding: 0 4px;
        position: absolute;
        top: -8px;
        left: -8px;
        letter-spacing: 0px;
    }
</style>