<template>
	<view class="yi-code">
		<view class="yi-code-show">
			<block v-for="i in numberArr">
				<view :class="'yi-code-show-item' + ((codes.length === i && isFocus) ? ' yi-code-show-active' : '')"
					:style="type !== 'block' ? (type === 'line' ? 'border-top: 0; border-left: 0; border-right: 0; border-radius: 0; border-width: 2px;' : 'border-style: dashed;') : ''">
					{{ showVal(codes[i]) }}
				</view>
			</block>
		</view>
		<view class="yi-code-hide" :style="'width: ' + (width * 2) + 'rpx;left: -' + width + 'rpx;'">
			<input ref="codeInput" v-model="value" :style="'width: ' + (width * 2) + 'rpx;'" :focus="focus"
				@focus="onFocus" @blur="onBlur" :type="inputType" @input="onChange" :maxlength="maxlength" />
		</view>
	</view>
</template>

<script>
export default {
	props: {
		/**
		 * @description 宽度 rpx
		 */
		width: {
			type: Number,
			default: 500,
		},
		/**
		 * @description 是否自动聚焦
		 */
		focus: {
			type: Boolean,
			default: true,
		},
		/**
		 * @description 隐藏字符（密码效果）
		 */
		hide: {
			type: String,
			default: '',
		},
		/**
		 * @description 验证码长度
		 */
		maxlength: {
			type: Number,
			default: 6
		},
		/**
		 * @description 样式类型 block 方框, dashed 虚线方框，line 线
		 */
		type: {
			type: String,
			default: 'block'
		},
		/**
		 * @description text | number 
		 */
		inputType: {
			type: String,
			default: 'number'
		},
	},
	created() {
		let arr = [];
		for (let i = 0; i < this.$props.maxlength; i++) {
			arr.push(i);
		}
		this.numberArr = arr;
	},
	data() {
		return {
			numberArr: [], // 
			codes: [],
			value: '',
			isFocus: false
		}
	},
	mounted() {
		// 组件挂载后自动聚焦
		if (this.$props.focus) {
			this.tryFocus();
		}
	},
	methods: {
		tryFocus(retryCount = 0) {
			this.$nextTick(() => {
				setTimeout(() => {
					console.log('尝试聚焦，重试次数:', retryCount, 'ref:', this.$refs.codeInput);
					// 方法1：尝试使用 ref 获取元素
					if (this.$refs.codeInput) {
						const inputEl = this.$refs.codeInput;
						if (inputEl.focus) {
							inputEl.focus();
							console.log('验证码输入框聚焦成功（ref方式）');
							return;
						}
						// 小程序中可能需要访问 $el
						if (inputEl.$el && inputEl.$el.focus) {
							inputEl.$el.focus();
							console.log('验证码输入框聚焦成功（ref.$el方式）');
							return;
						}
					}
					// 方法2：尝试使用 uni.createSelectorQuery
					uni.createSelectorQuery()
						.in(this.$el)  // 限定搜索范围
						.select('.yi-code-hide input')
						.node()
						.exec((res) => {
							console.log('SelectorQuery result:', res);
							if (res[0] && res[0].node) {
								res[0].node.focus();
								console.log('验证码输入框聚焦成功（SelectorQuery方式）');
							} else if (retryCount < 5) {
								this.tryFocus(retryCount + 1);
							}
						});
				}, 200 + retryCount * 150);
			});
		},
		clear() {
			this.codes = []
			this.value = ''
		},
		onFocus() {
			this.isFocus = true
		},
		onBlur() {
			this.isFocus = false
		},
		showVal(v) {
			return v ? (this.hide || v) : '';
		},
		onChange(e) {
			// 兼容不同平台的事件对象
			let str = '';
			if (e && e.detail && e.detail.value !== undefined) {
				str = e.detail.value;
			} else if (e && e.target && e.target.value !== undefined) {
				str = e.target.value;
			} else if (typeof e === 'string') {
				str = e;
			}
			if (str) {
				// 截断超过 maxlength 的部分
				const maxLen = this.$props.maxlength;
				str = String(str).slice(0, maxLen);
				this.value = str;
				this.codes = str.split('');
				this.$emit('onChange', str);
				if (this.codes.length === maxLen) {
					this.$emit('onComplete', str);
				}
			} else {
				this.codes = [];
				this.$emit('onChange', '');
			}
		}
	}
}
</script>

<style lang="scss">
.yi-code {
	position: relative;
	overflow: hidden;
	text-align: unset;
	width: 100%;

	.yi-code-show {
		display: flex;
		justify-content: space-between;
		align-items: center;
		

		.yi-code-show-item {
			box-sizing: border-box;
			width: 96rpx;
			height: 96rpx;
			background: #F7F8FA;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.yi-code-show-active {
			width: 96rpx;
			height: 96rpx;
			background: #F7F8FA;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			border: 1rpx solid #19D29B;

			// border-color: #ff5500;
			// border-width: 2px;
			//animation: myfirst 600ms infinite;

			@keyframes myfirst {
				0% {
					opacity: 0.1
				}

				100% {
					opacity: 1
				}
			}
		}
	}

	.yi-code-hide {
		position: absolute;
		z-index: 99;
		left: 0;
		top: 0;
		height: 96rpx;
		opacity: 0;
		text-align: unset;

		input {
			height: 96rpx;
			text-align: unset;
		}
	}
}
</style>