<template>
	<div class="myTable">
		<!-- 科目选择以及表格备注 -->
		<div class="table-subject-select">
			<!-- <Select v-model="subjectSelectVal" style="width:150px" v-if="showSelect" @on-change="onSelectChange">
                <Option v-for="(item,index) in subjectList" :value="index" :key="index">{{ item }}</Option>
            </Select> -->
			<div class="myTable-title">{{ tableName }}</div>
			<div>
				<span @click="exportData(3)" class="table-export-btn">
					<Icon type="ios-share-alt" /> {{$t('totalAnalysis.exportTable').slice(0,2)}}
				</span>
				<span class="table-tips" v-if="tips">{{tips}}</span>
				<span class="table-tips" v-if="!tips"></span>
			</div>

		</div>
		<!-- 表格组件 -->
		<Table :border="isShowBorder" ref="table" :data="tableData" :columns="tableColumns"
			@on-sort-change="onSortChange" @on-filter-change="onFilterChange"></Table>

		<!-- 表格分页组件 -->
		<div style="margin: 10px;overflow: hidden" v-if="!noPage">
			<div style="float: right;margin-top: 20px;">
				<Page show-total size="small" :current="currentPage" :total="originData.length" :page-size="pageSize"
					:page-size-opts="pageSizeOpts" @on-change="pageChange" @on-page-size-change="pageSizeChange"
					show-sizer />
			</div>
		</div>

	</div>
