<template>
	<div class="achievement-container">
		<Row>
			<span class="component-title" style="margin-top:40px">{{ this.$t('totalAnalysis.classBaseInfo') }}</span>
		</Row>
		<Row class-name="component-percents">
			<div class="percent-item warning-info-item" v-show="isAllSubject">
				<div class="fl-col-center">
					<span class="percent-name">{{ this.$t('totalAnalysis.ach_text11') }}</span>
					<span class="percent-value">{{ currentClass.stuCount || 0 }}</span>
				</div>
			</div>
			<div class="percent-item warning-info-item" v-show="isAllSubject">
				<div class="fl-col-center">
					<span class="percent-name">{{ this.$t('totalAnalysis.ach_text8') }}</span>
					<span class="percent-value">{{ currentClass.lineCount || 0 }}</span>
				</div>
			</div>
			<div class="percent-item" v-show="isAllSubject">
				<div class="fl-col-center">
					<span class="percent-name">{{ this.$t('totalAnalysis.ach_text9') }}</span>
					<span class="percent-value">{{ ((currentClass.lineCount / currentClass.stuCount) * 100).toFixed(1) }}%</span>
				</div>
			</div>
			<div class="percent-item">
				<div class="fl-col-center">
					<span class="percent-name">{{ this.$t('totalAnalysis.ach_table_text3') }}</span>
					<span class="percent-value">{{ currentClass.totalAverage.toFixed(1) }}</span>
				</div>
			</div>
			<div class="percent-item">
				<div class="fl-col-center">
					<span class="percent-name">{{ this.$t('totalAnalysis.ach_table_text4') }}</span>
					<span class="percent-value">{{ currentClass.standardDeviation.toFixed(1) }}</span>
				</div>
			</div>
			<div class="percent-item">
				<div class="fl-col-center">
					<span class="percent-name">{{ this.$t('totalAnalysis.sca_chart_text1') }}</span>
					<span class="percent-value">{{ currentClass.csRate }}%</span>
				</div>
			</div>
		</Row>

		<!-- 班级均分分析 -->
		<Row class-name="averageBarRow">
			<Col span="12">
				<span class="component-title">{{$t('totalAnalysis.ach_title8')}}</span>
				<div class="sort-box">
					<!-- <span
						style="font-size:14px;margin-right:10px;color: #a9a9a9;">{{$t('totalAnalysis.ach_chart_text1')}}:</span> -->
					<Select v-model="sortValue" style="width:120px" @on-change="handleSort">
						<Option v-for="(item,index) in sortArr" :value="index" :label="item" :key="index"></Option>
					</Select>
				</div>
				<div id="stuAverageBar"></div>
			</Col>
			<Col span="12">
				<span class="component-title">{{ this.$t('totalAnalysis.scoreRate') }}</span>
				<BaseScoreRateBar echartsId="sRateBar2"  :echartsData="scoreRateBarData"></BaseScoreRateBar>
			</Col>
		</Row>
		<!-- PR排名表格 -->
		<Row class-name="base-table-row">
			<BaseTable :columns="earlyPercentColumns" :tableDatas="tableData"
				:tableName="$t('totalAnalysis.ach_title7')" noPage tableRef="earlyWarningTable" ref="percentTable"
				v-show="warningIndex === 0"></BaseTable>
		</Row>
	</div>
</template>

