<template>
	<van-popup
		v-model="actionState"
		class="quick-enter-wrapper"
		:class="{'in_top': scrollBottomState }"
		round
		:position="isPosition"
		:overlay="false"
		:close-on-click-overlay="false"
		:lock-scroll="false"
		:style="popupStyle"
		@opened="actionStateOpened = true"
		@closed="actionStateOpened = false"
		get-container="body"
	>
		<main class="main-wrapper">
			<aside class="close" :class="{'opened': actionStateOpened}" @click="close">
				<span class="left line"></span>
				<span class="right line"></span>
			</aside>
			<section class="location-inner">
				<div class="location-box">
					<i class="iconfont icon-zuobiao icon_location"></i>
					<div class="location">
						<div class="location-item" v-for="(items, index) in location" :key="index"
							:class="{'active': islocationState(items)}">
							<div class="item-box">
								<i class="iconfont" :class="isLocationIcon(items)"></i>
								<span>{{ items.title | ellipsis }}</span>
							</div>
						</div>
					</div>
				</div>
				<aside class="control-box">
					<div class="control">
						<div v-for="(items, index) in controlList" :key="index" class="control-item"
							:class="{'active': islocationState(items)}" @click="handleChangeDirection(items)">
							<i class="iconfont" :class="isControlIcon(items)"></i>
							<span>{{ items.title | ellipsis }}</span>
						</div>
					</div>
				</aside>
			</section>
			<footer class="input-box">
				<van-field ref="quickInput" v-model="quickInput" id="quick-input" class="quick-input" autosize clearable
					clear-trigger="always" clickable :error="inputError" type="text" :placeholder="isInputPho"
					@input="autoInputting" @keyup.enter="handleConfirm" @click="handleClickInput" />
				<div class="tag-box">
					<van-tag class="tag-input" plain :color="isTagInputColor">
						{{ `${quickInputList.length}/${canEditList.length}` }}
					</van-tag>
					<template v-for="(item, index) in canEditList">
						<van-tag :key="index" :color="isTagListColorB(index)" :text-color="isTagListColorT(index)"
							v-show="index <= showTagListLength" @click="handleLocationTag(index)">
							<span class="tag-inner">
								{{ item.title | ellipsis }}
							</span>
						</van-tag>
					</template>
				</div>
			</footer>
		</main>
	</van-popup>
</template>

<script>