</template>
<script>
	import excel from '@/utils/excel.js'
	export default {
		props: {
			columns: {

				type: Array,
				default: () => []
			},
			isScroll: {
				type: Boolean,
				default: false
			},
			tableDatas: {
				type: Array,
				default: () => []
			},
			showSelect: {
				type: Boolean,
				default: false
			},
			noPage: {
				type: Boolean,
				default: false
			},
			tips: {
				type: String,
				default: null
			},
			tableTitle: {
				type: String,
				default: null
			},
			pageSize: {
				type: Number,
				default: 10
			},
			tableName: {
				type: String,
				default: 'Analysis Table'
			},
			tableRef: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				isShowBorder: true,
				isFirst: true,
				subjectSelectVal: 0,
				tableData: [],
				firstData: [],
				propsData:[],
				originData: [],
				tableColumns: [],
				subjectList: [],
				currentPage: 1,
				pageSizes: 10,
				pageSizeOpts: [5, 10, 20, 30, 40],
				poperData: []
			}
		},
		created() {
			this.tableColumns = this.columns
			this.originData = this.tableDatas
			this.columns.forEach(item => {
				item.render = typeof item.renderType === 'function' ? item.renderType : this[item.renderType]
			})


		},
		methods: {

			// 导出表格
			exportData(type) {
				let classList = [this.$t('totalAnalysis.allClasses')].concat([...new Set(this.$store.state.totalAnalysis.analysisJson.classes.map(item => item.className))])
				let subjectName = null
				let className = classList[this.$store.state.totalAnalysis.curClassIndex + 1]
				if(this.$route.path === '/total' || this.$route.path === '/total/achievement/earlyWarning'){
					subjectName = this.$store.state.totalAnalysis.indexSubject
				}else{
					subjectName = this.$store.state.totalAnalysis.currentSubject
				}
				
				if (type === 3) {
					const params = {
						title: this.columns.map(i => i.title),
						key: this.columns.map(i => i.key),
						data: this.originData,
						autoWidth: true,
						filename: this.tableName + '(' + subjectName + '、' + className + ')'
					}
					excel.export_array_to_excel(params)
				} else {
					// 多个文件 打包下载
					const params = {
						title: this.columns.map(i => i.title),
						key: this.columns.map(i => i.key),
						data: this.originData,
						autoWidth: true,
						filename: this.tableName
					}
					this.$store.commit('updateExportParams', params)
				}
			},

			// 排序操作
			onSortChange(data) {
				let order = data.order // 当前排序方式 升序、降序、正常
				let key = data.key // 当前排序依据
				switch (order) {
					case 'asc':
						this.originData = this.tableDatas.sort((a, b) => {
							return Number(a[key]) - Number(b[key])
						})
						break
					case 'desc':
						this.originData = this.tableDatas.sort((a, b) => {
							return Number(b[key]) - Number(a[key])
						})
						break
					case 'normal':
						this.originData = JSON.parse(JSON.stringify(this.propsData))
						break
					default:
						break
				}
				this.pageChange(1)
			},

			// 筛选操作
			onFilterChange(val) {
				console.log(val)
				let filterKey = val.key
				let filterValue = val._filterChecked.length ? val._filterChecked[0] : null
				if (filterKey === 'className') {
					this.originData = filterValue ? this.tableDatas.filter(item => item.className === filterValue) : this
						.firstData
				}else if(filterKey === 'scatter'){
					this.originData = filterValue ? this.tableDatas.filter(item => item.scatter === filterValue) : this
						.firstData
				}else if(filterKey === 'areaName'){
					this.originData = filterValue ? this.tableDatas.filter(item => item.areaName === filterValue) : this
						.firstData
				}else if (filterKey === 'score') {
					const ipoint = this.$store.state.totalAnalysis.analysisJson.ipoint
					const touchScore = this.$store.state.totalAnalysis.analysisJson.touchScore
					switch (filterValue) {
						case 1:
							this.originData = this.tableDatas.filter(item => item.score >= ipoint)
							break
						case 2:
							this.originData = this.tableDatas.filter(item => item.score >= ipoint && item.score < (ipoint +
								touchScore))
							break
						default:
							this.originData = this.firstData
							break
					}
				}
				// this.tableDatas = this.originData
				this.pageChange(1)
			},

			// 分页操作
			pageChange(page) {
				let start = this.pageSizes * (page - 1)
				let end = this.pageSizes * page
				this.currentPage = page
				this.tableData = this.originData.slice(start, end)
				console.log(this.tableColumns)
				console.log(this.tableData)
			},

			// 页码操作
			pageSizeChange(val) {
				this.pageSizes = val
				this.pageChange(1)
			},

			// 下拉选择
			onSelectChange(val) {
				this.$emit('onSelectChange', val)
			},

			// 渲染班级标题以及相应点击事件
			renderClassName(h, params) {
				let that = this
				let row = params.row
				return h('span', {}, [
					h('span', {
						domProps: {
							className: 'table-rank-value'
						}
					}, params.row.classId),
				])
			},

			renderEventIndex(h, params) {
				let that = this
				return h('span', {
					on: {
						click: function() {
							that.$parent.$parent.$parent.isShowQuestions = true
							that.$router.push({
								path: '/total/questionList',
								query: {
									QIndex: params.row.id
								}
							})
						}
					},
					style: {
						cursor: 'pointer',
						color: '#00ffd2',
						fontWeight: 'bold'
					}
				}, params.row.id)
			},

			// 总分排名Render
			renderRank(h, params) {
				const row = params.row
				return h('span', {
					domProps: {
						className: 'badge-wrap'
					}
				}, [
					h('span', {
						domProps: {
							className: 'table-rank-badge'
						},
						style: {
							color: row.changesStatus === 1 ? '#0ccb0c' : '#ff5d5d'
						}
					}, (row.changesStatus === 1 && row.changesVal !== 0) ? '+' + row.changesVal : (row
						.changesStatus === -1 && row.changesVal !== 0) ? '-' + row.changesVal : ''),
					h('span', {
						domProps: {
							className: 'table-rank-value'
						}
					}, row.gradeRank)

				])
			},

			// 折线图趋势变化
			renderLineChange(h, params) {
				const row = params.row
				return h('Poptip', {
					props: {
						trigger: 'hover',
						placement: 'right',
						transfer: true
					},
					on: {
						// 鼠标触发气泡事件
						'on-popper-show': () => {
							console.log(row.poperData)
							// this.poperData = row.poperData
						}
					}
				}, [
					h('Icon', {
						props: {
							type: row.classRank === 1 ? 'md-trending-up' : row.classRank === 2 ?
								'md-trending-down' : 'md-git-commit',
							color: row.classRank === 1 ? '#13ff13' : row.classRank === 2 ? '#fd4e4e' :
								'yellow',
							size: '22'
						},
						style: {
							cursor: 'pointer'
						}
					}),
					h('div', {
						slot: 'content'
					}, [h('BaseChangeLine', {
						props: {
							poperData: row.poperData,
							isLoad: true,
							lineColor: row.classRank === 1 ? 'green' : row.classRank === 2 ?
								'#fd4e4e' : '#ffcc33'
						}
					})])
				])
			},

			// 排名变化
			renderRankChange(h, params) {
				const row = params.row
				return h('span', [
					h('Icon', {
						props: {
							type: (row.changesStatus === 1 && row.changesVal !== 0) ? 'md-arrow-up' : (row
									.changesStatus === -1 && row.changesVal !== 0) ? 'md-arrow-down' :
								'md-git-commit',
							color: (row.changesStatus === 1 && row.changesVal !== 0) ? '#13ff13' : (row
								.changesStatus === -1 && row.changesVal !== 0) ? '#fd4e4e' : 'yellow',
							size: '22'
						},
						style: {
							cursor: 'pointer'
						}
					}),
					h('span', {
						domProps: {
							className: 'table-rank-value'
						}
					}, row.changesStatus === 0 ? '' : row.changesVal)
				])
			},

			// 是否进线
			renderEntry(h, params) {
				let that = this
				const row = params.row
				const ipoint = this.$store.state.totalAnalysis.analysisJson.ipoint
				const touchScore = this.$store.state.totalAnalysis.analysisJson.touchScore
				return h('span', [
					h('span', {
							domProps: {
								className: 'table-entry-status'
							},
							style: {
								cursor: 'pointer',
								background: row.score >= (ipoint + touchScore) ? '#209a31' : row.score >= ipoint ?
									'#00767d' : 'transparent'
							}
						}, row.score >= (ipoint + touchScore) ? that.$t('totalAnalysis.myTable.inner') : row.score >=
						ipoint ? that.$t('totalAnalysis.myTable.outer') : ''),
					h('span', {
						domProps: {
							className: 'table-rank-value'
						}
					}, row.score)
				])
			},

			// 变化状态
			renderStauts(h, params) {
				const row = params.row
				return h('span', [
					h('Icon', {
						props: {
							type: row.classRank === 1 ? 'md-arrow-up' : row.classRank === 2 ? 'md-arrow-down' :
								'md-git-commit',
							color: row.classRank === 1 ? '#13ff13' : row.classRank === 2 ? '#fd4e4e' :
								'yellow',
							size: '22'
						},
						style: {
							cursor: 'pointer'
						}
					})
				])
			},

			// 渲染应努力题号
			renderHard(h, params) {
				let that = this
				const list = params.row.hardList ? params.row.hardList.split(',') : params.row.itemNO.split(',')
				return h('span', {
					style: {
						textAlign: 'left'
					}
				}, list.sort((a,b) => a - b).map(function(item, index) {
					return h('span', {
						style: {
							fontSize: '16px',
							fontWeight: '600',
							color: '#03efdb',
							cursor: 'pointer',
							display: 'inline-block',
							float: 'left'
						},
						on: {
							'click': function() {
								that.$parent.$parent.$parent.isShowQuestions = true
								that.$router.push({
									path: '/total/questionList',
									query: {
										QIndex: isNaN(item) ? 1 : item
									}
								})
							}
						}
					}, item + (index === list.length - 1 ? '' : ' , '))
				}))
			},

			// 渲染应小心题号
			renderCareful(h, params) {
				let that = this
				const row = params.row
				const list = params.row.carefulList ? params.row.carefulList.split(',') : []
				return h('span', list.sort((a,b) => a - b).map(function(item, index) {
					return h('span', {
						style: {
							fontSize: '16px',
							fontWeight: '600',
							color: '#03efdb',
							cursor: 'pointer',
							display: 'inline-block',
							float: 'left'
							// textDecoration: "underline"
						},
						on: {
							'click': function() {
								that.$parent.$parent.$parent.isShowQuestions = true
								that.$router.push({
									path: '/total/questionList',
									query: {
										QIndex: isNaN(item) ? 1 : item
									}
								})
							}
						}
					}, item + (index === list.length - 1 ? '' : ' , '))
				}))
			},

			// 渲染百分比数据
			renderPercent(h, params) {
				return h('span', params.row.scoreRate + '%')
			},
			
			renderCsRate(h, params) {
				return h('span', params.row.csRate + '%')
			},
			
			renderOverRate(h, params) {
				return h('span', params.row.overAverageRate + '%')
			},
		},

		mounted() {
			if (this.noPage) {
				this.pageSizes = 999999
				this.pageChange(1)
				this.currentPage = 1
			}
		},

		computed: {
			exportTableRefs() {
				return this.$store.state.totalAnalysis.exportTableRefs
			}
		},

		watch: {
			tableDatas:{
				handler(data,oldData){
					let earlyFlag = data.length && oldData.length && Object.keys(data[0]).length > Object.keys(oldData[0]).length
					this.originData = JSON.parse(JSON.stringify(data))
					this.firstData = JSON.parse(JSON.stringify(data))
					if (this.isFirst || earlyFlag) this.propsData = JSON.parse(JSON.stringify(data))
					// 获取当前测评班级数据
					this.subjectList = this.$store.state.totalAnalysis.subjectList
					this.pageChange(1)
					this.isFirst = false
				},
			},
			columns:{
				handler(n,o){
					n.forEach(item => {
						item.render = item.renderType ? (typeof item.renderType === 'function' ? item.renderType : this[item.renderType]) : undefined
						item.filterRemote = function(value, row){
						}
					})
					this.tableColumns = n
				},
				deep:true
			},
			tableName:{
				handler(n,o){
					console.log(n)
				},
				deep:true
			},
			exportTableRefs: {
				handler(n) {
					// 如果导出的表格包含当前表格 则直接运行下载
					if (n.length && n.indexOf(this.tableRef) > -1) {
						// 如果选择下载的表格数量大于1 则进行打包下载
						if (n.length > 1) {
							this.exportData(4)
						} else {
							this.exportData(3)
						}
					}
				},
				deep: true
			}
		}

	}
