// 病例浏览
import React from 'react';
import { $http } from 'containers/config/https';
import {Input, Select, Button, Table, Pagination } from 'antd';
import store from 'store';
import "./style/index.less";

let {Option} = Select;
import ElectronicCaseTemplate from 'pages/common/ElectronicCaseTemplate.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

export default class CasePreview extends React.Component {
	constructor() {
		super();
		var recordData = JSON.parse(sessionStorage.getItem('patientData'));
		var userData = JSON.parse(sessionStorage.getItem('userData'));
		this.state = {
			recordData,
			userData,
			savedTemplatesData: [],
			templatePath: "",
			patienHistoryData: [],
			modalRowData: {},
			locRadioValue: undefined, // 就诊类型
			diagnosis: undefined, // 诊断
			historyAdmData: [],
			historyAdmPageSize: 20,
			historyAdmPage: 1,
			historyAdmTotal: 0,
			columns: [], 
			tableData: [], 
			total: 0, 
			page: 1, 
			pageSize: 20,
			totalWidth: 0
		}
	}

	componentDidMount() {
		this.getColumnsData();
		this.getHistoryAdmData();
	}

	//国际化
	setMessage = (name, message, defaultTitle) => {
		return this.state.localeProvider&&this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
	}


	handleCaseTemplateRef = ref => {
		this.caseTemplateChild = ref;
	}

