<template>
	<u-input
		:key="inpType"
		v-bind="__attrs"
		v-on="__listeners"
		ref="uInput"
	>
		<!--		<template :slot="name" v-for="(_, name) in $scopedSlots">
      <slot :name="name"></slot>
    </template>-->

		<template slot="prefix">
			<slot name="prefix"></slot>
		</template>

		<template slot="suffix">
			<slot name="suffix"></slot>
		</template>

		<template v-if="showPassword" slot="suffix">
			<u-icon
				v-show="inpType === 'password'"
				@click="toggleType('text')"
				name="eye-off"
				size="20"
			></u-icon>
			<u-icon
				v-show="inpType === 'text'"
				@click="toggleType('password')"
				name="eye-fill"
				size="20"
			></u-icon>
		</template>
	</u-input>
</template>
<script>
import uProps from 'uview-ui/components/u-input/props';

const customProps = {
	// 自定义props
	showPassword: Boolean, // 是否显示切换密码图标
};

export default {
	name: 'cInput',
	model: {
		prop: 'value',
		event: 'input',
	},
	props: {
		...uProps.props,
		...customProps,
	},
	data() {
		return {
			inpType: this.$props.type,
		};
	},
	watch: {
		type: {
			handler(val) {
				this.inpType = val;
			},
			immediate: true,
		},
	},
	computed: {
		__attrs() {
			return {
				...this.$props,
				...this.$attrs,
				type: this.inpType,
				placeholder: this.$props.placeholder || '请输入',
			};
		},
		__listeners() {
			return {
				...this.$listeners,
				input: this.onInput,
				blur: this.onBlur,
			};
		},
	},
	methods: {
		//去掉汉字
		removeChinese(strValue) {
			if (strValue) {
				const reg = /[\u4e00-\u9fa5]/g;
				return strValue.replace(reg, '');
			}
			return '';
		},
		onInput(val) {
			const reg = /[\u4E00-\u9FA5]+/;
			if (this.showPassword && reg.test(val)) {
				const newVal = this.removeChinese(val);
				this.$refs.uInput.innerValue = newVal;
				return;
			}
			this.$emit('input', val);
		},

		toggleType(type) {
			this.inpType = type;
		},
		onBlur(val = '') {
			const modelValue = val.trim();
			this.$emit('input', modelValue);
			this.$emit('blur', modelValue);
		},
	},
};
</script>
