<template>
	<div class="total-container">
		<div class="total-body">
			<!-- 评测列表展示组件 -->
			<!-- 右侧数据展示区域 -->
			<div class="total-content" ref="dataContainer">
				<vuescroll ref="vs" @handle-scroll="handleScroll">
					<div class="back-to-top fl-col-center" title="返回顶部" v-if="isShowBackToTop" @click="handleBackToTop">
						<Icon type="ios-arrow-up" />
					</div>
					<!--<Spin fix v-show="contentLoading"></Spin>-->
					<Loading :top="400" :borderWidth="4" :borderTopWidth="8" v-show="contentLoading"></Loading>

					<div class="basic-info" v-if="!isShowEvaluations && currentExamItem.name">
						<p style="display: flex;align-items: center;">
							<span class="info-type"
								:style="{color:colorTransfer[currentExamItem.type] || 'red',borderColor:colorTransfer[currentExamItem.type]|| 'red'}">{{nameTransfer[currentExamItem.type]}}</span>
							<span class="info-name">{{currentExamItem.name}}</span>
							<span class="info-grade">{{currentExamItem.period.name}}</span>
							<span class="info-subject" v-for="(subject,index) in currentExamItem.subjects"
								:key="index">{{subject.name}}</span>
						</p>
						<p class="info-date-person">
							<!--<span class="info-person">{{$t('totalAnalysis.text7')}}：<span style="color:#fff">{{currentExamItem.stuCount}}人</span></span>-->
							<!--<span class="info-date">{{$t('totalAnalysis.text8')}}：<span style="color:#fff">{{currentExamItem.time || '2019-02-11'}}</span></span>-->
							<span class="info-item">{{$t('totalAnalysis.echarts_text11')}}： <span
									style="color:#fff;font-weight:bold">{{ $tools.formatTime(currentExamItem.startTime,'yyyy-MM-dd')}}</span></span>
							<span class="info-item">{{$t('totalAnalysis.echarts_text12')}}： <span
									style="color:#fff;font-weight:bold">{{currentExamItem.stuCount}}</span></span>
							<span class="info-item">{{$t('totalAnalysis.echarts_text13')}}： <span
									style="color:#fff;font-weight:bold">{{currentExamItem.stuCount - currentExamItem.lostStu.length}}</span></span>
							<span class="info-item">{{$t('totalAnalysis.echarts_text14')}}： <span
									style="color:#fff;font-weight:bold">{{getJoinRate}}</span></span>
							<span class="info-item">{{$t('totalAnalysis.echarts_text15')}}： <span
									style="color:#fff;font-weight:bold">{{totalAverage}}</span></span>
						</p>
						<div class="basic-tools">
							<span class="basic-tool-export" @click="handleExportTables">
								<Icon type="md-cloud-download" /> {{$t('totalAnalysis.exportTable')}}
							</span>
							<span class="basic-tool-export" @click="goEvaluationList">
								<Icon type="md-exit" /> {{$t('totalAnalysis.goExamList')}}
							</span>
						</div>
						<!-- <div class="basic-tools">
                            <span class="basic-tool-export" @click="handleExportTables"> {{$t('totalAnalysis.exportTable')}} <Icon type="md-archive" /></span>
                            <span class="basic-tool-export" @click="goEvaluationList"> 查看更多评测 <Icon type="md-arrow-round-forward" /></span>
                        </div> -->
					</div>
					<div class="data-select" v-if="!isShowQuestions" ref="dataSelect">
						<div class="data-select-items" style="display:inline-block">
							<span
								:class="this.$route.path == '/total' || this.$route.path.indexOf('/total/achievement') > -1 ? 'data-select-active' : ''"
								@click="handleDataSelect('0')">{{$t('totalAnalysis.module1')}}</span>
							<span :class="this.$route.path.indexOf('/total/scatter') > -1 ? 'data-select-active' : ''"
								@click="handleDataSelect('1')">{{$t('totalAnalysis.module2')}}</span>
							<span :class="this.$route.path.indexOf('/total/test') > -1 ? 'data-select-active' : ''"
								@click="handleDataSelect('2')">{{$t('totalAnalysis.module3')}}</span>
							<span :class="this.$route.path.indexOf('/total/knowledge') > -1 ? 'data-select-active' : ''"
								@click="handleDataSelect('3')">{{$t('totalAnalysis.module4')}}</span>
							<span
								:class="this.$route.path.indexOf('/total/cognitionLevel') > -1 ? 'data-select-active' : ''"
								@click="handleDataSelect('4')">{{$t('totalAnalysis.module5')}}</span>
						</div>

						<div v-if="dataSelectIndex === '0'" class="class-subject-select">
							<Select v-model="currentClass" @on-change="onClassSelect" class="analysis-select">
								<Option v-for="(item,index) in classList" :value="index" :key="item">{{ item }}</Option>
							</Select>
							<div class="subject-tab">
								<span v-for="(subject,subjectIndex) in getSubjectList" :key="subjectIndex" @click="onEarlySubjectChange(subjectIndex,subject)" :class="['subject-tab-item',curWarningSubjectIndex === subjectIndex ? 'subject-tab-item-active' : '']">{{ subject }}</span>
							</div>
						</div>
						
						<div v-if="dataSelectIndex !== '0'" class="class-subject-select">
							<Select v-model="currentScatterClass" @on-change="onScatterClassSelect" class="analysis-select" v-if="dataSelectIndex !== '2'">
								<Option v-for="(item,index) in classList" :value="index" :key="item">{{ item }}</Option>
							</Select>
							<div class="subject-tab">
								<span v-for="(subject,subjectIndex) in getSubjectList" :key="subjectIndex" @click="handleSubjectChange(subject)" :class="['subject-tab-item',subjectSelectVal === subject ? 'subject-tab-item-active' : '']">{{ subject }}</span>
							</div>
						</div>

						<!-- <span style="float:right;margin-bottom:4px;" v-if="dataSelectIndex !== '0'">
							<span class="select-title">{{$t('totalAnalysis.currentSubject')}}：</span>
							<Select v-model="subjectSelectVal" style="width:150px" @on-change="handleSubjectChange">
								<Option v-for="(item,index) in getSubjectList" :value="item" :key="index" :label="item">
								</Option>
							</Select>
						</span> -->
					</div>
					<div class="data-container" style="position:relative" ref="routerView">
						<Loading :top="300" v-show="dataLoading"></Loading>
						<transition name="fade">
							<router-view />
						</transition>
					</div>
				</vuescroll>
			</div>
		</div>

		<!-- 导出表格弹窗  -->
		<Modal v-model="isExportTables" width="660" footer-hide class="export-modal">
			<ExportTables></ExportTables>
		</Modal>

	</div>
