import { nextTick } from 'vue';
import * as svg from '@element-plus/icons-vue';

// 获取阿里字体图标
const getAlicdnIconfont = () => {
	return new Promise((resolve, reject) => {
		nextTick(() => {
			const styles: any = document.styleSheets;
			let sheetsList = [] as any[];
			let sheetsIconList = [] as any[];
			for (let i = 0; i < styles.length; i++) {
				if (styles[i].href && styles[i].href.indexOf('at.alicdn.com') > -1) {
					sheetsList.push(styles[i]);
				}
			}
			for (let i = 0; i < sheetsList.length; i++) {
				for (let j = 0; j < sheetsList[i].cssRules.length; j++) {
					if (sheetsList[i].cssRules[j].selectorText && sheetsList[i].cssRules[j].selectorText.indexOf('.icon-') > -1) {
						sheetsIconList.push(
							`${sheetsList[i].cssRules[j].selectorText.substring(1, sheetsList[i].cssRules[j].selectorText.length).replace(/\:\:before/gi, '')}`
						);
					}
				}
			}
			if (sheetsIconList.length > 0) resolve(sheetsIconList);
			else reject('未获取到值，请刷新重试');
		});
	});
};

// 初始化获取 css 样式，获取 element plus 自带 svg 图标，增加了 ele- 前缀，使用时：ele-Aim
const getElementPlusIconfont = () => {
	return new Promise((resolve, reject) => {
		nextTick(() => {
			const icons = svg as any;
			const sheetsIconList = [] as any[];
			for (const i in icons) {
				sheetsIconList.push(`ele-${icons[i].name}`);
			}
			if (sheetsIconList.length > 0) resolve(sheetsIconList);
			else reject('未获取到值，请刷新重试');
		});
	});
};

// 初始化获取 css 样式，这里使用 fontawesome 的图标
const getAwesomeIconfont = () => {
	return new Promise((resolve, reject) => {
		nextTick(() => {
			const styles: any = document.styleSheets;
			let sheetsList = [] as any[];
			let sheetsIconList = [] as any[];
			for (let i = 0; i < styles.length; i++) {
				// 支持检测 fontawesome 和 fortawesome
				if (styles[i].href && (styles[i].href.indexOf('fontawesome') > -1 || styles[i].href.indexOf('fortawesome') > -1)) {
					sheetsList.push(styles[i]);
				}
			}
			for (let i = 0; i < sheetsList.length; i++) {
				try {
					for (let j = 0; j < sheetsList[i].cssRules.length; j++) {
						const rule = sheetsList[i].cssRules[j];
						if (rule.selectorText) {
							// 支持 Font Awesome 7.x 新格式：.fa-solid, .fa-regular, .fa-brands, .fa-xxx
							// 也支持旧格式：.fa-xxx
							if (
								(rule.selectorText.indexOf('.fa-solid') === 0 ||
								 rule.selectorText.indexOf('.fa-regular') === 0 ||
								 rule.selectorText.indexOf('.fa-brands') === 0 ||
								 rule.selectorText.indexOf('.fa-') === 0) &&
								rule.selectorText.indexOf(',') === -1
							) {
								if (/::before/.test(rule.selectorText)) {
									const iconClass = rule.selectorText
										.substring(1, rule.selectorText.length)
										.replace(/\:\:before/gi, '');
									// 如果是新格式（fa-solid fa-xxx），只取图标名部分
									const iconName = iconClass.replace(/^(fa-solid|fa-regular|fa-brands)\s+/, '');
									if (iconName && !sheetsIconList.includes(iconName)) {
										sheetsIconList.push(iconName);
									}
								}
							}
						}
					}
				} catch (e) {
					// 跨域样式表可能无法访问，忽略错误
					continue;
				}
			}
			if (sheetsIconList.length > 0) resolve(sheetsIconList.reverse());
			else reject('未获取到值，请刷新重试');
		});
	});
};

/*
 * 获取本地自带的图标
 * /src/assets/icons文件夹内的svg文件
 */
const getLocalIconfontNames = () => {
	return new Promise<string[]>((resolve, reject) => {
		nextTick(() => {
			let iconfonts: string[] = [];

			const svgEl = document.getElementById('local-icon');
			if (svgEl?.dataset.iconName) {
				iconfonts = (svgEl?.dataset.iconName as string).split(',');
			}

			if (iconfonts.length > 0) {
				resolve(iconfonts);
			} else {
				reject('No Local Icons');
			}
		});
	});
};

/**
 * 获取字体图标 `document.styleSheets`
 * @method ali 获取阿里字体图标 `<i class="iconfont 图标类名"></i>`
 * @method ele 获取 element plus 自带图标 `<i class="图标类名"></i>`
 * @method ali 获取 fontawesome 的图标 `<i class="fa 图标类名"></i>`
 */
const initIconfont = {
	// iconfont
	ali: () => {
		return getAlicdnIconfont();
	},
	// element plus
	ele: () => {
		return getElementPlusIconfont();
	},
	// fontawesome
	awe: () => {
		return getAwesomeIconfont();
	},
	local: () => {
		return getLocalIconfontNames();
	},
};

// 导出方法
export default initIconfont;
