import type { App } from 'vue';

/**
 * 输入过滤指令
 * @directive v-input-filter，如 `<el-input v-model="phone" v-input-filter="'number'" />`
 * @param number - 纯数字
 * @param alphanumeric - 数字+字母
 * @param idcard - 数字+字母+括号（支持大陆、港澳台身份证）
 * @param tel - 固话格式（数字+横杠+括号+空格）
 */
export function inputFilterDirective(app: App) {
	app.directive('input-filter', {
		mounted(el, binding) {
			const input = el.querySelector('input') || el;
			const filterType = binding.value || 'number';
			
			const filters: { [key: string]: RegExp } = {
				number: /[^\d]/g,                 // 纯数字
				alphanumeric: /[^0-9A-Za-z]/g,    // 数字+字母
				idcard: /[^0-9A-Za-z()]/g,        // 数字+字母+括号（支持港澳台）
				tel: /[^\d\-() ]/g,               // 固话：数字+横杠+括号+空格
			};
			
			const handleInput = (e: Event) => {
				const target = e.target as HTMLInputElement;
				const regex = filters[filterType];
				if (regex && target.value) {
					const newValue = target.value.replace(regex, '');
					if (newValue !== target.value) {
						target.value = newValue;
						// 触发 input 事件，确保 v-model 更新
						target.dispatchEvent(new Event('input'));
					}
				}
			};
			
			input.addEventListener('input', handleInput);
			// 保存 handler，用于 unmounted 时清理
			(el as any)._inputFilterHandler = handleInput;
			(el as any)._inputFilterElement = input;
		},
		unmounted(el) {
			const handler = (el as any)._inputFilterHandler;
			const input = (el as any)._inputFilterElement;
			if (handler && input) {
				input.removeEventListener('input', handler);
			}
		},
	});
}

/**
 * 按钮波浪指令
 * @directive 默认方式：v-waves，如 `<div v-waves></div>`
 * @directive 参数方式：v-waves=" |light|red|orange|purple|green|teal"，如 `<div v-waves="'light'"></div>`
 */
export function wavesDirective(app: App) {
	app.directive('waves', {
		mounted(el, binding) {
			el.classList.add('waves-effect');
			binding.value && el.classList.add(`waves-${binding.value}`);
			function setConvertStyle(obj: { [key: string]: unknown }) {
				let style: string = '';
				for (let i in obj) {
					if (obj.hasOwnProperty(i)) style += `${i}:${obj[i]};`;
				}
				return style;
			}
			function onCurrentClick(e: { [key: string]: unknown }) {
				let elDiv = document.createElement('div');
				elDiv.classList.add('waves-ripple');
				el.appendChild(elDiv);
				let styles = {
					left: `${e.layerX}px`,
					top: `${e.layerY}px`,
					opacity: 1,
					transform: `scale(${(el.clientWidth / 100) * 10})`,
					'transition-duration': `750ms`,
					'transition-timing-function': `cubic-bezier(0.250, 0.460, 0.450, 0.940)`,
				};
				elDiv.setAttribute('style', setConvertStyle(styles));
				setTimeout(() => {
					elDiv.setAttribute(
						'style',
						setConvertStyle({
							opacity: 0,
							transform: styles.transform,
							left: styles.left,
							top: styles.top,
						})
					);
					setTimeout(() => {
						elDiv && el.removeChild(elDiv);
					}, 750);
				}, 450);
			}
			el.addEventListener('mousedown', onCurrentClick, false);
		},
		unmounted(el) {
			el.addEventListener('mousedown', () => {});
		},
	});
}
