import lodash from 'lodash';
let idTmr;
const getExplorer = () => {
	let explorer = window.navigator.userAgent;
	//ie
	if (explorer.indexOf('MSIE') >= 0) {
		return 'ie';
	} else if (explorer.indexOf('Firefox') >= 0) {
		//firefox
		return 'Firefox';
	} else if (explorer.indexOf('Chrome') >= 0) {
		//Chrome
		return 'Chrome';
	} else if (explorer.indexOf('Opera') >= 0) {
		//Opera
		return 'Opera';
	} else if (explorer.indexOf('Safari') >= 0) {
		//Safari
		return 'Safari';
	}
};

const method = (ref, name) => {
	//整个表格拷贝到EXCEL中
	if (getExplorer() == 'ie') {
		let curTbl = ref;
		let oXL = new ActiveXObject('Excel.Application');

		//创建AX对象excel
		let oWB = oXL.Workbooks.Add();
		//获取workbook对象
		let xlsheet = oWB.Worksheets(1);
		//激活当前sheet
		let sel = document.body.createTextRange();
		sel.moveToElementText(curTbl);
		//把表格中的内容移到TextRange中
		sel.select;
		//全选TextRange中内容
		sel.execCommand('Copy');
		//复制TextRange中内容
		xlsheet.Paste();
		//粘贴到活动的EXCEL中
		oXL.Visible = true;
		//设置excel可见属性

		try {
			let fname = oXL.Application.GetSaveAsFilename('Excel.xls', 'Excel Spreadsheets (*.xls), *.xls');
		} catch (e) {
			print('Nested catch caught ' + e);
		} finally {
			oWB.SaveAs(fname);

			oWB.Close((savechanges = false));
			//xls.visible = false;
			oXL.Quit();
			oXL = null;
			// 结束excel进程，退出完成
			window.setInterval('Cleanup();', 1);
			idTmr = window.setInterval('Cleanup();', 1);
		}
	} else {
		tableToExcel(ref, name);
	}
};

const Cleanup = () => {
	window.clearInterval(idTmr);
};

const tableToExcel = (function () {
	// 编码要用utf-8不然默认gbk会出现中文乱码
	let uri = 'data:application/vnd.ms-excel;base64,',
		template =
			'<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
		base64 = function (s) {
			return window.btoa(unescape(encodeURIComponent(s)));
		},
		format = (s, c) => {
			return s.replace(/{(\w+)}/g, (m, p) => {
				return c[p];
			});
		};
	return (table, name) => {
		let ctx = {
			worksheet: name,
			table
		};

		//创建下载
		let link = document.createElement('a');
		link.setAttribute('href', uri + base64(format(template, ctx)));
		link.setAttribute('download', name);

		// window.location.href = uri + base64(format(template, ctx))
		link.click();
	};
})();

export default (datas, columns, flatColumns, context, dataname = 'Worksheet') => {
	// 建立节点
	let div = document.createElement('div');
	let title = document.createElement('h2');
	title.innerHTML = dataname;
	div.appendChild(title);
	let table = document.createElement('table');
	table.style.width = '100%';
	let thead = document.createElement('thead');
	let tbody = document.createElement('tbody');

	//  建立thead中的tr
	let thGroupTr = document.createElement('tr');
	thGroupTr.appendChild(document.createElement('th'))
	let thTr = document.createElement('tr');
	thTr.appendChild(document.createElement('th'));
	//  遍历写入th表头
	for (let column of columns) {
		if (column.children) {
			let th = document.createElement('th');
			th.innerText = column.headerName;
			th.colSpan = column.children.length
			thGroupTr.appendChild(th);
			for (let child of column.children) {
				let th = document.createElement('th');
				th.innerText = child.headerName;
				thTr.appendChild(th);
			}
		}
		else if (column.cellRendererParams && column.cellRendererParams.print) {
			let th = document.createElement('th');
			th.innerText = column.headerName;
			thTr.appendChild(th);
			thGroupTr.appendChild(document.createElement('th'));
			// td =
		}
	}
	for (let index in datas) {
		let data = datas[index];
		let clone = lodash.cloneDeep(data);
		let tr = document.createElement('tr');
		let indexTd = document.createElement('td');
		indexTd.innerText = Number(index) + 1;
		tr.appendChild(indexTd)
		for (let column of flatColumns) {
			if (column.cellRendererParams && column.cellRendererParams.print) {
				let td = document.createElement('td');
				if (column.valueFormatter) {
					clone[column.field] = column.valueFormatter({ value: clone[column.field], context: context, colDef: column });
				}
				if (column.type === 'boolean' && !clone._subTotal_row) {
					clone[column.field] = clone[column.field] === '1' ? '√' : 'X'
				}
				if (column.type === 'dict') {
					if (column.cellRendererParams && column.cellRendererParams.dict && typeof column.cellRendererParams.dict === 'object') {
						clone[column.field] = column.cellRendererParams.dict[clone[column.field]];
					} else if (!context.dicts || !context.dicts[ column.cellRendererParams.dict ]){
						console.warn(`字典翻译错误${context.dicts}，${column.cellRendererParams.dict}`);
					} else {
						clone[column.field] = context.dicts[ column.cellRendererParams.dict ][clone[column.field]]?context.dicts[column.cellRendererParams.dict][clone[column.field]]:clone[column.field];
					}
				}
				if (column.cellRendererParams && (column.cellRendererParams.asyncTranslate || column.cellRendererParams.asyncTranslateByPager)) {
					if ( !context.gridDicts[column.colId] ){
						console.warn(`异步翻译字典翻译错误${context.gridDicts[column.colId]}，${column.colId}`);
					}else{
						clone[column.field] = context.gridDicts[column.colId][clone[column.field]]?context.gridDicts[column.colId][clone[column.field]]:clone[column.field]
					}
				}

				td.innerText = clone[column.field] ? clone[column.field] : '';
				tr.appendChild(td);
			} else {

			}
		}
		tbody.appendChild(tr);
	}
	if (thGroupTr.children.length > 0) {
		thead.appendChild(thGroupTr);
	}
	thead.appendChild(thTr);
	table.appendChild(thead);
	table.appendChild(tbody);
	table.border = 1;
	table.style['border-collapse'] = 'collapse';
	div.appendChild(table);
	const createPdf = () => {
		let newWindow = window.open('_blank'); //打开新窗口
		let codestr = div.innerHTML; //获取需要生成pdf页面的div代码
		newWindow.document.write(codestr); //向文档写入HTML表达式或者JavaScript代码
		newWindow.document.close(); //关闭document的输出流, 显示选定的数据
		newWindow.print(); //打印当前窗口
		newWindow.close();
		return true;
	};
	createPdf();
	// if (state == 'print') {

	// } else if (state == 'excel') {
	// 	method(table.innerHTML, dataname);
	// }
};
