<template>
	<textarea
		type="text"
		:maxlength="maxlength"
		@keydown.stop="limitEnter($event)"
		@keyup.stop="limitValue"
		:rows="rows"
		:style="style"
		@focus.stop="focusInput"
		@blur.stop="blurInput"
		:placeholder="placeholder"
		v-model="textAreaVal"
	/>
</template>

<script>
	import * as ObjUtil from "../../../util/pattern/object";
	import MapUtil from "../../../util/pattern/map";
	export default {
		name: "updateInput",

		data() {
			return {
				textAreaVal: "",
				style: {}
			};
		},
		props: {
			rows: {
				type: Number
			},
			type: {
				type: String,
				default: "text"
			},
			maxlength: {
				type: String,
				default: ""
			},
			value: {
				type: [String, Number]
			},
			initStyle: {
				type: Object,
				default() {
					return {};
				}
			},
			placeholder: {
				type: String
			}
		},
		mounted() {
			let style = ObjUtil.copy(this.initStyle || {});
			MapUtil.setDftValue(style, {
				"text-align": "center",
				"box-sizing": "content-box",
				padding: "10px 20px",
				border: "1px solid rgba(255, 255, 255, 0.5)",
				height: this.initStyle["font-size"] || "auto",
				"line-height":
					this.initStyle["font-size"] || this.initStyle.height || "auto"
			});
			if (this.rows == 1) {
				style["overflow"] = "hidden";
			}
			this.style = style;
		},
		model: {
			prop: "value",
			event: "change"
		},
		watch: {
			initStyle: {
				immediate: true,
				handler(newV) {
					this.style = newV;
				},
				deep: true
			},
			value: {
				immediate: true,
				handler(newV, oldV) {
					if (!newV || newV == oldV || newV == this.textAreaVal) return;
					this.textAreaVal = newV;
				}
			},
			textAreaVal: {
				immediate: true,
				handler(newV, oldV) {
					if (newV == oldV) return;
					this.$emit("change", newV);
				}
			}
		},
		methods: {
			limitValue() {
				if (this.type == "number") {
					//有报错待优化
					this.value = this.value.replace(/[^\d]/g, "");
				}
			},
			limitEnter(event) {
				if (this.rows == 1 && event.keyCode === 13) {
					event.preventDefault(); // 阻止浏览器默认换行操作
					return false;
				}
			},
			focusInput() {
				let vm = this;
				let newcss = {
					border: "1px solid #cccccc"
				};
				Object.assign(this.style, newcss);
				vm.$emit("focusInput");
			},
			blurInput() {
				let vm = this;
				let newcss = {
					border: "1px solid rgba(255, 255, 255, 0.5)"
				};
				Object.assign(this.style, newcss);
				vm.$emit("blurInput");
			}
		}
	};
</script>

<style scoped>
	textarea::-webkit-scrollbar {
		/*隐藏滚轮*/
		width: 0;
	}
</style>
