import React, { Component, Fragment } from 'react';
import { queryConfig } from '../services';
import { getInfo } from '@/highOrderComponent/Service';
import { message } from 'antd';
import Shell from '@/baseComponent/Shell';
import ButtonDiy from '@/baseComponent/ButtonDiy';
import router from 'umi/router';
import DetailDom from './DetailDom';
import { A4Width, A4Height, getCLodopFuncJS, templateCode, defaultConfigInfo } from './config';
import RenderAuthorized from '@/components/Authorized';
import { getAuthority } from '@/utils/authority';
import { ModalInfo } from '@/baseComponent/Modal';
import { isJSON } from '@/webPublic/one_stop_public/copy';

const Authorized = RenderAuthorized(getAuthority());

export default class ViewPrint extends Component {
	constructor(props) {
		super(props);
		this.state = {
			configAll: null,
			viewData: null,
			loading: true,
			printIndex: 0,
			showWindowPrint: false,
			preaparePrint: false,
		};
		this.getConfigInfo = queryConfig.bind(this);
	}

	getViewData = () => {
		const { selectedRows, dataQueryCallBack } = this.props;
		const ids = selectedRows.map((x) => x.id);
		this.getConfigInfo().then((x) => {
			if (x && x.queryUrl) {
				getInfo(
					{
						ids: ids.join(','),
					},
					x.queryUrl,
				).then((viewData) => {
					if (!viewData || !viewData.length) {
						message.warning('未查询到可打印的数据');
						console.error(`${x.queryUrl}接口报错或者没有返回数据`);
						return false;
					}
					if (dataQueryCallBack && typeof dataQueryCallBack === 'function') {
						viewData = dataQueryCallBack(viewData);
					}
					for (const item of viewData) {
						for (let z in item) {
							if (item[z] === null || item[z] === 'null') {
								item[z] = '';
							}
						}
					}
					this.setState({
						viewData,
					});
				});
			}
		});
	};

	componentDidMount() {
		this.getViewData();
		getCLodopFuncJS().then((response) => {
			window.On_CLodop_Opened = function() {
				console.log('打印插件准备就绪,随时可以打印');
				window.On_CLodop_Opened = null;
			};
			if (response) {
				this.setState({
					loading: false,
				});
			}
		});
	}

	detailDom = (data) => {
		const {
			configAll: { config },
		} = this.state;
		const res = [];
		for (const item of config) {
			res.push(
				DetailDom({
					config: item,
					data: data[item.fieldCode],
				}),
			);
		}
		return res;
	};

	printOne = (optionType = 0) => {
		const { printIndex, configAll, viewData } = this.state;
		let { info } = configAll;
		if (isJSON(info)) {
			info = JSON.parse(info);
		} else {
			info = defaultConfigInfo;
		}
		const { printMeth } = configAll;
		const { LODOP } = window;
		let dom = document.getElementById(`printDomId-${printIndex}`);
		if (optionType >= 1) {
			dom = document.getElementById('printDomId-0');
		}
		if (!dom) {
			console.error('dom节点没找到');
			return false;
		}
		const strHTML = dom.innerHTML;
		if (!LODOP.PageDataEx || !LODOP.PageDataEx.companyname || !LODOP.PageDataEx.license) {
			console.log(LODOP.PageDataEx, 'license未注入成功,正在重新注册');
			LODOP.SET_SHOW_MODE('LANGUAGE', 0);
			LODOP.SET_LICENSES('成都市知用科技有限公司', '649677881727389907689190562356', '', '');
		}
		// LODOP.PRINT_INITA(0, 0, `${wide}cm`, `${high}cm`, `printDomId${printIndex}`);
		LODOP.PRINT_INIT(`${Math.random() * 10000 + 'test'}`);
		LODOP.SET_PRINT_MODE('RESELECT_PAGESIZE', true);
		LODOP.SET_PRINT_PAGESIZE(printMeth, info.paperWidth, info.paperHeight, 'CreateCustomPage'); // 打印方向 纸张大小.
		LODOP.ADD_PRINT_HTML(0, 0, '100%', '100%', strHTML); // HTML 打印
		switch (optionType) {
			case 1:
				LODOP.PREVIEW(); // 打印预览
				break;
			case 2:
				LODOP.PRINT_DESIGN(); // 打印设计
				break;
			case 0:
				LODOP.PRINT(); // 打印
				break;
			default:
				break;
		}
	};

	printPreview = () => {
		// 打印预览
		this.printOne(1);
	};

	printSetUp = () => {
		this.printOne(2);
	};

	printedDataSave = (index) => {
		const { selectedRows } = this.props;
		const { configAll } = this.state;
		if (!selectedRows[index] || !selectedRows[index].id) {
			console.error('printedDataSave 没有正确的id 无法保存打印信息到后台');
			return false;
		}
		const ids = selectedRows[index].id;
		getInfo({ ids }, configAll.callUrl).then((x) => {
			if (x) {
				console.log(`${ids}的打印信息已保存到后台`);
				return true;
			} else {
				return false;
			}
		});
	};