export default {
	name: 'LjQuickEnter',
	filters: {
		ellipsis(value) {
			let val = value.trim();
			if (!val) return ''
			if (val.length > 4) {
				return val.slice(0, 4) + '...'
			}
			return value
		}
	},
	data() {
		return {
			actionState: false, // 窗体显示与隐藏
			actionStateOpened: false,
			quickInput: '',
			inputError: false,
			lastState: false, // 上次窗体的到底了吗
			scrollBottomState: false, // 当前到底了吗
			popupStyle: {},
			titleTipsTimer: null,
			titleTipsTime: 0, // 计时器
			// headerSubHeight: '', // 标题高度
			verticalOrNot: true, // true:纵向录入，false:横向录入
			quickInputList: [], // 输入输入识别
			quickInputIndex: -1, // 记录光标当前索引
			canEditList: [], // 可录入列表
			showTagListLength: 0, // 展示已识别录入
			colCanEdit: [], // 记录纵向可录入数据
			rowCanEdit: [], // 记录横向可录入数据
			location: [], // 坐标
			controlList: [{
					type: 'col',
					title: '纵向'
				},
				{
					type: 'row',
					title: '横向'
				}
			],
			draftName: "quickEnterState", // 记录verticalOrNot用户习惯
		};
	},
	props: {
		// 默认录入方向
		direction: {
			type: String,
			default: 'vertical'
		},
		// 记录用户历史录入方向
		tableName: {
			type: String,
			default: ''
		},
		// 关键字段名
		propertyName: {
			type: String,
			default: ''
		}
	},
	computed: {
		isPosition() {
			// if (this.scrollBottomState != this.lastState) {
			//   this.lastState = this.scrollBottomState;
			//   if (this.scrollBottomState) {
			//     this.popupStyle.top = this.headerSubHeight;
			//     return 'top'
			//   } else {
			//     this.popupStyle = {}
			//     return 'bottom'
			//   }
			// } else {
			return this.scrollBottomState ? 'top' : 'bottom';
			// }
		},
		isTipsDirection() {
			return this.verticalOrNot ? '向下' : '向右'
		},
		isTagInputColor() {
			return this.quickInputList.length > this.canEditList.length ? '#f44336' : '#bdbdbd'
		},
		isTagListColorB(idx) {
			return function (idx) {	
				return idx == this.quickInputIndex ? '#d1edfd' : '#f2f2f2';
			}
		},
		isTagListColorT(idx) {
			return function (idx) {
				return idx == this.quickInputIndex ? '#2196f3' : '#828282';
			}
		},
		isLocationIcon(items) {
			return function (items) {
				return items.type == 'col' ? 'icon-zongxiang1' : 'icon-hengxiang'
			}
		},
		isControlIcon(items) {
			return function (items) {
				return items.type == 'col' ? 'icon-zongxiang' : 'icon-hengxiang1'
			}
		},
		islocationState(items) {
			return function (items) {
				if (items.type == 'col' && this.verticalOrNot) {
					return true
				}
				if (items.type == 'row' && !this.verticalOrNot) {
					return true
				}
				return false
			}
		},
		isInputPho() {
			let pho = '';
			if (this.titleTipsTime % 2 == 0) {
				pho = `以坐标为起点，${this.isTipsDirection}录入数据`;
			} else {
				pho = `使用" "(空格)或"，" 或"。"分隔数据`
			}
			return pho;
		}
	},
	mounted() {
		// 初始化
		this.autoCycleReminder();
		let quickEnterStorage = $lj.getStorage(this.draftName);
		if (this.tableName && quickEnterStorage && quickEnterStorage[this.tableName]) {
			this.verticalOrNot = quickEnterStorage[this.tableName]
		} else {
			this.verticalOrNot = this.direction.toLowerCase() == 'vertical'
		}
		// if (document.querySelector("header")) {
		//   this.headerSubHeight = document.querySelector("header").offsetHeight + document.querySelector("header").offsetTop + "px";
		// }
		// window.onscroll = () => {
		// 	console.log('触发了滚动');
		//   this.autoIsScrollBottom();
		// };
		// window.onresize = () => {
		// 	console.log('触发了reseize');
		//   this.autoIsScrollBottom();
		// };
	},
	methods: {
		/** 循环提示器 */
		autoCycleReminder() {
			clearInterval(this.titleTipsTimer);
			this.titleTipsTimer = setInterval(() => {
				this.titleTipsTime++;
			}, 6000);
		},
		/** 检测滚动是否到底 */
		// autoIsScrollBottom() {
		//   //滚动条滚动时，距离顶部的距离
		//   let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
		//   //可视区的高度
		//   let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
		//   //滚动条的总高度
		//   let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
		// 	console.log('scrollTop :>> ', scrollTop);
		// 	console.log('windowHeight 可视区的高度 :>> ', windowHeight);
		// 	console.log('scrollHeight 滚动条的总高度:>> ', scrollHeight);
		//   //滚动条到底部的条件
		//   if (scrollTop == 0) {
		//     this.scrollBottomState = false;
		//   } else {
		//     this.scrollBottomState = scrollTop + windowHeight == scrollHeight;
		//   }
		// },
		/** 开启组件 */
		show({column, row, index}, tableData, columns) {
			if (!tableData || !tableData.length || !columns || !columns.length) {
				$lj.alert("快捷录入读取错误");
				return false;
			}
			console.log('tableData :>> ', JSON.stringify(tableData));
			console.log('columns :>> ', JSON.stringify(columns));
			this._FnClearData();
			this.location = [{
					type: 'col',
					title: column.label
				},
				{
					type: 'row',
					title: row[this.propertyName]
				}
			];
			for (let i = index; i < tableData.length; i++) {
				let obj = {
					index: i,
					id: column.property,
					title: tableData[i][this.propertyName]
				};
				this.colCanEdit.push(obj);
			}
			let colCanIn = false;
			for (let j = 0; j < columns.length; j++) {
				if (columns[j].editable) {
					if (!colCanIn && columns[j].property == column.property) {
						colCanIn = true
					}
					if (colCanIn) {
						let obj = {
							index: index,
							id: columns[j].property,
							title: columns[j].label,
							type: columns[j].type || ''
						};
						this.rowCanEdit.push(obj);
					}
				}
			}
			if (this.actionState) {
				$lj.toast(`切换坐标`, 1000, 'top');
			} else {
				this.actionState = true;
			}
			this.$nextTick(() => {
				this._FnChangeDirection();
			})
		},
		_FnClearData() {
			this.canEditList = [];
			this.colCanEdit = [];
			this.rowCanEdit = [];
		},
		/** 输入中检测 */
		autoInputting(string) {
			this.quickInputList = this._FnString2Array(string);
			if (this.quickInputList[this.quickInputList.length - 1] == "") {
				this.quickInputList.splice(this.quickInputList.length - 1, 1)
			}
			if (this.quickInputList.length) {
				this.inputError = false;
			}
			console.log('this.quickInputList :>> ', JSON.stringify(this.quickInputList));
			this.handleClickInput();
			this._FnCountShowTagIndex();
		},
		/** 点击输入框，定位标签 */
		handleClickInput() {
			let index = this._FnCursorPosition('quick-input');
			let oString = this.quickInput.substring(0, index);
			let list = this._FnString2Array(oString);
			this.quickInputIndex = list.length - 1;
			console.log('this.quickInputIndex :>>', this.quickInputIndex);
		},
		/** 反向定位 */
		handleLocationTag(index) {
			this.quickInputIndex = index;
			let oInput = document.getElementById('quick-input');
			let string = this.quickInputList[index];
			let beforeString = '';
			if (index > 0) {
				for (let i = 0; i < index; i++) {
					beforeString += this.quickInputList[i] + ' ';
				}
			}
			oInput.focus();
			oInput.setSelectionRange(beforeString.length, beforeString.length + string.length);
		},
		/** 字符串转数组，使用'，','。',' '三个字符分割 */
		_FnString2Array(string) {
			let countInput = '';
			countInput = string.replace(/，/g, ' ');
			countInput = countInput.replace(/。/g, ' ');

			let list = countInput.split(' ');
			return list
		},
		/** 获取光标位置 */
		_FnCursorPosition(id) {
			let oInput = document.getElementById(id);
			let cursorPosition = -1;
			if (oInput && oInput.selectionStart) {
				//非IE浏览器
				cursorPosition = oInput.selectionStart;
				// } else {
				// 	//IE
				// 	var range = document.selection.createRange();
				// 	range.moveStart("character", -oInput.value.length);
				// 	cursorPosition = range.text.length;
			}
			console.log('cursorPosition :>> ', cursorPosition);
			return cursorPosition
		},
		close() {
			this.actionState = false;
		},
		/** 确认 */
		handleConfirm() {
			if (!this.quickInputList.length) {
				this.inputError = true;
				return false;
			}
			let arr = JSON.parse(JSON.stringify(this.canEditList));
			for (let i = 0; i < this.showTagListLength + 1; i++) {
				arr[i].value = this.quickInputList[i];
			}
			arr.length = this.showTagListLength + 1

			console.log('this.canEditList :>> ', JSON.stringify(arr));
			this.$emit('confirm', this.verticalOrNot, this.quickInputList, arr);
		},
		enterDone() {
			this.$refs.quickInput.blur();
			$lj.toast('录入成功', 1000, 'top');
		},
		/** 更改录入方向 */
		handleChangeDirection(item) {
			if (item.type == 'col' && !this.verticalOrNot) {
				this.verticalOrNot = true;
				this.autoSetStorage();
				this._FnChangeDirection();
			} else if (item.type == 'row' && this.verticalOrNot) {
				this.verticalOrNot = false;
				this.autoSetStorage();
				this._FnChangeDirection();
			}
		},
		/** 存储用户记录 */
		autoSetStorage() {
			if (this.tableName) {
				let storage = $lj.getStorage(this.draftName) || {};
				storage[this.tableName] = this.verticalOrNot
				$lj.setStorage(this.draftName, storage);
			}
		},
		_FnChangeDirection() {
			this.canEditList = this.verticalOrNot ? this.colCanEdit : this.rowCanEdit;

			this._FnCountShowTagIndex();
			this.$refs.quickInput.focus();
		},
		_FnCountShowTagIndex() {
			this.showTagListLength = this.quickInputList.length > this.canEditList.length ? this.canEditList.length -
				1 : this.quickInputList.length - 1
		}
	},
};
</script>

