<template>
	<view class="table_box">
		<view class="boxlist">
		</view>
		<scroll-view scroll-x scroll-y :class="tabHeight" @scrolltolower="scrolltolower" class="lips">
			<uni-table stripe border :loading="loading" style="min-height: 100%;">
				<uni-tr id="lyy-thead" :class="headerFixed?'fixed-head':''" style="display: flex;">
					<uni-th v-for="(item,index) in headers" :key="index" :width="item.widtd" align="center" :style="{
					  display:item.hidden?'none':'flex',justifyContent: 'center',
					  left:fixedLeft(index),
					  position:index<=columnFixed-1?'sticky':'unset',
					  zIndex:index<=columnFixed-1?999:99,
					  backgroundColor:'inherit'
					  }">
						<view @click="doSort(item)" style="display: flex;flex-direction: row;justify-content: center;">
							<text :style="{lineHeight:'20px'}">{{item.label}}</text>
							<view class="header-icon"
								style="line-height:8px;display:flex;flex-direction:column;margin-left:10px;justify-content: center;"
								v-if="item.sort">
								<text class="iconfont icon-arrow-up"
									:style="{fontSize:'8px',height:'10px',color:lastSortItem===item.key&&sortWay=='asc'?'#333':'#bcbcbc'}" />

								<text class="iconfont icon-arrow-down"
									:style="{fontSize:'8px',height:'10px',color:lastSortItem===item.key&&sortWay=='desc'?'#333':'#bcbcbc'}" />
							</view>
						</view>
					</uni-th>
				</uni-tr>
				<!--<uni-tr v-if="headerFixed" :style="{height: theadHeight}">
            </uni-tr>
            <!-- <uni-td class="no_data" align="center">暂无数据</uni-td> -->
				<!-- <view v-if="contents.length<1" class="no_data">暂无数据</view> -->
				<template v-if="contents.length>0">
					<uni-tr v-for="(content,sindex) in sortContents" :key="sindex"
						style="display:flex;table-layout: fixed;min-width: 100%;" @click.native="rowClick(content)">
						<uni-td v-for="(header,hindex) in headers" :key="hindex" :width="header.widtd" align="center"
							:style="{display:header.hidden?'none':'table-cell',textAlign:'center',
					  left:fixedLeft(hindex),
					  position:hindex<=columnFixed-1?'sticky':'unset',
					  zIndex:hindex<=columnFixed-1?9:'unset',
					  backgroundColor:'inherit'}">
							<template v-if="header.format!==undefined">
								<lyy-progress
									v-if="header.format.type==='progress'&&!isNaN(parseFloat(content[header.key]))"
									:percent="content[header.key].toFixed(2)" show-info round></lyy-progress>
								<view v-else-if="header.format.type==='html'" v-html="content[header.key]"></view>
								<text v-else>{{content[header.key]||emptyString}}</text>
							</template>
							<template v-if="header.label == '告警状态'">
								<text
									:class="[content[header.key] ==2?'warnColor':'']">{{content[header.key] === 0 ? '待处理':content[header.key] === 1 ? '处理中' : '已处理'}}</text>
							</template>
							<template v-else>
								<view v-if="header.label == '操作' && !battery" class="editColor" @click="EditAlarm(content)">处理
								</view>
								<view v-if="header.label == '操作' && battery" class="editColor" @click="EditAlarmInfo(content)">详情
								</view>
								<view v-if="header.label == '时段明细'" class="editColor" @click="EditAlarmDetail(content)">明细
								</view>
								<text v-else>{{content[header.key]||emptyString}}</text>
							</template>
						</uni-td>
					</uni-tr>
				</template>

				<uni-tr v-if="totalRow.length>0" style="min-width: 100%;display: flex;">
					<uni-td v-for="(header,index) in headers" :key="Math.random()" align="center" :style="{textAlign: 'center',display:header.hidden?'none':'table-cell',width:header.width,
                  left:fixedLeft(index),
                  zIndex:index<=columnFixed-1?9:'unset',
                  position:index<=columnFixed-1?'sticky':'unset',
                  backgroundColor:'inherit'}">
					</uni-td>
				</uni-tr>
			</uni-table>
			<uni-load-more v-show="showLoadMore" :status="loadMore"></uni-load-more>
		</scroll-view>
	</view>