<script>
	import BaseTable from '@/components/student-analysis/total/BaseMyTable.vue'
	import BaseScoreRateBar from '@/components/student-analysis/total/BaseScoreRateBar.vue'
	export default {
		components: {
			BaseTable,BaseScoreRateBar
		},
		data() {
			return {
				isAllSubject:true,
				scoreRateBarData:[],
				currentClass:{
					stuCount:0,
					lineCount:0,
					totalAverage:0,
					standardDeviation:0
				},
				echartData: [],
				tableData: [],
				currentPR: [],
				subjectList: [],
				classAverage: 0,
				gradeAverage: 0,
				areaAverage: 0,
				warningIndex: 0,
				sortValue: 0,
				className: '',
				sortArr: [this.$t('totalAnalysis.ach_chart_text2'), this.$t('totalAnalysis.ach_chart_text3'), this.$t(
					'totalAnalysis.ach_chart_text4')],
				earlyPercentColumns: [{
						title: this.$t('totalAnalysis.base_name'),
						key: 'name',
						fixed: 'left',
						minWidth:100
					},
					{
						title: this.$t('totalAnalysis.base_id'),
						key: 'setNo',
						minWidth:100,
						renderType: function(h, params) {
						    return h('span', params.row.setNo || '-')
						}
					},
					{
						title: this.$t('totalAnalysis.ach_table_text2'),
						sortable: 'custom',
						key: 'score',
						minWidth:100
					},
					{
						title: this.$t('totalAnalysis.sca_chart_text1'),
						sortable: 'custom',
						key: 'sRate',
						minWidth:100,
						renderType: function(h, params) {
						    return h('span', (Number(params.row.sRate)).toFixed(2) + '%')
						},
					},
					{
						title: this.$t('totalAnalysis.ach_table_text8'),
						key: 'classRank',
						sortable: 'custom',
						minWidth:200,
						renderType: function(h, params) {
						    return h('span',  `${ params.row.classRank } （${ params.row.classPR }）`)
						}
					},
					{
						title: this.$t('totalAnalysis.ach_table_text9'),
						key: 'gradeRank',
						sortable: 'custom',
						minWidth:200,
						renderType: function(h, params) {
						    return h('span',  `${ params.row.gradeRank } （${ params.row.gradePR }）`)
						}
					},
				]
			}
		},

		created() {
			this.className = this.$route.query.name
		},

		methods: {
			warningTabClick(index) {
				this.warningIndex = index
			},

			handleSort(index) {
				let memberList = this.tableData
				if (index === 0) {
					this.echartData = memberList.sort(function(a, b) {
						return Number(a.setNo) - Number(b.setNo)
					})
				} else if (index === 1) {
					this.echartData = memberList.sort(function(a, b) {
						return Number(b.score) - Number(a.score)
					})
				} else {
					this.echartData = memberList.sort(function(a, b) {
						return Number(b.score) - Number(a.score)
					}).reverse()
				}
				this.drawLine(this.echartData)
			},

			onSelectChange(val) {
				this.tableData = this.onGetClassTable(val)
				this.drawLine(this.tableData)
			},

			goBack() {
				this.$store.commit('updateExportTable', [{
					tableRef: 'entryTable',
					tableName: '进线情况统计'
				}, {
					tableRef: 'entryRateTable',
					tableName: '进线率统计'
				}])
				this.$router.back(-1)
				this.$parent.isShowQuestions = false
			},
			
			/**
			 * 获取指定科目的表格数据
			 * @param subjectIndex
			 */
			onGetClassTable(subjectIndex) {
				let result = []
				let analysisJson = JSON.parse(JSON.stringify(this.getAnalysisJson))
				let curClassItem = analysisJson.classes.filter(i => i.className === this.className)[0]
				let studentIds = curClassItem.studentIds
				let singleSubjectItem = curClassItem.subjects[subjectIndex - 1]
				this.currentClass = curClassItem
				this.currentClass.standardDeviation = subjectIndex === 0 ? curClassItem.standardDeviation : singleSubjectItem.standard
				this.currentClass.totalAverage = subjectIndex === 0 ? curClassItem.totalAverage : singleSubjectItem.average
				this.currentClass.csRate = subjectIndex === 0 ? curClassItem.csRate : singleSubjectItem.sRate
				this.classAverage = subjectIndex === 0 ? curClassItem.totalAverage.toFixed(1) : singleSubjectItem.average
				
				// 判断当前选择科目是全科还是单科 赋予不同的值
				studentIds.forEach((stuId, stuIndex) => {
					let stuItem = analysisJson.students.filter(i => i.id === stuId)[0]
					let stuSubjectItem = subjectIndex === 0 ? null : analysisJson.students.filter(i => i.id === stuId)[0].subjects[subjectIndex - 1]
					let studentItemScores = subjectIndex === 0 ? {} : this.getStudentItemScore(stuIndex,analysisJson,subjectIndex - 1)
					let baseObj = {
						name: stuItem.name,
						setNo: stuItem.no,
						sRate: subjectIndex === 0 ? stuItem.sRate : stuSubjectItem.sRate,
						score: subjectIndex === 0 ? stuItem.total : stuSubjectItem.score,
						classPR: subjectIndex === 0 ? stuItem.cpr : stuSubjectItem.cpr,
						classRank: subjectIndex === 0 ? stuItem.csort : stuSubjectItem.csort,
						gradePR: subjectIndex === 0 ? stuItem.gpr : stuSubjectItem.gpr,
						gradeRank: subjectIndex === 0 ? stuItem.gsort : stuSubjectItem.gsort,
						areaPR: 0,
						areaRank: 0
					}
					result.push(Object.assign(baseObj,studentItemScores))
				})
				console.log(result)
				this.scoreRateBarData = result
				
				if(subjectIndex !== 0){
					// this.earlyPercentColumns.push
					let itemsLength = analysisJson.paper[subjectIndex - 1].value
					let itemsColumns = []
					itemsLength.forEach((i,index) => {
						itemsColumns.push({
							title: '题目' + (index + 1),
							key: 's' + (index + 1),
							minWidth:100
						})
					})
					this.earlyPercentColumns.splice(6,this.earlyPercentColumns.length - 6,...itemsColumns)
				}else{
					this.earlyPercentColumns.splice(6,this.earlyPercentColumns.length - 6)
				}
				return result
			},
			
			/* 获取每个学生每道题目的得分详细表 */
			getStudentItemScore(stuIndex,analysisJson,subjectIndex){
				let itemsLength = analysisJson.paper[subjectIndex].value
				let result = {}
				itemsLength.forEach((i,index) => {
					result['s'+ (index + 1)] = analysisJson.students[stuIndex].subjects[subjectIndex].scores[index]
				})
				return result
			},

			/**
			 * 渲染柱状图
			 * @param echartData
			 */
			drawLine(echartData) {
				let that = this
				let myBar = this.$echarts.init(document.getElementById('stuAverageBar'))
				var option = {
					legend: {
						top: 40,
						data: [{
								name: this.$t('totalAnalysis.ach_table_text2'),
								textStyle: {
									color: '#fff'
								}
							},
							{
								name: this.$t('totalAnalysis.ach_text4'),
								color: 'red',
								textStyle: {
									color: '#fff'
								}
							},
							{
								name: this.$t('totalAnalysis.ach_text5'),
								color: 'red',
								textStyle: {
									color: '#fff'
								}
							},
							{
								name: this.$t('totalAnalysis.ach_text6'),
								color: 'red',
								textStyle: {
									color: '#fff'
								}
							}
						]

					},
					tooltip: {
						show: true, // 是否显示提示框，默认为true
						trigger: 'axis', // 数据项图形触发
						axisPointer: {
							// 指示样式
							type: 'shadow',
							axis: 'auto',
							shadowStyle: {
								color: 'rgba(128,128,128,0.1)'
							}
						},
						padding: 5,
						textStyle: {
							color: '#fff'
						},
						formatter: function(params) {
							let name = echartData[params[0].dataIndex].name
							let result = name
							for (let i = 0; i < params.length; i++) {
								result += '<br>' + params[i].marker + params[i].seriesName + '：' + params[i].data
									.toFixed(2)
							}
							return result
						}
					},
					grid: {
						show: false,
						containLabel: true,
						height: 300,
						width: '75%',
						right:'18%',
						tooltip: {
							show: true,
							trigger: 'axis', // 触发类型
							textStyle: {
								color: '#666'
							}
						}
					},
					dataZoom: [{
						'show': true,
						'height': 10,
						'xAxisIndex': [
							0
						],
						bottom: 10,
						'start': 0,
						'end': 100,
						handleIcon: 'M512 497.821538m-418.264615 0a418.264615 418.264615 0 1 0 836.52923 0 418.264615 418.264615 0 1 0-836.52923 0Z',
						handleSize: '160%',
						handleStyle: {
							color: '#d3dee5'

						},
						textStyle: {
							color: '#fff'
						},
						borderColor: '#90979c'
					}, {
						'type': 'inside',
						'show': true,
						'height': 15,
						'start': 0,
						'end': 100
					}],
					// toolbox: {
					//  show: true,
					//  feature: {
					//    magicType: { show: true, type: ['line', 'bar'] },
					//    saveAsImage: { show: true }
					//  }
					// },
					xAxis: {
						show: true,
						offset: 0,
						type: 'category',
						nameTextStyle: {
							color: '#a2a2a2'
						},
						name: this.$t('totalAnalysis.base_id'),
						axisLabel: {
							show: true,
							inside: false,
							margin: 15,
							color: '#989898'
						},
						data: echartData.map(item => item.setNo || '-')
					},
					yAxis: {
						name: this.$t('totalAnalysis.ach_table_text2'),
						show: true,
						nameTextStyle: {
							color: '#a2a2a2'
						},
						type: 'value',
						axisLabel: {
							show: true,
							inside: false,
							rotate: 0,
							margin: 8,
							color: '#989898',
							fontSize: 12,
							fontFamily: 'Microsoft YaHei'
						},
						splitLine: {
							show: true,
							lineStyle: {
								color: '#4c504a',
								width: 0.5,
								type: 'solid'
							}
						}
					},
					series: [{
							name: this.$t('totalAnalysis.ach_table_text2'),
							type: 'bar',
							itemStyle: {
								normal: { // 渐变色
									color: '#07cdd8'
								},
							},
							barMaxWidth: 40,
							markPoint: {
								data: [{
										type: 'max',
										name: '最大值',
										itemStyle: {
											color: '#0099ff'
										}
									},
									{
										type: 'min',
										name: '最小值',
										itemStyle: {
											color: 'red'
										}
									}
								],

							},
							data: echartData.map(item => item.score)
						},
						{
							name: this.$t('totalAnalysis.ach_text4'),
							type: 'line',
							itemStyle: {
								color: 'yellow',
								width: 0
							},
							symbol: 'none',
							lineStyle: {
								type: 'dashed',
								width: 0
							},
							markLine: {
								data: [{
									type: 'average'
								}],
								lineStyle: {
									color: 'yellow',
									type: 'dashed'
								}
							},
							data: echartData.map(item => Number(this.classAverage))
						},
					]
				}

				// 绘制图表
				myBar.setOption(option)
				window.addEventListener('resize', function() {
					myBar.resize()
				})
			}

		},

		mounted() {
			this.$parent.isShowQuestions = true
			this.$refs.percentTable.$el.childNodes[1].style.borderRight = '0'

			if (this.getAnalysisJson) {
				this.tableData = this.onGetClassTable(0)
				this.subjectList = this.getAnalysisJson.subjects.map(item => item.name)
				this.drawLine(this.tableData)
			}

			this.$EventBus.$off('changeClassName')
			this.$EventBus.$on('changeClassName', val => {
				this.className = val
				this.tableData = this.onGetClassTable(0)
				this.subjectList = this.getAnalysisJson.subjects.map(item => item.name)
				this.drawLine(this.tableData)
				this.handleSort(this.sortValue)
			})

			this.$EventBus.$off('onEarlySubjectChange')
			this.$EventBus.$on('onEarlySubjectChange', index => {
				this.isAllSubject = index === 0
				this.onSelectChange(index)
				this.handleSort(this.sortValue)
			})
		},

		computed: {
			getAnalysisJson() {
				return this.$store.state.totalAnalysis.analysisJson
			}
		},
		watch: {
			getAnalysisJson(val) {
				if (!val) return
				this.tableData = this.onGetClassTable(0)
				this.subjectList = val.subjects.map(item => item.name)
				this.drawLine(this.tableData)
			}

		}
	}
