<template>
    <div style="height: 100%;background: #404040;position:relative;">
        <Poptip padding="0px 0px" offset="10" placement="top-end" width="300" trigger="hover" :class="shoppingCarClass">
            <Badge type="primary" :count="shoppingQuestionList.length" show-zero :offset="[-3,-3]"  @mouseenter.native="changeActive($event)" @mouseleave.native="removeActive($event)">
                <Icon custom="iconfont icon-sp-car" color="#1cc0f3" size="50"/>
            </Badge>
            <div slot="content">
                <div class="shopping-car-detail">
                    <p class="shopping-car-detail-title">{{$t('evaluation.createPaper.total')}}<span style="margin:0px 5px;">{{shoppingQuestionList.length}}</span>{{$t('evaluation.createPaper.nums')}}</p>

                    <div class="shopping-car-detail-item">
                        <span class="question-type">{{$t('evaluation.single')}}：</span>
                        <Progress stroke-color="#6bdfc3" :percent="groupList.single*100/shoppingQuestionList.length" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
                        <span class="question-num">{{groupList.single}}{{$t('evaluation.createPaper.spc')}}</span>
                    </div>

                    <div class="shopping-car-detail-item">
                        <span class="question-type">{{$t('evaluation.multiple')}}：</span>
                        <Progress stroke-color="#6bdfc3" :percent="groupList.multiple*100/shoppingQuestionList.length" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
                        <span class="question-num">{{groupList.multiple}}{{$t('evaluation.createPaper.spc')}}</span>
                    </div>
                    <div class="shopping-car-detail-item">
                        <span class="question-type">{{$t('evaluation.judge')}}：</span>
                        <Progress stroke-color="#6bdfc3" :percent="groupList.judge*100/shoppingQuestionList.length" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
                        <span class="question-num">{{groupList.judge}}{{$t('evaluation.createPaper.spc')}}</span>
                    </div>
                    <div class="shopping-car-detail-item">
                        <span class="question-type">{{$t('evaluation.complete')}}：</span>
                        <Progress stroke-color="#6bdfc3" :percent="groupList.complete*100/shoppingQuestionList.length" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
                        <span class="question-num">{{groupList.complete}}{{$t('evaluation.createPaper.spc')}}</span>
                    </div>
                    <div class="shopping-car-detail-item">
                        <span class="question-type">{{$t('evaluation.subjective')}}：</span>
                        <Progress stroke-color="#6bdfc3" :percent="groupList.subjective*100/shoppingQuestionList.length" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
                        <span class="question-num">{{groupList.subjective}}{{$t('evaluation.createPaper.spc')}}</span>
                    </div>
					<div class="shopping-car-detail-item">
					    <span class="question-type">{{$t('evaluation.connector')}}：</span>
					    <Progress stroke-color="#6bdfc3" :percent="groupList.connector*100/shoppingQuestionList.length" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
					    <span class="question-num">{{groupList.connector}}{{$t('evaluation.createPaper.spc')}}</span>
					</div>
					<div class="shopping-car-detail-item">
					    <span class="question-type">{{$t('evaluation.correct')}}：</span>
					    <Progress stroke-color="#6bdfc3" :percent="groupList.correct*100/shoppingQuestionList.length" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
					    <span class="question-num">{{groupList.correct}}{{$t('evaluation.createPaper.spc')}}</span>
					</div>
                    <div class="shopping-car-detail-item">
                        <span class="question-type">{{$t('evaluation.compose')}}：</span>
                        <Progress stroke-color="#6bdfc3" :percent="groupList.compose*100/shoppingQuestionList.length" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
                        <span class="question-num">{{groupList.compose}}{{$t('evaluation.createPaper.spc')}}</span>
                    </div>
                    <p class="shopping-car-detail-bottom" @click="goToPreview">{{$t('evaluation.createPaper.goDetails')}}</p>
                </div>
            </div>
        </Poptip>
        <vuescroll ref="manualScroll">
            <div class="manual-filter-wrap">
                <Row style="width:100%;">
                    <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="6">
                    <div class="manual-filter-item">
                        <span class="manual-filter-label">{{$t('evaluation.filter.origin')}}：</span>
                        <CheckboxGroup v-model="manualFilter.code" style="display:inline-block;"  @on-change="checkAll($event,'origin')">
                            <!--<Checkbox   label="all">全部</Checkbox>-->
                            <Checkbox  :label="$store.state.userInfo.TEAMModelId" v-if="!isSchool">{{$t('evaluation.filter.privateBank')}}</Checkbox>
                            <Checkbox  :label="$store.state.userInfo.schoolCode" :disabled="!hasSchool">{{$t('evaluation.filter.schoolBank')}}</Checkbox>
                        </CheckboxGroup>
                    </div>
                    </Col>
                    <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="18">
                    <div class="manual-filter-item evaluation-attr-form">
                        <span class="manual-filter-label">{{$t('evaluation.filter.period')}}：</span>
                        <Select v-model="manualFilter.periodCode[0]" :disabled="!isPeriod || isSchool"  size="small"  style="display: inline-block;width:100px"  @on-change="checkAll($event,'periodCode')">
                            <Option v-for="(item,index) in schoolPeriod" :value="item.id" :key="index">{{ item.name }}</Option>
                        </Select>
						<span class="manual-filter-label" style="margin-left: 30px;">{{$t('evaluation.filter.subject')}}：</span>
						<Select v-model="manualFilter.subjectCode[0]" :disabled="!isPeriod || isSchool"  size="small"  style="display: inline-block;width:100px"  @on-change="checkAll($event,'subjectCode')">
						    <Option v-for="(item,index) in subjectList" :value="item.id" :key="index">{{ item.name }}</Option>
						</Select>
                        <span class="manual-filter-label" style="margin-left: 30px;">{{$t('evaluation.filter.level')}}：</span>
                        <Select v-model="manualFilter.field"  size="small"  style="display: inline-block;width:100px"  @on-change="checkAll($event,'field')">
                            <Option value="all">{{$t('evaluation.filter.all')}}</Option>
                            <Option v-for="(item,index) in fieldList" :value="index" :key="index">{{ item }}</Option>
                        </Select>
                    </div>
                    </Col>
                    <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="16">
                    <div class="manual-filter-item">
                        <span class="manual-filter-label">{{$t('evaluation.filter.type')}}:</span>
                        <CheckboxGroup v-model="manualFilter.type" border style="display: inline-block;" @on-change="checkAll($event,'type')">
                            <Checkbox label="all">{{$t('evaluation.filter.all')}}</Checkbox>
                            <Checkbox label="single">{{$t('evaluation.single')}}</Checkbox>
                            <Checkbox label="multiple">{{$t('evaluation.multiple')}}</Checkbox>
                            <Checkbox label="judge">{{$t('evaluation.judge')}}</Checkbox>
                            <Checkbox label="complete">{{$t('evaluation.complete')}}</Checkbox>
                            <Checkbox label="subjective">{{$t('evaluation.subjective')}}</Checkbox>
                            <Checkbox label="connector">{{$t('evaluation.connector')}}</Checkbox>
                            <Checkbox label="correct">{{$t('evaluation.correct')}}</Checkbox>
                            <Checkbox label="compose">{{$t('evaluation.compose')}}</Checkbox>
                        </CheckboxGroup>
                    </div>
                    </Col> 
                    <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="8">
                    <div class="manual-filter-item">
                        <span class="manual-filter-label">{{$t('evaluation.filter.diff')}}:</span>
                        <CheckboxGroup v-model="manualFilter.level" border style="display: inline-block;" @on-change="checkAll($event,'level')">
                            <Checkbox label="all">{{$t('evaluation.filter.all')}}</Checkbox>
                            <Checkbox v-for="(item,index) in exersicesDiff" :key="index" :label="index + 1">{{ item }}</Checkbox>
                        </CheckboxGroup>
                    </div>
                    </Col>
                </Row>
            </div>
            <div class="question-list-wrap">
                <!-- <Loading :top="100" v-show="isLoading"></Loading> -->
                <ExerciseList ref="exList" :selQue="selQue" :propsList="questionList" @pageScroll="doScroll"
				 @on-question-change="selectQuestion"></ExerciseList>
                <EmptyData style="margin-top:120px;" v-if="!isLoading && questionList.length == 0" :textContent="$t('evaluation.addTip5')"></EmptyData>
                <!-- <div class="page-wrap">
                    <Page :current.sync="pageNum" :total="totalNum" show-total :page-size="pageSize" size="small" show-sizer @on-change="getCurrentPageData" />
                </div> -->
            </div>
        </vuescroll>
    </div>