</template>

<script>
	import FileSaver from "file-saver";
	import JSZip from "jszip";
	import Loading from '@/common/Loading.vue'
	import excel from '@/utils/excel.js'
	import '../../../utils/chalk.js'
	import 'animate.css'
	import ExportTables from '@/components/student-analysis/total/ExportTables.vue'
	export default {
		components: {
			ExportTables,
			Loading
		},
		data(vm) {
			return {
				searchValue: '',
				contentLoading: false,
				dataLoading: false,
				dataSelectIndex: '0',
				menuIndex: 0,
				isShowBackToTop: false,
				isShowQuestions: false,
				isShowEvaluations: false,
				isSubMenuShow: false,
				isExportTables: false,
				currentExamItem: {},
				subjectSelectVal: 0,
				subjectSplitList: [],
				subjectList: [],
				examList: [],
				colorTransfer: {
					'regular': '#fbd103',
					'simulation': '#baecff',
					'normal': '#00ff8a'
				},
				nameTransfer: {
					regular: vm.$t('totalAnalysis.ti_text6'),
					simulation: vm.$t('totalAnalysis.ti_text7'),
					normal: vm.$t('totalAnalysis.ti_text8')
				},
				scrollTopssss: 0,
				totalAverage: 0,
				currentClass: 0,
				currentScatterClass:0,
				curWarningSubjectIndex:0,
				classList: [],
			}
		},
		async created() {
			if (!this.$store.state.totalAnalysis.analysisJson && !localStorage.getItem('curExam')) {
				this.$store.dispatch('getAnalysisJson', {
					code: this.$route.query.code,
					id: this.$route.query.id
				}).then(res => {
					console.log('index页面获取JSON')
				})
			}

		},

		methods: {
			/* 获取当前评测的平均分 */
			getTotalAverage(data) {
				let analysisJson = this.$store.state.totalAnalysis.analysisJson
				let totalScore = analysisJson.students.reduce(function(total, currentValue, currentIndex, arr) {
					return total + currentValue.total;
				}, 0);
				this.totalAverage = (totalScore / analysisJson.students.length).toFixed(1)
			},

			onClassSelect(val) {
				this.$store.commit('updateClassIndex',val)
				this.currentScatterClass = val
				if (val === 0) {
					this.$store.commit('updateExportTable', [{
						tableRef: 'entryTable',
						tableName: this.$t('totalAnalysis.ach_title4')
					}, {
						tableRef: 'entryRateTable',
						tableName: this.currentScatterClass === 0 ? this.$t('totalAnalysis.ach_title5') : this.$t('totalAnalysis.ach_title5_2')
					}])
					this.$router.push({
						path: '/total'
					})
				} else {
					this.onEarlySubjectChange(0,this.$t('totalAnalysis.allSubjects'))
					this.$store.commit('updateExportTable', [{
						tableRef: 'earlyWarningTable',
						tableName: this.$t('totalAnalysis.myTable.rank')
					}])
					if(this.$route.path === '/total/achievement/earlyWarning'){
						this.$EventBus.$emit('changeClassName',this.classList[val])
					}else{
						this.$router.push({
							path: '/total/achievement/earlyWarning',
							query: {
								name: this.classList[val]
							}
						})
					}
				}
			},
			
			onScatterClassSelect(val){
				this.$store.commit('updateClassIndex',val)
				this.$EventBus.$emit('changeClassName',this.classList[val])
			},

			// 选择查看模块
			handleDataSelect(index) {
				let path = ''
				let that = this
				this.dataSelectIndex = index + ''
				this.dataLoading = true
				switch (Number(index)) {
					case 0:
						path = '/total'
						this.currentClass = 0
						this.onEarlySubjectChange(0,this.$t('totalAnalysis.allSubjects'))
						this.$store.commit('updateExportTable', [{
							tableRef: 'entryTable',
							tableName: this.$t('totalAnalysis.ach_title4')
						}, {
							tableRef: 'entryRateTable',
							tableName: this.currentScatterClass === 0 ? this.$t('totalAnalysis.ach_title5') : this.$t('totalAnalysis.ach_title5_2')
						}])

						break
					case 1:
						path = '/total/scatter'
						// this.currentScatterClass = 0
						this.$store.commit('updateExportTable', [{
							tableRef: 'scatterTable',
							tableName: this.$t('totalAnalysis.sca_title2')
						}])
						break
					case 2:
						path = '/total/test'
						this.$store.commit('updateExportTable', [{
							tableRef: 'exerciseAnalsisTable',
							tableName: this.$t('totalAnalysis.ta_title3')
						}, {
							tableRef: 'exerciseScoreRateTable',
							tableName: this.$t('totalAnalysis.ta_title4')
						}])
						break
					case 3:
						path = '/total/knowledge'
						this.$store.commit('updateExportTable', [{
							tableRef: 'pointScoreRateTable',
							tableName: this.$t('totalAnalysis.ka_title3')
						}, {
							tableRef: 'pointScoreTable',
							tableName: this.$t('totalAnalysis.ka_title5')
						}, {
							tableRef: 'pointWrongTable',
							tableName: this.$t('totalAnalysis.ka_title6')
						}])
						break
					case 4:
						path = '/total/cognitionLevel'
						this.$store.commit('updateExportTable', [{
							tableRef: 'levelScoreRateTable',
							tableName: this.$t('totalAnalysis.le_title3')
						}, {
							tableRef: 'levelScoreTable',
							tableName: this.$t('totalAnalysis.le_title5')
						}, {
							tableRef: 'levelWrongTable',
							tableName: this.$t('totalAnalysis.le_title6')
						}])
						break
					default:
						break
				}
				that.dataLoading = false
				this.$router.push(path)
			},

			// 查看更多评测列表
			goEvaluationList() {
				this.$store.commit('clearAnalysis', null)
				this.$router.push({
					name: 'totalIndex'
				})
			},

			// 导出表格操作
			handleExportTables() {
				this.isExportTables = true
			},

			// 返回顶部
			handleBackToTop() {
				this.$refs['vs'].scrollTo({
						y: '0'
					},
					500
				)
			},
			
			onEarlySubjectChange(index,subject){
				console.log(index,subject)
				this.$store.state.totalAnalysis.indexSubject = subject
				this.$EventBus.$emit('onEarlySubjectChange', index)
				this.curWarningSubjectIndex = index
			},

			// 切换科目时更换页面图表数据
			handleSubjectChange(val) {
				console.log(val)
				let that = this
				// this.dataLoading = true
				console.log('API===========================' + val)
				this.$store.commit('updateCurSubject', val)
				this.$EventBus.$emit('onSubjectChange', val)

			},

			// 判断容器滚动距离
			handleScroll(vertical, horizontal, nativeEvent) {
				this.isShowBackToTop = vertical.scrollTop > 400
				this.scrollTopssss = vertical.scrollTop
				this.$store.commit('updateScrollTop', vertical.scrollTop)
			},

			// 多选文件下载
			onMultipleDownLoad(val) {
				let excelNums = this.$store.state.totalAnalysis.excelNums
				if (val.length === excelNums) {
					// 如果下载数据已全部获取到 则执行下载程序
					const zip = new JSZip();
					let promiseArr = []
					val.forEach(async data => {
						promiseArr.push(excel.excelZipExport(data))
					})
					// 表格files全部拿到 则进行打包并且下载
					Promise.all(promiseArr).then(result => {
						console.log(result)
						result.forEach(file => {
							zip.file(file.name, file, {
								binary: true
							}); // 逐个添加文件
						})
						zip.generateAsync({
							type: "blob"
						}).then(content => {
							// 生成二进制流
							FileSaver.saveAs(content,
								`${ result[0].name.split('.xlsx')[0] }等${ result.length} 个表格.zip`
								); // 利用file-saver保存文件
							this.isLoading = false;
						})
					})

				}
			},

		},
		mounted() {
			let downLoadExcels = []
			let examIndex = this.$route.query.index
			this.$nextTick(() => {
				if (this.$route.name !== 'earlyWarning') {
					// this.getExamData(examIndex)
				}
			})
			this.getTotalAverage()
			this.handleDataSelect(0)
			this.currentExamItem = JSON.parse(localStorage.getItem('curExam'))
			console.log(this.currentExamItem)

			if (this.getAnalysisJson) {
				this.classList = [this.$t('totalAnalysis.allClasses')].concat([...new Set(this.getAnalysisJson.classes.map(item => item
					.className))]) // 获取班级列表
			}
		},
		computed: {
			// 获取最新成绩分析模块数据
			getAnalysisJson() {
				return this.$store.state.totalAnalysis.analysisJson
			},
			getSubjectList() {
				this.subjectSelectVal = this.$store.state.totalAnalysis.currentSubject
				/* 如果是成绩分析则要加入全科统计栏目 */
				if(this.dataSelectIndex === '0'){
					return [this.$t('totalAnalysis.allSubjects'),...this.$store.state.totalAnalysis.subjectList] 
				}else{
					return this.$store.state.totalAnalysis.subjectList
				}
				
			},
			getVuexExamList() {
				return this.$store.state.totalAnalysis.examList
			},
			getVuexExcelData() {
				return this.$store.state.totalAnalysis.exportTableParams
			},
			getJoinRate() {
				return ((this.currentExamItem.stuCount - this.currentExamItem.lostStu.length) / this.currentExamItem.stuCount).toFixed(2) * 100 + '%'
			}
		},
		// 监听部分路由变化
		watch: {
			'$route'(to, from) {
				this.handleBackToTop()
				if (to.path === '/total' && from.path === '/totalindex') {
					this.isShowEvaluations = false
					this.isShowQuestions = false
					this.$refs.examListRef.examIndex = to.query.index
				}
			},
			getVuexExamList(val) {
				console.log(val)
				if (val.length) {
					this.examList = val
				}
			},
			getVuexExcelData(val) {
				console.log('表格数据变化')
				console.log(val)
				this.onMultipleDownLoad(val)
			}
		}
	}
