import { parse } from 'querystring';
import moment from 'moment';
import numeral from 'numeral';
import ExportJsonExcel from 'js-export-excel';
import type { RangePickerDateProps } from 'antd/es/date-picker/generatePicker';
import type { ProColumns } from '@ant-design/pro-table';

type RangePickerValue = RangePickerDateProps<moment.Moment>['value']

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
	if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
		return true;
	}
	return window.location.hostname === 'preview.pro.ant.design';
};

// For the official demo site, it is used to turn off features that are not needed in the real development environment
export const isAntDesignProOrDev = (): boolean => {
	const { NODE_ENV } = process.env;
	if (NODE_ENV === 'development') {
		return true;
	}
	return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

export function getTimeDistance(type: 'today' | 'week' | 'month' | 'year'): RangePickerValue {
	const now = new Date();
	const oneDay = 1000 * 60 * 60 * 24;

	if (type === 'today') {
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);
		return [moment(now), moment(now.getTime() + (oneDay - 1000))];
	}

	if (type === 'week') {
		let day = now.getDay();
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);

		if (day === 0) {
			day = 6;
		} else {
			day -= 1;
		}

		const beginTime = now.getTime() - day * oneDay;

		return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
	}
	const year = now.getFullYear();

	if (type === 'month') {
		const month = now.getMonth();
		const nextDate = moment(now).add(1, 'months');
		const nextYear = nextDate.year();
		const nextMonth = nextDate.month();

		return [
			moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
			moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
		];
	}

	return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
}

export function fixedZero(val: number) {
	return val * 1 < 10 ? `0${val}` : val;
}

// 拆分小数点前后数字
export const splitAmount = (value: any, fixedType?: string) => {
	const formatType = fixedType || '0,0'
	const stringValue = numeral(value).format(formatType)

	const [intValue, floatValue] = stringValue.split(".")
	return [intValue, floatValue]
}

// 报表导出excel
export const exportExcel = async (
	outColumn: ProColumns<any>[],
	reqDetailList: any[],
	fileName?: string,
) => {
	// 网络请求命名空间
	// const outColumn: ProColumns<any>[] = columns.slice(3); // 需要放在state里边,Table，Columns
	const option: { fileName: string; datas: any[] } = {
		fileName: fileName || '新建文件', // : '收营员报表' + moment().format('YYYYMMDDHHmmss'),
		datas: [],
	};
	if (reqDetailList?.length) {
		const getList = (data = [], index: number) => {
			const wrapData: any = data.map((item: any) => {
				const node = { ...item };
				if (item.children && item.children.length > 0) {
					const childNode = getList(item.children, index)
					return [node, ...childNode.data]
				}
				return node
			});
			return { data: wrapData, index: index + 1 };
		}

		const data = getList(reqDetailList as [], 0)
		const outList = data.data.flat(data.index + 1)
		option.datas = [
			{
				sheetData: outList.map((item: any, index: number) => {
					const result = {};

					outColumn.forEach((c: any, i) => {
						if (c.hideInTable) return;
						if (c.dataIndex === 'index') {
							result[c.dataIndex] = index + 1;
						} else if (c.render) {
							result[c.dataIndex] = typeof c.render(item[c.dataIndex], item) === 'object' ?
								item[c.dataIndex] : c.render(item[c.dataIndex], item)
						} else {
							result[c.dataIndex] = item[c.dataIndex] || ''
						}
					});
					// if(item.children) {
					// 	const childrenColums =  item.children.map((child, index) => {
					// 		const res = {};
					// 		outColumn.forEach((c: any, i) => {
					// 			if (c.hideInTable) return;
					// 			if (i !== 0) {
					// 				res[c.dataIndex] = c.render ? c.render(child[c.dataIndex],item) : child[c.dataIndex]  ;
					// 			} else {
					// 				res[c.dataIndex] = index + 1;
					// 			}
					// 		});
					// 		return res
					// 	})
					// 	console.log(childrenColums)
					// 	// return {childrenColums}

					// }
					return result;
				}),
				sheetName: 'sheet1', // Excel文件名称
				sheetFilter: outColumn.map((item) => item.dataIndex),
				sheetHeader: outColumn.map((item) => item.title),
				columnWidths: outColumn.map(() => 10),
			},
		];

		// function warpNode(data) {
		// 	data.map((item, index) => {
		// 		const result = {};
		// 		if(item.children) {
		// 		}
		// 		outColumn.forEach((c: any, i) => {
		// 			if (c.hideInTable) return;
		// 			if (i !== 0) {
		// 				result[c.dataIndex] = item[c.dataIndex];
		// 			} else {
		// 				result[c.dataIndex] = index + 1;
		// 			}
		// 		});
		// 		return result;
		// 	})
		// 	}
		// }
		const toExcel = new ExportJsonExcel(option);
		toExcel.saveExcel();
		return { message: 'ok' };
	}
	return { message: '没有可导出的数据' };
};

// 打印页面配置内容
export const printOutBody = (ele: any, content: string) => {

	const dateEle = document.createElement('div');
	const printConent = document.createElement('div');
	if (typeof ele === 'object' && ele.length > 1) {
		ele.forEach(n => printConent.appendChild(n))
	} else {
		const title = ele?.getElementsByClassName('ant-table-wrapper')[0];
		printConent.appendChild(ele)
		if (title) {
			dateEle.setAttribute('style', 'text-align:right;font-size:20px;margin-bottom: 20px;');
			dateEle.innerHTML = content;
			ele.insertBefore(dateEle, title);
		}
	}

	// dateEle.setAttribute('style', 'text-align:right;font-size:20px;margin-bottom: 20px;');
	// dateEle.innerHTML = content;

	return printConent;
};

// 获取临时查看图片的base4码
export const getBase64 = async (file: any): Promise<any> => {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result);
		reader.onerror = error => reject(error);
	});
}

export const EventBus = {
	eventList: {},
	on(name: string, callback: Function) {
		this.eventList[name] = callback;
	},
	emit(name: string, arg: any[] | any) {
		if (this.eventList[name]) {
			// if (Array.isArray(arg)) {
			//   this.eventList[name](...arg);
			// } else {
			//   this.eventList[name](arg);
			// }
			this.eventList[name](arg);
		}
	},
};

export const getGuid = (): string => {
	return Array.from(
		{ length: 8 },
		(_, i) =>
			(((1 + Math.random()) * 0x10000) || 0).toString(16).substring(1) +
			([1, 2, 3, 4].includes(i) ? '-' : '')
	).join('')
}