	printOneByOne = () => {
		// 按队列打印
		const { viewData, printIndex } = this.state;
		if (viewData && viewData.length) {
			this.printOne();
			const { length } = viewData;
			let LODOPObj = window.LODOP;
			LODOPObj.On_Return_Remain = true;
			LODOPObj.On_Return = (TaskId, Value) => {
				console.log(TaskId);
				if (Number(Value) === 1) {
					message.info(`正在打印第${this.state.printIndex + 1}张, 共${viewData.length}张`);
					this.printedDataSave(printIndex);
				}
				this.setState({ printIndex: this.state.printIndex + 1 }, () => {
					if (this.state.printIndex < length) {
						this.printOne();
					} else {
						LODOPObj.On_Return_Remain = false;
						this.setState({
							loading: false,
							printIndex: 0,
						});
					}
				});
			};
		} else {
			console.error('暂无任何数据无法打印');
		}
	};

	printByLodop = () => {
		if (!window.LODOP || !window.LODOP.PRINT_INIT) {
			console.error('打印服务未启动');
			ModalInfo('打印服务未启动');
			return false;
		}
		this.setState(
			{
				showWindowPrint: true,
				printIndex: 0,
				loading: true,
			},
			() => {
				this.printOneByOne();
			},
		);
	};

	render() {
		const { configAll, viewData, showWindowPrint, loading, preaparePrint } = this.state;
		if (!viewData) {
			return (
				<Shell styleShell={{ marginTop: '0', marginBottom: '20px' }}>
					<div style={{ height: '54px', padding: '12px 0 12px 12px' }}>
						<ButtonDiy
							name={'返回'}
							handleClick={() => {
								router.goBack();
							}}
						/>
					</div>
				</Shell>
			);
		}
		if (!configAll.backgroundUrl) {
			console.error('没有设置模版图片无法使用');
			return null;
		}
		const { wide, high } = configAll;
		const imageStyle = {
			height: high ? `${high}cm` : A4Height,
			width: wide ? `${wide}cm` : A4Width,
			textAlign: 'center',
		};
		const { pathname } = this.props.location;
		const templateInfo = templateCode.find((x) => {
			return x.path === pathname;
		});
		if (!templateInfo) {
			console.error('未找到templateInfo', pathname);
		}
		return (
			<Fragment>
				<Shell styleShell={{ marginTop: '0', marginBottom: '20px' }}>
					<div style={{ height: '54px', padding: '12px 0 12px 12px' }}>
						<ButtonDiy
							name={'打印设备选择'}
							handleClick={() => {
								window.LODOP.SELECT_PRINTER();
								this.setState({
									preaparePrint: true,
								});
							}}
							loading={loading}
						/>
						<ButtonDiy
							name={'打印预览'}
							handleClick={() => {
								if (!preaparePrint) {
									message.warning('请先选择打印设备');
									window.LODOP.SELECT_PRINTER();
									this.setState({
										preaparePrint: true,
									});
									return false;
								}
								this.printPreview();
							}}
							loading={loading}
						/>
						<ButtonDiy
							name={'打印'}
							handleClick={() => {
								if (!preaparePrint) {
									window.LODOP.SELECT_PRINTER();
									this.setState({
										preaparePrint: true,
									});
									message.warning('请先选择打印设备');
									return false;
								}
								this.printByLodop();
							}}
							loading={loading}
						/>

						<span style={{ float: 'right' }}>
							<ButtonDiy
								name={'返回'}
								handleClick={() => {
									const { state } = this.props.location;
									if (state && state.returnUrl) {
										router.push({
											pathname: state.returnUrl,
											searchInfo: state.searchInfo,
										});
									} else {
										router.goBack();
									}
								}}
							/>
						</span>

						<Authorized authority={'/jc/setting/PrintPositionSetting'}>
							<span style={{ float: 'right' }}>
								<ButtonDiy
									name={'打印调试模式(实施)'}
									handleClick={() => {
										this.printSetUp();
									}}
									loading={loading}
								/>
							</span>
						</Authorized>
						<Authorized authority={'/jc/setting/PrintPositionSetting'}>
							<span style={{ float: 'right' }}>
								<ButtonDiy
									name={'打印模版设置(实施)'}
									handleClick={() => {
										router.push({
											pathname: '/jc/setting/PrintConfig',
											state: { code: templateInfo.code },
										});
									}}
								/>
							</span>
						</Authorized>

						<Authorized authority={'/jc/setting/PrintPositionSetting'}>
							<span style={{ float: 'right' }}>
								<ButtonDiy
									name={'字段位置设置(实施)'}
									handleClick={() => {
										router.push({
											//pathname: '/xg/xg_hard/AwardSet/printSetting', // 中医大这里也要改
											pathname: '/jc/setting/printSetting',
											state: { code: templateInfo.code },
										});
									}}
								/>
							</span>
						</Authorized>
					</div>
				</Shell>
				{viewData && viewData.length ? (
					<div
						ref={(node) => (this.content = node)}
						style={{
							display: showWindowPrint || true ? 'block' : 'none',
						}}>
						{viewData.map((info, index) => {
							return (
								<div
									key={`${index}divKey`}
									id={`printDomId-${index}`}
									style={{
										marginBottom: '10px',
									}}>
									<div
										style={{
											position: 'relative',
											pageBreakAfter: 'avoid',
											...imageStyle,
											backgroundColor: '#fff',
										}}>
										{this.detailDom(info)}
									</div>
								</div>
							);
						})}
					</div>
				) : null}
			</Fragment>
		);
	}
}