</script>

<style src="./AchievementAnalysis.less" lang="less" scoped></style>
<style lang="less" scoped>
	.warning-info-item {
		.percent-name {
			font-size: 14px !important;
		}

		.percent-value {
			padding-left: 0 !important;
		}
	}

	.early-warning-tab {
		margin-left: 60px;
		font-size: 16px;
	}

	.early-warning-tab span {
		border-bottom: 2px solid #808080;
		margin-left: 20px;
		padding: 5px 0;
		cursor: pointer;
	}

	.early-warning-tab .early-warning-active {
		font-weight: bold;
		color: #07cdd8;
		border-color: #07cdd8;
	}

	#stuAverageBar {
		height: 400px;
	}

	.averageBarRow {
		position: relative;
	}

	.sort-box {
		position: absolute;
		right: 100px;
		top: 50px;
		font-size: 12px;
		z-index: 999;
		
	}
</style>

<style>
	.sort-box .ivu-input::-webkit-input-placeholder {
		color: #a9a9a9;
	}

	.sort-box .ivu-select {
		height: 25px;
		line-height: 25px;
		font-size: 12px;
	}

	.sort-box .ivu-select-single .ivu-select-selection {
		height: 25px;
		line-height: 25px;
		background: transparent;
		border: 1px solid #a9a9a9;
		box-shadow: none;
	}
	
	.sort-box .ivu-select-selected-value{
		line-height: 25px !important;
		height: 25px !important;
		font-size: 12px !important;
	}

	.sort-box .ivu-select-single .ivu-select-dropdown {
		/*background: #595959;*/
		font-size: 12px;
	}

	.sort-box .ivu-select-single .ivu-select-placeholder {
		height: 25px;
		line-height: 25px;
		font-size: 16px;
	}

	.sort-box .ivu-select-single .ivu-select-selected-value {
		color: #a9a9a9;
	}

	.sort-box .ivu-select-single .ivu-select-arrow {
		color: #a9a9a9;
	}
</style>