</template>
<script>
    import QuestionList from '@/components/learnactivity/QuestionList.vue'
    import ExerciseList from '@/components/evaluation/ExerciseList.vue'
    export default {
        props: {
            selQue: {
                type: Array,
                default: () => {
                    return []
                }
            },
			subjectCode:{
				type:String,
				default:''
			},
			periodCode:{
				type:String,
				default:''
			}
        },
        components: {
            QuestionList,
			ExerciseList,
        },
        data() {
            return {
                isLoading: false,
                questionList:[],
                pageSize: 10,
                totalNum: 0,
                pageNum:1,
                exersicesDiff: this.$GLOBAL.EXERCISE_DIFFS(),
                questionConfig: {
                    showSelect: true
                },
                groupQuestion: {
                    single: 0,
                    multiple: 0,
                    judge: 0,
                    complete: 0,
                    subjective: 0,
                    connector: 0,
                    correct: 0,
                    compose: 0
                },
                shoppingQuestionList: [],
                shoppingCarClass: 'question-shopping-car',
                pointTab: '',
                selectPointsStatus: false,
                addKnowledgeStatus: false,
                manualFilter: {
                    periodCode: [],
                    code: [],
                    points: ['all'],
                    type: ['all'],
                    level: ['all'],
                    subjectCode: [],
                    scoped: "school",
					field:'all'
                },
                schoolPeriod: [],
				showQuestion:[],
				subjectList:[],
                groupList: {},
				fieldList: [this.$t('evaluation.level1'),this.$t('evaluation.level2'),this.$t('evaluation.level3'),
				this.$t('evaluation.level4'),this.$t('evaluation.level5'),this.$t('evaluation.level6')],
            }
        },

        methods: {
			/* 页面滚动逻辑 */
			doScroll(scrollDistance){
				this.$nextTick(() => {
					this.$refs.manualScroll.scrollTo({
							y: scrollDistance,
						},
						500,
						"easeInQuad"
					);
				})
			},
            /**
             * 选择全部逻辑
             * @param data:选中数据
             * @param key:字段名
             */
            checkAll(data, key) {
				console.log('点击了筛选区域')
				// 切换学段
				if(key === 'periodCode'){
					this.subjectList = this.schoolPeriod.filter(i => i.id === this.manualFilter.periodCode[0])[0].subjects
					this.manualFilter.subjectCode = [this.subjectList[0].id]
					this.queryQuestionByPage()
					return
				}
				// 切换科目
				if(key === 'subjectCode'){
					this.queryQuestionByPage()
					return
				}
				
				if(key === 'origin'){
					this.queryQuestionByPage()
					return
				}
				
				if(key === 'field'){
					this.queryQuestionByPage()
					return
				}
				
				// 切换其余筛选项
                if (this.manualFilter[key].length !== 1 && this.manualFilter[key].indexOf('all') === 0) {
                    this.manualFilter[key].splice(this.manualFilter[key].indexOf('all'), 1)
                } else if (this.manualFilter[key].indexOf('all') > 0) {
                    this.manualFilter[key].length = 0
                    this.$set(this.manualFilter[key],0,'all')
                }else if (this.manualFilter[key].length === 0){
					this.$set(this.manualFilter[key],0,'all')
				}
                this.pageNum = 1
                this.queryQuestionByPage()
            },
			
			/* 查询操作 */
            async queryQuestionByPage() {
                this.isLoading = true
				let resultList = []
                if (this.manualFilter.code.length > 0) {
					console.log(this.manualFilter.code)
					for (let i = 0; i < this.manualFilter.code.length; i++) {
						let code = this.manualFilter.code[i]
						let scope = code === this.$store.state.userInfo.TEAMModelId ? 'private' : 'school'
						try{
							let data = await this.queryQuestion(scope, code)
							resultList = resultList.concat(data)
						}catch(e){
							console.log(e)
						}
						
					}
					this.questionList = resultList
					this.totalNum = this.questionList.length
					this.isLoading = false
                } else {
                    this.$Message.warning(this.$t('evaluation.createPaper.noOriginTips'))
                    this.isLoading = false
                }
            },
			
			// 访问查询接口
            queryQuestion(scope, code) {
                let queryData = {
                    "@DESC": "createTime",
                    "code": code,
                    "periodId": scope === 'school' ? this.deleteAll(this.manualFilter.periodCode) : [],
                    "gradeIds[*]": [],
                    "subjectId": scope === 'school' ? this.deleteAll(this.manualFilter.subjectCode) : [],
                    "level": this.deleteAll(this.manualFilter.level),
                    "type": this.deleteAll(this.manualFilter.type),
                    "field": this.manualFilter.field !== 'all' ? this.manualFilter.field + 1 : [],
                    "scope": scope,
                    "pid": null
                }
                return new Promise((resolve, reject) => {
                    this.$api.newEvaluation.FindExerciseList(queryData).then(res => {
						if(res.items){
							resolve(res.items)
						}
                    }).catch((e) => {
                        reject(e);
                    });
                });
            },
			
			/* 去除无效值 */
            deleteAll(data) {
                if (data.length == 1) {
                    if (data[0] == 'all') {
                        return []
                    } else {
                        return data
                    }
                } else {
                    return data
                }
            },
			
			
            /*选择题目||取消选择题目*/
            async selectQuestion(data, info) {
                this.groupList = { ...this.groupQuestion }
                this.shoppingQuestionList = data
                this.shoppingCarClass = 'question-shopping-car animated heartBeat'
                setTimeout(() => {
                    this.shoppingCarClass = 'question-shopping-car'
                }, 1000)
                let groupResult = await this.$jsFn.groupBy(this.shoppingQuestionList, 'type')
                console.log(groupResult)
                for (let i = 0; i < groupResult.length; i++) {
                   this.groupList[groupResult[i][0].type]= groupResult[i].length
                }
                console.log(this.shoppingQuestionList)
                console.log(data)
                this.$emit('selectedQuestion', {
                    questions: this.shoppingQuestionList,
                    item: data
                })
            },
            goToPreview() {
                this.$emit('goToPreview')
            },
            changeActive(e) {
                this.shoppingCarClass = 'question-shopping-car animated pulse'
            },
            removeActive() {
                this.shoppingCarClass = 'question-shopping-car'
            },
            addKnowledge() {
                this.addKnowledgeStatus = true
            },
			confirmSelectPoints(){
				
			},
			/** 获取当前学校基础数据 */
			getSchoolBaseInfo() {
				return new Promise((r, j) => {
					this.$store.dispatch("user/getSchoolProfile").then((res) => {
						let schoolBaseInfo = res.school_base;
						if (schoolBaseInfo) {
							r(schoolBaseInfo)
						} else {
							r('noSchool')
						}
					});
				})
			},
        },
		mounted() {
			if(this.selQue.length){
				let data = this.selQue
				this.shoppingQuestionList = JSON.parse(JSON.stringify(data))
				let groupResult = this.$jsFn.groupBy(data, 'type')
				this.groupList = { ...this.groupQuestion }
				for (let i = 0; i < groupResult.length; i++) {
				    this.groupList[groupResult[i][0].type] = groupResult[i].length
				}
			}
			this.manualFilter.code = this.isSchool ? [this.$store.state.userInfo.schoolCode] : [this.$store.state.userInfo.TEAMModelId]
			this.getSchoolBaseInfo().then(res => {
				if (res === 'noSchool'){
					this.queryQuestionByPage()
				}else{
					this.schoolPeriod = res.period
					if(this.isSchool && this.periodCode && this.subjectCode){
						this.manualFilter.periodCode = [this.periodCode]
						this.subjectList = this.schoolPeriod.filter(i => i.id === this.periodCode)[0].subjects
						this.manualFilter.subjectCode = [this.subjectCode]
					}
					console.log(this.manualFilter)
					if(!this.isSchool || this.manualFilter.periodCode.length){
						this.queryQuestionByPage()
					}
				}
			})
			this.$EventBus.$off('onPaperItemChange')
		    this.$EventBus.$on('onPaperItemChange', data => {
				console.log('eventBus', data)
		        this.shoppingQuestionList = JSON.parse(JSON.stringify(data))
				this.$nextTick(() => {
					if(this.$refs.exList){
						this.$refs.exList.selectList = JSON.parse(JSON.stringify(data))
					}
				})
		        let groupResult = this.$jsFn.groupBy(data, 'type')
		        this.groupList = { ...this.groupQuestion }
		        for (let i = 0; i < groupResult.length; i++) {
		            this.groupList[groupResult[i][0].type] = groupResult[i].length
		        }
		    })
		},
        computed: {
            //判断是否为校本题库
            isPeriod() {
                return this.manualFilter.code.indexOf(this.$store.state.userInfo.schoolCode) > -1 
            },
			isSchool(){
				return this.$route.name === 'newSchoolPaper'
			},
			hasSchool() {
				return this.$store.state.userInfo.hasSchool;
			},
        },
		watch:{
			periodCode:{
				handler(n){
					this.manualFilter.periodCode[0] = n
					this.subjectList = this.schoolPeriod.filter(i => i.id === n)[0].subjects
				}
			},
			subjectCode:{
				handler(n){
					this.manualFilter.subjectCode[0] = n
					console.log(this.manualFilter.subjectCode)
					this.queryQuestionByPage()
				}
			}
		}
    }
</script>
<style lang="less">
    @import "./ManualCreate.less";
</style>