import React from 'react';
import { httpConfig } from 'containers/config/httpConfig';
import { Modal, Spin, message } from 'antd';
import fetchJsonp from 'fetch-jsonp';
//"dataResult":{    //此数据为打印数据dataResult必需为{} 不能是[]  data1,data2 可以随意命名但必需为[] 不能为{}
//    "data1":[{"name":"sdsds","name2":"1232322"},{"name":"sdsds","name2":"1232322"}],
//   "data2":[{"name5":"sdsds","name6":"1232322"},{"name5":"sdsds","name6":"1232322"}],  
//}
//"dataParams":{    //当数据量大不能在前端传入 此参数是直接调用后端取 dataResult         
//   "params": [{
//      "userID":"292",
//      "userCode":"1020",
//      "currentLocFlag":"Y",
//      "language":"CN"}],
//    "code":"01040043"
// }
/*
templateName:打印模板代码
hospID:医院ID
dataResult:打印的数据
let dataResult = {    //此数据为打印数据dataResult必需为{} 不能是[]  data1,data2 可以随意命名但必需为[] 不能为{}
				"data1": [{ "name": "sdsds1", "name2": "12323221" }, { "name": "sdsds1", "name2": "12323221" }],
				"data2": [{ "name5": "sdsds2", "name6": "12323222" }, { "name5": "sdsds2", "name6": "12323222" }],
			}
dataParams:后台取数据入参  当dataResult为空时   数据量比较大时可以使用
designFlag：Y:弹出编辑界面 N：不弹编辑界面
detailRowID：模板ID
logFlag:参数是否打印日志 C:\ProgramData\prykNT\prBrowser\bin\service\plugins\FastReport\Log\
*/
export async function $fastReportTemplate(templateName, hospID, dataResult, dataParams, designFlag = "N", detailRowID = "", logFlag = "N", pdfName = "",printPreview = "") {

	if (designFlag === "N") {
		let data = {
			params: [{
			}]
		}

		let res = await React.$asyncPost(this, '01040308', data);
		if (res.errorCode == '0') {
			if (res.designFlag == "Y") {
				/////多次打印，如果是进入编辑器会存在后面弹框覆盖前面，如果不是进行编辑器权限不会影响打印
				Modal.confirm({
					title: '报表编辑',
					content: '报表编辑，是否进入报表编辑器',
					okText: '是',
					cancelText: '否',
					onOk: () => {
						FastReportreturn(templateName, hospID, dataResult, dataParams, "Y", detailRowID, logFlag, pdfName,printPreview);
					},
					onCancel: () => {
						FastReportreturn(templateName, hospID, dataResult, dataParams, "N", detailRowID, logFlag, pdfName,printPreview);
					},
				});
			} else {
				return FastReportreturn(templateName, hospID, dataResult, dataParams, designFlag, detailRowID, logFlag, pdfName,printPreview);
			}
		} else {
			return FastReportreturn(templateName, hospID, dataResult, dataParams, designFlag, detailRowID, logFlag, pdfName,printPreview);
		}
	} else {
		return FastReportreturn(templateName, hospID, dataResult, dataParams, designFlag, detailRowID, logFlag, pdfName,printPreview);
	}

}
const FastReportreturn = async (templateName, hospID, dataResult, dataParams, designFlag, detailRowID, logFlag, pdfName,printPreview) => {
	let openYBModal = Modal.info({
		title: '正在打印,请稍等...',
		content: <Spin size="large" />,
		okText: "",
		onOk() { },
	});
	let { userData } = window.sessionStorage;
	let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : "");
	// 判断是否是本地，如果是本地的话取https配置地址，线上则取地址栏地址 （内外网）
	let httpIp = windowHost && (windowHost.indexOf("localhost") !== -1 || windowHost.indexOf("127.0.0.1") !== -1) ? httpConfig.ipDeault : windowHost;
	return Promise.resolve()
		.then((oldRes) => {
			return new Promise(async (resolve, rejeck) => {
				let data = {
					params: [
						{
							"designFlag": designFlag,
							"logFlag": logFlag,
							"dataResult": dataResult,
							"dataParams": dataParams,
							"pdfName": pdfName,
							"printPreview": printPreview,
							"reportparams": {
								"params": [{
									fastReportCode: templateName,
									hospID: hospID,
									templateID: detailRowID,
								}],
								"code": "01040306"
							},
							"dataURL": {
								"dataIP": (httpIp),
								"urlAddress": (httpConfig.urlAddress),
								"authorization": (httpConfig.authorizationToken)
							}
						}
					],
					session: [(JSON.parse(userData))]
				}
				let paramsJSON = "{'inputDir':'" + "FastReport/FastReportFrom.dll" + "','clsName':'" + "FastReportFrom.FastReportDll" + "','funcName':'" + "FastReport" + "','dllInput':'" + JSON.stringify(data) + "'}";
				if (typeof (CefSharp) != 'undefined') { // 定制浏览器
					CefSharp.BindObjectAsync('xysCefToJavaScripts');
					return new Promise((resolve, reject) => {
						if (xysCefToJavaScripts && 'fastReport' in xysCefToJavaScripts && xysCefToJavaScripts.fastReport) {
							paramsJSON =  JSON.stringify(data) ;
							xysCefToJavaScripts.fastReport(paramsJSON).then((returnVale) => {
								let res = JSON.parse(returnVale);
								if (res.errorCode == '0') {
								} else {
									message.error(res.errorMessage)
								}
								resolve(returnVale)
								openYBModal.destroy(); // 弹框等待提示
							})
						} else {
							xysCefToJavaScripts.driveLocalHardware(paramsJSON).then((returnVale) => {
								let res = JSON.parse(returnVale);
								if (res.errorCode == '0') {
								} else {
									message.error(res.errorMessage)
								}
								resolve(returnVale)
								openYBModal.destroy(); // 弹框等待提示
							})
						}
					})
				} else {
					const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 使用暴露的c#的对象
					return new Promise((resolve, reject) => {
						if (frame) {
							// 获取的属性是proxy promise;
							frame.DynamicLoadingDLL(paramsJSON)
								.then(
									res => {
										let result = JSON.parse(res);
										if (result.errorCode == '0') {
										} else {
											message.error(result?.errorMessage || '新版浏览器调用异常，请稍后再试！');
										}
										resolve(res);
										openYBModal.destroy(); // 弹框等待提示
									},
									err => {
										console.log(err);
										message.error('动态库调用异常，请稍后再试！');
										reject(err);
										openYBModal.destroy(); // 弹框等待提示
									}
								)
						} else {
							fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + paramsJSON, {
								jsonpCallback: 'JsonCallback',
								timeout: 500000,
							}).then(function (response) {
								return response.json()
							}).then(function (json) {
								resolve(JSON.parse(json));
								openYBModal.destroy(); // 弹框等待提示
							}).catch(function (err) {
								reject(err);
								message.error('动态库调用异常，请稍后再试！');
								openYBModal.destroy(); // 弹框等待提示
							})
						}
					})
				}
			})
		})
}