</script>

<style src="./index.less" lang="less" scoped></style>

<style lang="less">
	.total-content .analysis-select {
		width: 140px;
		margin-right: 20px;

		.ivu-select-selection {
			width: 140px;
			background-color: #252525e3 !important;
			border-radius: 0;
			border-color: #96969640 !important;
		}

		.ivu-select-dropdown {
			background-color: #3c3c3c;

			.ivu-select-item {
				color: #e6e6e6;

				&:hover {
					background-color: #565656;
				}
			}

			.ivu-select-item-focus {
				background-color: #3c3c3c;
			}
		}
	}

	.total-content {
		.basic-tools {
			.ivu-input {
				background: transparent;
				border: 1px solid #595959;
				height: 30px;
				padding-left: 10px;
				font-size: 14px;
				font-weight: bold;
				color: #a2a2a2;
				box-shadow: none;
				border-radius: 5px;

				&::-webkit-input-placeholder {
					color: #616161;
				}
			}

			.ivu-select {
				margin: 5px 20px 5px 0;
				height: 30px;
			}
		}

		.ivu-select-single {
			.ivu-select-selection {
				height: 30px;
				background: transparent;
				border: 1px solid #595959;
				box-shadow: none;
				color: #cecece;
			}

			.ivu-select-placeholder {
				height: 30px;
				line-height: 30px;
				font-size: 16px;
			}
		}

		.ivu-spin-fix {
			background: rgba(209, 209, 209, 0.51);
		}

		.ivu-spin-dot {
			width: 100px;
			height: 100px;
		}
	}

	.export-modal {
		.ivu-modal-header {
			display: none;
		}

		.ivu-modal-content {
			background: #fff;
			color: #757575;
		}
	}

	/*全科单科选择部分*/
</style>