<style lang="less" scoped>
@import "../assets/css/lj-style-variable";

.quick-enter-wrapper {
	padding: 10px;
	padding-top: 14px;
	// border-radius: 16px;
	transition: all cubic-bezier(.8, 0, .2, 1) 0.4s;
	// box-shadow: 0px -4px 4px rgba(0, 0, 0, 0.1);
 	 box-shadow: 0px -4px 4px 0px rgba(0,0,0,0.04), 0px 0px 6px 0px rgba(0,0,0,0.12);

	&.in_top {
		box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.1);
	}

	.main-wrapper {
		position: relative;

		.close {
			position: absolute;
			top: -6px;
			left: 0;
			right: 0;
			margin: auto;
			width: 36px;
			display: flex;

			.line {
				width: 20px;
				height: 4px;
				border-radius: 2px;
				background-color: #4f4f4f;
				transition: all cubic-bezier(.8, 0, .2, 1) 0.4s;
			}

			.left {
				transform: rotate(-20deg) translateX(2px);
			}

			.right {
				transform: rotate(20deg) translateX(-2px);
			}

			&.opened {
				.left {
					transform: rotate(20deg) translateX(2px);
				}

				.right {
					transform: rotate(-20deg) translateX(-2px);
				}
			}
		}

		.location-inner {
			display: flex;
			width: 100%;

			.location-box {
				flex: 1;
				display: flex;
				align-items: center;

				.icon_location {
					flex-shrink: 0;
					color: @musePrimary;
					font-size: 16px;
					margin-right: 2px;
				}
			}

			.location {
				flex: 1;
				display: flex;

				.location-item {
					.item-box {
						position: relative;
						display: inline-block;
						box-sizing: border-box;
						margin-top: 2px;
						padding: 2px;
						padding-left: 18px;
						height: 18px;
						line-height: 14px;
						border-radius: 4px;
						color: @museTrack;
						font-size: @quaternaryTextFontSize;
						transition: all cubic-bezier(.8, 0, .2, 1) 0.2s;
					}

					.iconfont {
						position: absolute;
						top: 0;
						bottom: 0;
						left: 4px;
						margin: auto;
						width: @quaternaryTextFontSize;
						height: @quaternaryTextFontSize;
						font-size: @quaternaryTextFontSize;
					}

					span {
						align-self: center;

						display: -webkit-box;
						-webkit-line-clamp: 1;
						-webkit-box-orient: vertical;
						overflow: hidden;
					}

					&.active {
						.item-box {
							color: @musePrimary;
							background-color: @colorPassThr;
						}

						.iconfont {
							color: @musePrimary;
						}
					}

					&+.location-item {
						margin-left: 2px;
					}
				}
			}

			.control-box {
				margin-left: 5px;
				flex-shrink: 0;
			}

			.control {
				display: flex;
				background-color: #f2f2f2;
				border-radius: 12px;

				.control-item {
					box-sizing: border-box;
					display: inline-block;
					padding: 4px 8px;
					height: 24px;
					line-height: 16px;
					color: @museTrack;
					border-radius: 12px;
					font-size: @tertiaryTextFontSize;
					transition: all cubic-bezier(.8, 0, .2, 1) 0.2s;

					.iconfont {
						margin-right: 2px;
						font-size: @summaryIconFontSize;
					}

					span {
						align-self: center;
					}

					&.active {
						color: #ffffff;
						background-color: @musePrimary;

						.iconfont {
							color: #ffffff;
						}
					}
				}
			}
		}

		.input-box {
			.quick-input {
				font-size: @summaryIconFontSize;
				margin-top: 5px;
				margin-bottom: 5px;
			}

			.van-cell {
				padding-left: 5px;
				padding-right: 5px;

				&::after {
					content: none;
				}
			}

			.tag-box {
				margin-top: 2px;

				.van-tag {
					margin-right: 2px;
					border-radius: 4px;
				}
			}

			.van-tag {
				.tag-inner {
					text-align: center;
				}
			}
		}
	}
}
</style>