</script>

<style>
	.myTable {
		width: 100%;
		/*height: 400px;*/
		/*padding: 20px 0;*/
		padding-right: 20px;
		margin-top: 20px;
		margin: 0 auto;
		display: block;
		user-select: none !important;
	}

	.myTable .ivu-table td,
	.myTable .ivu-table th {
		/*border: none;*/
		color: #e4eadb;
		border-color: #595959;
	}

	.myTable .ivu-table-wrapper {
		/*border:none;*/
		border-color: #595959;
		border-right: 1px solid #595959;
	}

	.myTable .ivu-table::before,
	.myTable .ivu-table::after {
		height: 1px;
		background: #595959;
	}

	.myTable .ivu-table {
		box-sizing: border-box;
		/*border:1px solid #595959;*/
	}

	.myTable .ivu-table,
	.myTable .ivu-table td {
		background: #343434;
		text-align: center;
		position: relative;
	}

	.myTable .ivu-table th {
		background: rgba(107, 107, 107, 0.19);
		text-align: center;
		position: relative;
	}

	.myTable .ivu-table-sort {
		margin-left: -6px;
	}

	.myTable .ivu-table-sort i {
		color: #fff;
		margin-left: 1px;
	}

	.myTable .ivu-table-sort i.on {
		color: #4cf8da;
	}

	.myTable .ivu-table-header .ivu-table-cell {
		font-size: 14px;
		font-weight: bold;
	}

	.myTable .ivu-table-header {
		background: rgba(228, 234, 219, 0.08);
	}

	.myTable .table-rank-value {
		margin-left: 10px;
		vertical-align: middle;
		font-size: 14px;
	}

	.myTable .table-rank-badge {
		position: absolute;
		right: 10px;
		top: 12px;
		font-size: 14px;
		padding: 2px 14px;
		color: #e4eadb;
	}

	.myTable .badge-wrap .ivu-icon,
	.myTable .badge-wrap img {
		position: absolute;
		left: 7px;
		top: 12px;
	}

	.myTable .ivu-page-item {
		background: rgba(40, 40, 40, .5);
	}

	.myTable .ivu-page-item:hover {
		border-color: #e4eadb;
	}

	.myTable .ivu-page-item-active {
		background: #bfbfb9;
	}

	.myTable .ivu-page-item a {
		color: #f1f1f1;
	}

	.myTable .ivu-page-next,
	.myTable .ivu-page-prev {
		background: rgba(0, 0, 0, 0);
	}

	.myTable .ivu-page-next a,
	.myTable .ivu-page-prev a {
		color: #e4eadb;
	}

	.myTable .ivu-page-next:hover,
	.myTable .ivu-page-prev:hover {
		border-color: #e4eadb;
	}

	.myTable .ivu-page-item-active,
	.myTable .ivu-page-item:hover a {
		border-color: #e4eadb;
	}

	.myTable .ivu-page-item-active a {
		color: #595959;
	}

	.myTable .ivu-table-fixed {
		/*padding-top:3px;*/
		background: #282828;
	}

	.myTable .ivu-table-fixed-right::before,
	.ivu-table-fixed::before {
		height: 0;
	}

	.table-subject-select {
		position: relative;
		display: flex;
		justify-content: space-between;
		padding-right: 5px;
		height: 40px;
		margin-bottom: 10px;
	}

	.table-subject-select .table-tips {
		font-size: 14px;
		color: #4cf8da;
		font-weight: bold;
		position: absolute;
		right: 65px;
		top: 10px;
	}

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

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

	.table-subject-select .ivu-select-single .ivu-select-arrow {
		/*top:76%;*/
	}

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

	.table-subject-select .table-export-btn {
		font-size: 14px;
		font-weight: bold;
		width: 50px;
		position: absolute;
		right: 5px;
		top: 10px;
		cursor: pointer;
	}

	.myTable .table-entry-status {
		position: absolute;
		right: 20px;
		top: 15px;
		background: #209a31;
		width: 15px;
		height: 15px;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10px;
	}

	.ivu-table-overflowX::-webkit-scrollbar {
		height: 12px !important;
	}

	.ivu-table-overflowX::-webkit-scrollbar-track {
		border-radius: 0px;
		display: none;
	}

	.ivu-table-overflowX::-webkit-scrollbar-thumb {
		border-radius: 0px;
		background: #949494;
	}

	.myTable .ivu-select-small.ivu-select-single .ivu-select-selection .ivu-select-selected-value {
		height: 27px;
		line-height: 27px;
		font-size: 12px;
	}

	.myTable .myTable-title {
		font-size: 16px;
	}
</style>
