import type { App } from 'vue';
import { getImageUrl } from '@/utils/tools';

/**
 * 按钮波浪指令
 * @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.removeEventListener('mousedown', () => {});
		},
	});
}
export function lazyImgDirective(app: App) {
	// 图片懒加载指令
	app.directive('lazy', {
		mounted(el: any, binding: any) {
			// vue2.0 inserted vue3.0 mounted
			const observer = new IntersectionObserver(
				([{ isIntersecting }]) => {
					if (isIntersecting) {
						// isIntersecting判断是否进入视图
						observer.unobserve(el); // 进入视图后，停止监听
						el.onerror = () => {
							// 加载失败显示默认图片
							el.src = getImageUrl('public/fail.png');
						};
						el.src = binding.value; // 进入视图后，把指令绑定的值赋值给src属性，显示图片
					}
				},
				{
					threshold: 0.01, // 当图片img元素占比视图0.01时 el.src = binding.value
				}
			);
			observer.observe(el); //观察指令绑定的dom
		},
	});
}
// 输入框去除两边空格
export function inputTrimDirective(app: App) {
	// 图片懒加载指令
	app.directive('trim', {
		mounted(el: any) {
			function getInput(el: any) {
				let inputEle: any;
				const { tagName } = el;
				if (tagName === 'INPUT' || tagName === 'TEXTAREA') {
					inputEle = el;
				} else {
					inputEle = el.querySelector('input');
					if (!inputEle) {
						inputEle = el.querySelector('textarea');
					}
				}
				return inputEle;
			}
			function dispatchEvent(el: any, type: any) {
				let evt = new Event(type, {
					bubbles: true,
					cancelable: true,
					composed: true,
				});
				el.dispatchEvent(evt); //手动触发input时间
			}
			if (!el) return;
			let inputEle = getInput(el);
			const handler = function (event: any) {
				const newVal = event.target.value.trim();
				if (event.target.value != newVal) {
					event.target.value = newVal;
					dispatchEvent(inputEle, 'input');
				}
			};
			el.inputEle = inputEle;
			el._blurHandler = handler;
			inputEle?.addEventListener('blur', handler);
		},
		beforeUnmount(el: any) {
			const { inputEle } = el;
			inputEle?.removeEventListener('blur', el._blurHandler);
		},
	});
}