</template>

<script>
	import lyyProgress from './lyy-progress'
	/**
	 * lyyTable ver1.3.3
	 * @description lyyTable表格组件 ver1.3.3
	 */
	export default {
		name: "lyyTable",
		components: {
			lyyProgress
		},
		data() {
			return {
				lastSortItem: '', //上一次排序列
				sortWay: 'none', //默认无排序
				sortIndex: 0,
				sortContents: [], //排序时的表格内容
				footContent: {},
				scrollHeight: '',
				theadHeight: '',
				tabHeight: null,
			}
		},
		props: {
			faultDrawer: {
				type: Function
			},
			//显示加载
			loading: {
				type: Boolean,
				default: false
			},
			//上拉加载文字，参考uni-load-more
			loadMore: {
				type: String,
				default: 'more'
			},
			//是否显示上拉加载组件
			showLoadMore: {
				default: Boolean,
				default: false
			},
			//固定表头
			headerFixed: {
				type: Boolean,
				default: false
			},
			//服务记录是否显示详情
			battery: {
				type: Number,
				default:3
			},
			//固定首列 ver1.3.3弃用
			/*firstColumnFixed: {
			    type: Boolean,
			    default: false
			},*/
			//固定列数 ver1.3.3新增
			columnFixed: {
				type: Number,
				default: 0
			},
			//排序方式
			sortWays: {
				type: Array,
				default: () => ['none', 'asc', 'desc']
			},
			//数据为空时的占位符
			emptyString: {
				type: String,
				default: '-'
			},
			//表头
			headers: {
				type: Array,
				default: [],
			},
			//表格数据
			contents: {
				type: Array,
				default: []
			},
			//合计列
			totalRow: {
				type: Array,
				default: () => []
			}
		},
		mounted() {
			//uni.setStorageSync('contents',this.contents)
			this.sortContents = JSON.parse(JSON.stringify(this.contents))
			this.renderContents()
			this.createTotalRow()
			//ver 1.2.0 修复 uni-table width 问题
			/*this.$nextTick(() => {
			    console.log('abc',this.$refs)
			    const query = uni.createSelectorQuery().in(this)
			    query.select('.uni-table').boundingClientRect(dom=>{
			        console.log(123456,dom)
			    }).exec()
			    this.$refs['uni-table'].removeAttribute('style')
			})*/
			//ver 1.2.0 新增 固定表头
			/*if (this.headerFixed) {
			    /*var wHeight = document.body.clientHeight
			    var tablePoseY = document.getElementById('lyy-tbody').getBoundingClientRect().y
			    document.getElementById('lyy-tbody').style.height = wHeight - tablePoseY + 'px'
			    const query = uni.createSelectorQuery().in(this)

			    query.select('#lyy-thead').boundingClientRect(dom => {
			        console.log(dom)
			        this.theadHeight = dom.height + 'px'
			    }).exec()
			}*/
		},
		watch: {
			contents: {

				handler(value) {
					console.log(value)
					this.sortContents = JSON.parse(JSON.stringify(value))
					this.renderContents()
					this.createTotalRow()
					this.lastSortItem = ''
					this.sortWay = 'none'
					for (var header of this.headers) {
						this.renderTotalRow(header)
					}
					this.$forceUpdate()
					if (value.length > 9) {
						this.tabHeight = 'container'
					} else {
						this.tabHeight = null
					}
				},
				deep: true

			},
			//监听排序变化
			sortChange(value) {
				var that = this
				var contents = JSON.parse(JSON.stringify(that.contents))
				switch (value.sortWay) {
					case 'none':
						that.sortContents = contents
						this.renderContents()
						break
					case 'asc': //正序
						that.sortContents = that.sortContents.sort(function(a, b) {
							//需要排序的列为数字时直接计算
							if (!isNaN(parseFloat(a[that.lastSortItem])) && !isNaN(parseFloat(b[that
									.lastSortItem]))) {
								return a[that.lastSortItem] - b[that.lastSortItem]
							}
							//非数字转为ASCII排序
							else {
								return a[that.lastSortItem].charCodeAt() - b[that.lastSortItem].charCodeAt()
							}
						})
						break
					case 'desc': //倒序
						that.sortContents = that.sortContents.sort(function(a, b) {
							if (!isNaN(parseFloat(a[that.lastSortItem])) && !isNaN(parseFloat(b[that
									.lastSortItem]))) {
								return b[that.lastSortItem] - a[that.lastSortItem]
							} else {
								return b[that.lastSortItem].charCodeAt() - a[that.lastSortItem].charCodeAt()
							}
						})
						break
				}
				that.$forceUpdate()
			}
		},
		computed: {
			//将排序方式、上次排序列作为一个整体进行监听，不然会出现切换排序列不排序的现象
			sortChange() {
				var {
					sortWay,
					lastSortItem
				} = this
				return {
					sortWay,
					lastSortItem
				}
			}
		},
		methods: {
			//触发故障告警抽屉
			EditAlarm(row) {
				this.$emit('faultDrawer', row)
			},
			//换电详情弹出框
			EditAlarmInfo(row) {
				this.$emit('drawer', row)
			},
			//充电明细弹出框
			EditAlarmDetail(row) {
				this.$emit('charging', row)
			},
			//点击排序表头时存储上次排序列名，并循环切换排序方式
			doSort(item) {

				if (item.sort) {

					if (this.lastSortItem !== item.key) {
						this.lastSortItem = item.key
						this.sortIndex = 0
						this.sortIndex++
						this.sortWay = this.sortWays[this.sortIndex]
					} else {
						if (this.sortIndex < 2) {
							this.sortIndex++
							this.sortWay = this.sortWays[this.sortIndex]
						} else {
							this.sortIndex = 0
							this.sortWay = this.sortWays[0]
						}
					}
				}
			},
			//表格内容渲染
			renderContents() {
				const headers = this.headers
				//防止修改穿透
				var contents = JSON.parse(JSON.stringify(this.contents))
				//var contents=uni.getStorageSync('contents')
				let sortContents = JSON.parse(JSON.stringify(this.sortContents))
				var newArr = []
				var result = ''
				sortContents.forEach(function(content, index) {
					var item = content
					headers.forEach(function(header) {
						//字符类型格式化
						if (typeof header.format !== 'undefined' && (header.format.type === 'string' ||
								header.format.type === 'html')) {
							var template = header.format.template
							var keys = header.format.keys
							//console.log(typeof template)
							if (typeof template === 'function') {
								var arg = []
								keys.forEach((el, i) => {
									arg.push(contents[index][el])
								})
								result = template(arg)
								//console.log(result)
							} else {
								keys.forEach((el, i) => {
									var value = contents[index][el]
									var reg = new RegExp('\\{' + i + '}', 'g')
									template = template.replace(reg, value)
								})
								result = template
							}
							item[header.key] = result
						}
						//计算类型格式化
						else if (typeof header.format !== 'undefined' && (header.format.type ===
								'compute' || header.format.type === 'progress')) {
							//console.log(header.format.template)
							var temp = header.format.template
							var keys = header.format.keys
							keys.forEach((el, i) => {
								var reg = new RegExp('\\{' + i + '}', 'g')
								temp = temp.replace(reg, contents[index][el])
							})
							//console.log(temp)
							item[header.key] = eval(temp)
							//this.sortContents[index][header.key]=result
						}
					})
					newArr.push(item)
				})
				this.sortContents = newArr
			},
			createTotalRow() {
				if (this.totalRow.length > 0 && this.sortContents[0] !== undefined) {
					/*var obj = {...this.contents[0]}
					console.log(obj)
					for (var i in obj) {
					    this.footContent[i] = obj[i]
					}*/
					this.footContent = JSON.parse(JSON.stringify(this.sortContents[0]))
					for (var i in this.footContent) {
						var result = 0
						if (this.sortContents.length > 0) {
							for (var j in this.sortContents) {
								result += parseFloat(this.sortContents[j][i]) || 0
							}
						}
						this.footContent[i] = result
					}
				}
			},
			//合计列渲染
			renderTotalRow(header) {
				var content = JSON.parse(JSON.stringify(this.footContent))
				var result = this.emptyString
				if (this.totalRow.indexOf(header.key) > -1) {
					if (typeof header.format !== 'undefined' && header.format.type === 'progress') {
						var temp = header.format.template
						var keys = header.format.keys
						for (var index in keys) {
							var reg = new RegExp('\\{' + index + '}', 'g')
							temp = temp.replace(reg, content[keys[index]])
						}
						result = eval(temp)
						result = isNaN(result) ? 0 : result.toFixed(2)
					} else {
						if (content[header.key] != null && !isNaN(content[header.key])) {
							result = content[header.key]
						}
					}
				}
				return result
			},
			//行点击事件
			rowClick(data) {
				this.$emit('rowClick', data)
			},
			//上拉加载事件
			scrolltolower(e) {
				if (e.detail.direction == 'bottom') {
					this.$emit('onPullup')
				}
			},
			//固定列left计算
			fixedLeft(index) {
				var headers = this.headers.filter(item => !item.hidden)
				var left = 'calc(0px'
				for (var i = 1; i < index + 1; i++) {
					left += ' + ' + headers[i - 1].width
				}
				left += ')'
				return left
			}
		}
	}