	// 获取已保存模板
	getSavedTemplatesData = (recordData) => {
		let data = {
			params: [{
				admID: recordData&&recordData.admID ? recordData.admID : "", // 就诊记录主键
			}]
		}
		$http.post('urlS', this, {
			code: "06010096",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = res.result&&res.result.dataAry ? JSON.parse(JSON.stringify(res.result.dataAry)) : [];
					for(var i = 0; i < arr.length; i++) {
						arr[i].ID = arr[i].eMRTemplateID;
					}
					this.setState({savedTemplatesData: arr})
				}
			}
		})
	}

	// 双击加载已保存模板
	handleSaveDTemplatesClick = (item) => {
		let key = [];
		let treeSelectData = JSON.parse(JSON.stringify(item));
		treeSelectData.ID = treeSelectData.wTemplateCatID;
		key.push(treeSelectData.eMRTemplateID);
		this.setState({selectedKeys: key, treeSelectData}, () => {
			let obj = JSON.parse(JSON.stringify(item));
			obj.ID = obj.eMRTemplateID;
			obj.releaseVersion = obj.eMRReleaseVersion, // 版本号
			setTimeout(() => {
				this.getPatienHistoryData(obj);
			}, 300)
		})
	}

	// 3.6.8.获取患者病历数据
	getPatienHistoryData = (obj, flag) => {
		this.setState({modalRowData: obj}); // 选择的模板数据
		let {recordData, treeSelectData} = this.state;
		let data = {
			params: [{
				admID: recordData&&recordData.admID ? recordData.admID : "",
				catalogueID: treeSelectData.ID, // 分组目录ID
				groupTemplateID: obj.ID, // 分组模板ID
			}]
		}
		$http.post('urlS', this, {
			code: "06050008",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					// console.log(res.result)
					this.setState({templatePath : res.result&&res.result.templatePath ? res.result.templatePath : ''}, () => {
						this.state.templatePath ? this.caseTemplateChild.setElementTextByID(this.state.templatePath, res.result.dataSource, "N", "boolFalse") : this.caseTemplateChild?.NewFile();
					})
				} else {
					this.setState({patienHistoryData: []})
				}
			}
		})
	}

	handleAdmTypeChange = e => {
		this.setState({locRadioValue: e})
	}

	handleQuery = () => {
		this.setState({page: 1}, () => {
			this.getHistoryAdmData()
		})
	}

	// 获取历史就诊
	getHistoryAdmData = () => {
		let {recordData, locRadioValue, diagnosis, pageSize, page} = this.state;
		let data = {
			params: [{
				admID: recordData&&recordData.admID ? recordData.admID : "",
				diagnosis,
				// currentDoc: currentDoc ? "Y" : "N", // 当前医师
				admType: locRadioValue, // 就诊类型
				// admLoc: currentRadio === "currentLocID" ? (userData&&userData.locID ? userData.locID : "") : "", // 就诊科室
				// power: "DocEMRHistory",
				// catalogueID: treeSelectData&&treeSelectData.ID ? treeSelectData.ID : "", // 分组模板目录ID
				// groupTemplateID: modalRowData&&modalRowData.ID ? modalRowData.ID : "", // 病历模板ID
			}],
			pagination: [{
				pageSize,
				currentPage: page
			}]
		}
		$http.post('urlS', this, {
			code: "06010069",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					for(var i = 0; i < res.result.Data.length; i++) {
						res.result.Data[i].key = i;
					}
					this.setState({tableData: res.result.Data, total: res.result.totalCount});
				} else {
					this.setState({tableData: [], total: 0})
				}
			}
		})
	}

	commonTableRef = ref => {
		this.commonTableChild = ref;
	}

	onMainColumnRef = ref => {
		this.mainColumnRef = ref;
	}

	getColumnsData = () => {
		let {userData} = this.state;
		let data = {
			params: [{
				compontName: "EMRCitingResourcesHistoryAdm",
				type: "",
			}]
		}
		$http.post('urlDeault', this, {
			code: "01040073",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					var totalWidth = 0;
					let arr = res.result.C&&res.result.C.map((item, index) => {
						return {
							...item,
							key: index,
							widthNum: parseInt(item.width),
							title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item&&item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
						}
					});
					let filterArr = arr.filter(function(item){ return item.display === 'Y'});
					for(var i = 0; i < filterArr.length; i++) {
						totalWidth += filterArr[i].widthNum;
					}
					this.setState({
						columns: filterArr,
						totalWidth,
						localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
					})
				}
			}
		})
	}
	  
	handleRow = (record) => {
        return {
            // 单击行选中
            onDoubleClick: () => {
				this.setState({rowId: record.admID}, () => {
					this.getSavedTemplatesData(record)
				})
           }
       }
    }

    handleRowClassName = (record) => {
        return record.admID === this.state.rowId ? 'clickRowStyle' : '';
	}

	handlePaginationChange = (pageNumber) => {
		this.setState({page: pageNumber}, () => {
			this.getHistoryAdmData()
		})
	}

	handleShowSizeChange = (current, size) => {
		this.setState({page: 1, pageSize: size}, () => {
			this.getHistoryAdmData()
		})
	}

	handleDiagnosisChange = e => {
		this.setState({diagnosis: e.target.value})
	}

	render() {
		let {savedTemplatesData, modalRowData, locRadioValue, columns, tableData, totalWidth, total, page, pageSize, diagnosis} = this.state;
		let param = {
			isInsert: "hidden",
			formView: "Normal",
			isFont: true,
			isBasicOperation: true,
		}

		let savedTemplatesDom = savedTemplatesData&&savedTemplatesData.length > 0 ? savedTemplatesData.map((item, index) => {
			return (
				<li key={index} onDoubleClick={() => this.handleSaveDTemplatesClick(item)} 
					style={{
						borderBottom: "1px solid #e8e8e8", 
						padding: '2px 6px', background: "#fff", cursor: "pointer", marginRight: "12px",
						color: modalRowData&&(modalRowData.ID === item.ID) ? "#40a9ff" : "#000000a6",
						textAlign: "center"
					}}
				>
					{item.eMRtemplateDesc}
				</li>
			)
		}) : <li>{this.setMessage("CaseInformationPageNo_saved_templates", "descripts", "暂无已保存模板")}</li>;

		let admTypeOption = (
			<Select style={{width: "150px"}} value={locRadioValue} onChange={this.handleAdmTypeChange} placeholder="就诊类型">
				<Option value="O">
					门诊
				</Option>
				<Option value="EM">
					急诊
				</Option>
				<Option value="I">
					住院
				</Option>
				<Option value="">
					全部
				</Option>
			</Select>
		)

		return (
			<div style={{height: "100%"}} className="case-preview">
				<div style={{width: "400px", height: '100%', display: 'inline-block', overflow: 'hidden'}}>
					<div style={{textAlign: "center", height: '34px', lineHeight: '34px', fontWeight: 900, fontSize: "14px", background: "#fafafa", borderBottom: "1px solid #e8e8e8"}}>{this.setMessage("MRTemplate", "descripts", "历史就诊")}</div>
					<div style={{padding: "12px"}}>
						{admTypeOption}
						<Input style={{width: "120px", margin: "0 12px 0 6px"}} placeholder="诊断" disabled value={diagnosis} onChange={this.handleDiagnosisChange} />
						<Button type="primary" onClick={this.handleQuery}>查询</Button>
					</div>
					<div style={{padding: "0 12px"}}>
						<Table 
							columns={columns} 
							bordered
							dataSource={tableData}
							scroll={{x: totalWidth, y: store.getState().tableHeight.y + 241 - 198}}
							onRow={this.handleRow}
							pagination={false}
							rowClassName={this.handleRowClassName}
						/>
						<Pagination 
							style={{float: "right", marginTop: "8px"}} 
							size="small" 
							current={page}
							total={total} showSizeChanger 
							pageSize={pageSize}
							onChange={this.handlePaginationChange}
							onShowSizeChange={this.handleShowSizeChange}
						/>
					</div>
				</div>
				<div style={{width: "calc(100% - 600px)", height: '100%', display: 'inline-block', overflow: 'auto'}}>
					<div style={{padding: '0 6px', position: 'relative', height: '100%' }}>
						<div style={{height: "100%"}}>
							<ElectronicCaseTemplate 
								param={param}
								onRef={this.handleCaseTemplateRef}
							/>
						</div>
						<div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%'}}></div>
						<div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%'}}></div>
					</div>
				</div>
				<div style={{width: "200px", height: '100%', display: 'inline-block', overflow: 'hidden'}}>
					<div style={{textAlign: "center", height: '34px', lineHeight: '34px', fontWeight: 900, fontSize: "14px", background: "#fafafa", borderBottom: "1px solid #e8e8e8"}}>{this.setMessage("CaseInformationPageMRTemplate", "descripts", "病历目录导航")}</div>
					<ul>
						{savedTemplatesDom}
					</ul>
				</div>
				<ColumnAuthoritysModel
					clientWidth='800px'
					compontName='EMRCitingResourcesHistoryAdm'
					configType="C"
					onRef={this.onMainColumnRef}
					reloadData={this.getColumnsData}
				/>
			</div>
		)
	}
}