// 电子导出
import React from 'react';
import { message, Input, Icon, Button, Table, Modal, Popconfirm, Select, Row, Col } from 'antd';
import { $http } from 'containers/config/https';
import { httpConfig } from 'containers/config/httpConfig';
import ColumnAuthoritysModel from '../columnAuthority/ColumnAuthoritysModel';
import CommonRangePicker from 'components/rangePicker/index';
import './style/index.less';
import moment from 'moment';
import fetchJsonp from 'fetch-jsonp';
const { confirm } = Modal;
const { Option } = Select;
let user;
export default class ExportEmr extends React.Component {
	constructor() {
		super();
		this.state = {
			hospID: window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData).hospID : '',
			tableData: [], //导出数据
			cloumns: [], //列头信息
			number: 10,
			templateID: '',
			hospital: [], //医院列表
			template: [], //病历列表
			stDate: moment(moment().subtract(29, 'days')).format('YYYY-MM-DD'),
			endDate: moment().format('YYYY-MM-DD')
		};
		user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
	}
	componentDidMount() {
		// 获取医院列表
		this.getHospital();
		// 初始化列表数据
		this.getDetailTableColumns();
		//初始化病历
		this.getTemplateList();
	}
	// 获取明系列表头数据
	getDetailTableColumns = () => {
		let data = {
			params: [
				{
					reactCode: [ 'exportEMR' ],
					compontName: 'exportEMR',
					type: 'C'
				}
			]
		};
		$http.post('urlS', this, {
			code: '01040073',
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
				}
			}
		});
	};
	///获取医院列表 (本院及下级医院)
	getHospital = () => {
		let data = {
			params: [
				{
					hospID: user.hospID,
					logonGroupID: user.groupID,
					logonHospID: user.hospID
				}
			]
		};

		$http.post('urlDeault', this, {
			code: '01040001',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					this.setState({ hospital: res.depDoctor });
				}
			}
		});
	};
	getTemplateList = () => {
		let data = {
			params: [
				{
					hospID: this.state.hospID
				}
			]
		};
		$http.post('urlDeault', this, {
			code: '06050021',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					this.setState({ template: res.result });
				}
			}
		});
	};
	componentWillUnmount() {
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state, callback) => {
			return;
		};
	}
	/**
     * 选择医院触发
     * @param {*} value 
     */
	onChangehosp = (value) => {
		this.setState(
			{
				hospID: value
			},
			() => {
				this.getTemplateList();
			}
		);
	};
	/**
     * 修改input框数据事件
     * @param {*} code 
     * @param {*} e 
     */
	onChangeValue = (code, e) => {
		this.setState({ [code]: e.target.value });
	};
	/**
     * 选择病历事件
     * @param {*} value 
     */
	onSelectTemplate = (value) => {
		this.setState({
			templateID: value
		});
	};
	//导出病历PDF
	exportEmrPDF() {
		let url = httpConfig.ipDeault;
		if (window.location && window.location.host && window.location.host != '127.0.0.1:3000') {
			url = window.location.protocol + '//' + window.location.host;
		}
		let httpUrlAddress = url + httpConfig.urlAddress;
		if (httpUrlAddress.indexOf('https://') >= 0) {
		} else {
			if (httpUrlAddress.indexOf('http://') < 0) {
				httpUrlAddress = 'http://' + httpUrlAddress;
			}
		}
		let dllInput = {};
		dllInput.exeName = 'EMRExport.exe';
		let parameter = '';
		let sessionObj = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		let _this = this;
		Object.keys(sessionObj).forEach(function(key) {
			if (key != 'hospID') {
				parameter = parameter + key + ':' + sessionObj[key] + ',';
			} else {
				parameter = parameter + key + ':' + _this.state.hospID + ',';
			}
		});
		httpUrlAddress = httpUrlAddress.replace(/:/g, '$');
		let authorization = httpConfig.authorizationToken;
		authorization = authorization.replace(/ /g, '$');
		parameter = parameter + 'connetedIP:' + httpUrlAddress + ',';
		parameter = parameter + 'authorization:' + authorization + ',';

		parameter = parameter + 'templateID:' + this.state.templateID;
		parameter = parameter + ',' + 'exportNumber:' + this.state.number;
		parameter = parameter + ',' + 'stDate:' + this.state.stDate;
		parameter = parameter + ',' + 'endDate:' + this.state.endDate;
		dllInput.parameter = parameter;

		if (typeof CefSharp != 'undefined') {
			// 新元素定制浏览器
			dllInput.path = '1';
			CefSharp.BindObjectAsync('xysCefToJavaScripts');
			setTimeout(() => {
				xysCefToJavaScripts
					.driveLocalHardware(
						"{'inputDir':'ExportEMR/OpenExe.dll','clsName':'OpenExe.ExeObj','funcName':'CreateProcess','dllInput':'" +
							JSON.stringify(dllInput) +
							"'}"
					)
					.then((returnVale) => {
						console.log(returnVale);
					});
			}, 100);
		} else {
			dllInput.path = 'C:\\ProgramData\\XYS\\XYSService\\plugins\\ExportEMR\\';
			let data =
				'input={"inputDir":"ExportEMR/OpenExe.dll","clsName":"OpenExe.ExeObj","funcName":"CreateProcess","dllInput":' +
				JSON.stringify(dllInput) +
				'}';
			let that = this;
			fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
				jsonpCallback: 'JsonCallback',
				timeout: 30000
			})
				.then(function(response) {
					console.log(1);
					return response.json();
				})
				.then(function(json) {
					console.log(2);
				})
				.catch(function(ex) {
					console.log(3);
				});
		}
	}
	save = () => {
		this.exportEmrPDF();
	};
	render() {
		const hospital = [];
		this.state.hospital.map((item) => {
			hospital.push(
				<Option key={item.id} value={item.id + ''} title={item.descspell}>
					{item.descripts}
				</Option>
			);
		});
		const templateOption = [];
		this.state.template.map((item) => {
			templateOption.push(
				<Option key={item.ID} value={item.ID + ''} title={item.code + item.descripts}>
					{item.descripts}
				</Option>
			);
		});
		return (
			<div className="exportEMR" style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
				<ColumnAuthoritysModel
					clientWidth="800px"
					compontName="exportEMR"
					configType="C"
					onRef={this.onColumnRef}
					reloadData={this.getDetailTableColumns}
				/>
				<div className="table-operations">
					<Row style={{ minHeight: '80px', padding: '0 24px 24px 24px' }}>
						<Col span={23}>
							医院：<Select
								style={{ width: '180px', margin: '23px 15px 0 0' }}
								value={this.state.hospID}
								onChange={this.onChangehosp}
							>
								{hospital}
							</Select>
							病历:<Select
								allowClear={true}
								showSearch={true}
								optionFilterProp="title"
								placeholder="请选择要导出的病历"
								value={this.state.templateID}
								style={{ width: '220px', margin: '23px 15px 0 0' }}
								onChange={this.onSelectTemplate}
							>
								{templateOption}
							</Select>
							<div style={{ display: 'inline-block', margin: '23px 15px 0px 0px' }}>
								<CommonRangePicker
									width={320}
									label="起止日期："
									startDate={this.state.stDate}
									endDate={this.state.endDate}
									format={'YYYY-MM-DD'}
									startChange={(date) => this.setState({ stDate: date })}
									endChange={(date) => this.setState({ endDate: date })}
								/>
							</div>
							导出份数:<Input
								allowClear={true}
								value={this.state.number}
								onChange={this.onChangeValue.bind(this, 'number')}
								placeholder="导出份数"
								style={{ width: '160px', margin: '23px 15px 0 0' }}
							/>
							<Button type="primary" onClick={this.save} style={{ margin: '23px 15px 0 0' }}>
								导出
							</Button>
							<Button
								onClick={this.saveAs}
								style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '23px 15px 0 0' }}
							>
								另存为
							</Button>
						</Col>
					</Row>
				</div>
				<div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }} />
				<div style={{ width: '100%', height: 'calc(100% - 127px)', overflow: 'hidden' }} />
			</div>
		);
	}
}