</script>

<style scoped lang="scss">
	@import './css/iconfont.css';
	.boxlist {
		width: 100%;
		height: 5px;
		position: sticky;
		z-index: 999;
		background: #111827;
		top: -5px;
	}

	.table_box {
		height: 520px;
		overflow: hidden;
	}

	.warnColor {
		color: #636C97;
	}

	.editColor {
		color: #55B693;
		font-weight: bold;
	}

	.container {
		height: 100%;
		margin: 0;
		padding: 0;
	}

	.uni-table-scroll {
		overflow: unset !important;
		margin: 0;
		padding: 0;
		// height: 576px;
	}

	.no_data {
		position: absolute;
		width: 100%;
		background-color: #FFF;
		height: 50px;
		text-align: center;
		line-height: 50px;
	}

	.fixed-head {
		position: sticky;
		top: 0px;
		z-index: 99;
		height: 50px;
	}

	.uni-table-th {
		width: 142px;
	}

	.uni-table-td {
		width: 142px;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;

	}

	::v-deep .uni-table-text {
		position: fixed;
		right: 0;
		left: 240px;
		text-align: center;
		font-size: 14px;
		color: #999;
		width: 1001px;
	}

	/*修复滑动时偏移1px问题*/
	.table--border {
		border-top: none;
		border-left: none;
	}

	::v-deep .table--border {
		border: none !important;
	}

	::v-deep .uni-load-more {
		position: fixed;
		bottom: 20px;
		z-index: 9999;
		width: 1000px;
		text-align: center;

		.uni-load-more__text {
			font-size: 14px;
			color: #636C97 !important;
		}
	}

	::v-deep .uni-table {
		background: none;

		.empty-border {
			border: none;
			height: 80px;
			line-height: 80px;
		}

		.uni-table-th {
			color: #FFFFFF;
		}

		.uni-table-td {
			font-weight: 400;
			color: #FFFFFF;
			font-size: 14px;
			height: 50px;
			line-height: 32px;
		}

		.uni-table-tr:nth-child(n + 2):hover {
			background-color: #1e2f36;
		}
	}

	#lyy-thead {
		/*min-width: 750upx;*/
		display: table;
		height: 50px;
		background: #1D283E;
		box-shadow: 0px 1px 0px 0px #2F3C86;
		font-weight: 600;
		color: #FFFFFF;
		font-size: 14px;
	}

	// ::v-deep .table--stripe .uni-table-tr:nth-child(2n + 1) {
	// 	background-color: #141B2B;
	// 	box-shadow: 0px 1px 0px 0px #292D46, 0px -1px 0px 0px #292D46;
	// }
	.table--stripe .uni-table-tr:nth-child(2n + 3) {
		background-color: #111827;
	}

	::v-deep .uni-table-tr {
		background-color: #141B2B;
		// box-shadow: 0px 1px 0px 0px #292D46;
		border-bottom: #292D46 solid 1px;
	}
</style>
