// 病例查询
import React from 'react';
import store from 'store';
import {Row, Col, Card, Icon, Form, Select, Input, DatePicker, Tree} from 'antd';
import Moment from 'moment';
import { $http } from 'containers/config/https';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import "./style/index.less";

let {Option} = Select;
const { TreeNode } = Tree;

class CaseSearch extends React.Component {
	constructor() {
		super();
		var userData = JSON.parse(sessionStorage.getItem('userData'));
		this.state={
			userData,
			localeProvider: {},
			customDataSet: [],
			dataSetExpandedKeys: [],
			checkedKeys: [], // 选中树check
			checkedData: [],
			tableData: [], 
			columns: [], 
			total: 0, 
			page: 1, 
			pageSize: 20,
			loading: false,
			widthTotal: 0,
			departmentInformation: [],
			wardSelectData: []
		}
	}

	componentDidMount() {
		this.getDepartmentInformation();
		// this.getTableData();
		this.getCustomDataSet();
		this.childRef.handleLoading()
	}

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

	// 3.13.23.获取科室信息
	getDepartmentInformation = () => {
		let {userData} = this.state;
		let data = {
			params: [
				{ 
					hospID: userData&&userData.hospID ? userData.hospID : "",
					type: "O^I^E^OI",
				}
			]
		}
		$http.post('urlS', this, {
			code: "04020008",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ departmentInformation: res.result.Data})
				} else {
					this.setState({ departmentInformation: [] })
				}
			}
		})
	}

	// 获取病区下拉数据
	getWardSelectData = (e) => {
		if (!e) {
			this.setState({wardSelectData: []})
			this.props.form.setFieldsValue({admWardID: undefined})
			return;
		}
		let {userData} = this.state;
		let data = {
			params: [
				{ 
					hospID: userData&&userData.hospID ? userData.hospID : "",
					locID: e, // 科室名称
					type: "W",
					linkFlag: 1,
					linkType: "W"
				}
			]
		}
		$http.post('urlS', this, {
			code: "04020008",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ wardSelectData: res.result.Data&&res.result.Data.length > 0 ? res.result.Data[0].linkLoc : []})
				} else {
					this.setState({ wardSelectData: [] })
				}
			}
		})
	}

	// 获取自定义数据集
	getCustomDataSet = () => {
		let data = {
			params: [{
				ID: '', // 表ID
				code: '', // 数据集代码
				descripts: '', // 数据集描述
				serviceCode: '', // 服务代码
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: "06010017",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.length; i++) {
						res.result[i].key = "main"+res.result[i].ID;
					}
					this.setState({ customDataSet: res.result}, () => {
						for(var i = 0; i < this.state.customDataSet.length; i++) {
							if (this.state.customDataSet[i].ID == 1 || this.state.customDataSet[i].ID == 8) {
								let obj = {};
								obj.props =  this.state.customDataSet[i];
								obj.props.dataRef = this.state.customDataSet[i];
								this.onLoadData(obj, true)
							}
						}
					})
				}
			}
		})
	}

	renderCustomDataSetTreeNodes = data => data.map(item => {
		const index = item.descripts.indexOf(this.state.dataSetValue);
		const beforeStr = item.descripts.substr(0, index);
		const afterStr = item.descripts.substr(index + this.state.dataSetValue&&this.state.dataSetValue.length);
		const title = index > -1 ? (
			<span>
			{beforeStr}
			<span style={{ color: '#FF7F00' }}>{this.state.dataSetValue}</span>
			{afterStr}
			</span>
		) : <span>{item.descripts}</span>;
		let disabled = item.key.substring(0, 4) === "main" ? true : false;
		if (item.children&&item.children.length > 0) {
			return (
				<TreeNode title={title} key={item.ID} dataRef={item} disabled={disabled}>
					{this.renderCustomDataSetTreeNodes(item.children)}
				</TreeNode>
			);
		}
		return <TreeNode title={title} key={item.ID} {...item} dataRef={item} disabled={disabled} />;
	});

	// 异步加载数据集的子数据数据
	onLoadData = (treeNode, isSet) =>
		new Promise(resolve => {
			if ((treeNode.props&&(!treeNode.props.serviceCode)) || (treeNode.props&&treeNode.props.children)) {
				resolve();
				return;
			}
			let ID = treeNode.props&&treeNode.props.ID ? treeNode.props.ID : "";
			let mianCode = treeNode.props&&treeNode.props.code ? treeNode.props.code : "";
			let data = {
				params: [{
					code: "", // 数据集代码
					descripts: "", // 数据集描述
					CBEMRDSRParRef: ID,
				}],
				pagination: [{
					pageSize: 1000,
					currentPage: 1
				}]
			}
			$http.post('urlS', this, {
				code: "06010025",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0 && res.result) {
						for(var i = 0; i < res.result.length; i++) {
							res.result[i].key = mianCode+res.result[i].code;
							res.result[i].isLeaf = true;
							res.result[i].serviceCode = treeNode.props.serviceCode;
							res.result[i].type = 'C',
							res.result[i].customID = res.result[i].ID; 
						}
						treeNode.props.dataRef.children = res.result;
						// console.log(this.state.customDataSet)
						this.setState({
							customDataSet: [...this.state.customDataSet],
						}, () => {
							if (isSet) {
								let checkedKeys = ["CUS01001patNo", "CUS01001patName", "CUS01001patSexDesc", "CUS01001patAge", "CUS01004admDateTime", "CUS01004disDateTime", "CUS01004admLocDesc"];
								this.filterCheckedData(res.result, checkedKeys)
								this.setState({checkedKeys})
							}
						});
						resolve();
					} else {
						resolve();
					}
				}
			})
		}
	)

	// 根据key值刷选出相对应的数据
	filterCheckedData = (data=[], keys=[]) => {
		let checkedData = [];
		for(var i = 0; i < keys.length; i++) {
			for(var j = 0; j < data.length; j++) {
				if (keys[i] === data[j].key) {
					checkedData.push(data[j])
				}
			}
		}
		this.setState({checkedData: this.state.checkedData.concat(checkedData)}, () => {
			this.handleArrColumn()
		})
	}

	dataSetOnExpand = (dataSetExpandedKeys) => {
		this.setState({
			dataSetExpandedKeys,
		});
	}

	handleTreeCheck = (checkedKeys, info) => {
		let checkedData = []
		for(var i = 0; i < info.checkedNodes.length; i++) {
			checkedData.push(info.checkedNodes[i].props.dataRef)
		}
		this.setState({checkedKeys, checkedData})
	};

	handleQuery = () => {
		this.setState({pageSize: 20}, () => {
			this.getTableData()
		})
	}
	
	// 获取表格数据
	getTableData = () => {
		let {pageSize, page} = this.state;
		const { form: { validateFields } } = this.props;
		validateFields((errors, values) => {
				// 验证成功
				if (errors === null) {
					values.admInStartDate = values&&values.admInStartDate ? Moment(values.admInStartDate).format("YYYY-MM-DD") : ""
					values.admInEndDate = values&&values.admInEndDate ? Moment(values.admInEndDate).format("YYYY-MM-DD") : ""
					values.admOutStartDate = values&&values.admOutStartDate ? Moment(values.admOutStartDate).format("YYYY-MM-DD") : ""
					values.admOutEndDate = values&&values.admOutEndDate ? Moment(values.admOutEndDate).format("YYYY-MM-DD") : ""
					let data = {
						params: [{
							...values
						}],
						pagination:[{ 
							pageSize: pageSize,
							currentPage: page,
							sortColumn: "Code",
							sortOrder: "asc"
						}]
					}
					$http.post('urlDeault', this, {
						code: "06050009",
						data: data,
						success: (res) => {
							if (+res.errorCode === 0) {
								for(var i = 0; i < res.result.length; i++) {
									res.result[i].key=i
								}
								this.setState({tableData: res.result, total: res.totalNum})
							}
						}
					})
				}
		})
	}
	

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

	handleCardMain = () => {
		this.mainColumnRef.onOpenModel();
	}

	// 获取表头数据
	getTableColumns = () => {
		let {userData} = this.state;
		let data = {
			params: [{
				compontName: "CaseSearch",
				type: 'C',
			}]
		}
		$http.post('urlS', this, {
			code: '01040073',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
						return  {
							...item,
							key: index + 1,
							title: <div onDoubleClick={this.handleCardMain}>{userData.language == 'EN' ? (item&&item.enDescripts ? item.enDescripts : item.title) : item.title}</div>
						}
					}) : '';
					let filterArr = arr.filter(function(item){ return item.display === 'Y'});
					this.setState({
						columns: filterArr, widthTotal: res.totalWidth,
						localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
					})
				}
			}
		})
	}

	onRef = ref => {
		this.childRef = ref
	}

	// 添加列结果
	handleArrColumn = () => {
		let widthTotal = 0;
		let columns = this.state.checkedData&&this.state.checkedData.length > 0 ?this.state.checkedData.map((item, index) => {
			return {
				key: index+1,
				title: item.descripts,
				dataIndex: item.key,
				width: 100,
				align: "center"
			}
		}) : []
		for(var i = 0; i < columns.length; i++) {
			widthTotal+=columns[i].width
		}
		this.setState({columns, widthTotal})
	}

	render() {
		let {dataSetExpandedKeys, customDataSet, checkedKeys, tableData, columns, total, page, pageSize, loading, widthTotal, departmentInformation, wardSelectData} = this.state;

		const { getFieldDecorator } = this.props.form;
		const formItemInput  = {
			labelCol: {span: 8},
			wrapperCol: {span: 16}
		};

		// 组件所需参数
		const param = {
			// 表头配置
			columns: columns&&columns.length > 0 ? columns : [],
			// 表格数据
			data: tableData,
			// 数据总条数
			total,
			// 当前页数
			page,
			pageSize,
			// 表格的宽度
			x: columns&&columns.length > 0 ? widthTotal : 4000,
			y: store.getState().tableHeight.y + 95,
			height: store.getState().tableHeight.y + 140 + 'px',
			loading,
			TableClassName: "case-search-table"
		}
		
		// 科室
    let locOption = departmentInformation&&departmentInformation.map((item, index) => {
      return (<Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
		})
		
		// 病区
		let wardOption = wardSelectData&&wardSelectData.map((item, index) => {
      return (<Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
		})
		return (
			<div className="case-search">
				<Row>
					<Col xs={12} sm={12} md={10} lg={8} xl={6} xxl={4}>
						<Card
							size="small"
							title={<div className="card-title-left-icon">
								<div></div>
								{this.setMessage("DispQueryPrescListOperation_button", "descripts", "查询条件")}
								<div style={{float: "right"}}><span className="span" onClick={this.handleQuery}>查询</span></div>
							</div>}
							className="card-padding-no"
						>
							<div style={{height: store.getState().tableHeight.y / 2 + 64 + "px", overflow: "auto", padding: "0 12px"}} className="scroll-bar-style">
								<Form>
									<Form.Item label={this.setMessage("DispQueryPrescListCard_number", "descripts", "全文检索：")} {...formItemInput}>
										{getFieldDecorator('contentElement', {
											initialValue: undefined,
										})(
											<Input placeholder={this.setMessage("DispQueryPrescListCard_number", "message", "请输入检索条件(Enter)")} allowClear onPressEnter={this.getTableData} />
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListCard_number", "descripts", "患者姓名：")} {...formItemInput}>
										{getFieldDecorator('patName', {
											initialValue: undefined,
										})(
											<Input placeholder={this.setMessage("DispQueryPrescListCard_number", "message", "请输入患者姓名(Enter)")} allowClear onPressEnter={this.getTableData} />
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListCard_number", "descripts", "登记号：")} {...formItemInput}>
										{getFieldDecorator('patNo', {
											initialValue: undefined,
										})(
											<Input placeholder={this.setMessage("DispQueryPrescListCard_number", "message", "请输入登记号(Enter)")} allowClear onPressEnter={this.getTableData} />
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListCard_number", "descripts", "病案号：")} {...formItemInput}>
										{getFieldDecorator('patMedicalNo', {
											initialValue: undefined,
										})(
											<Input placeholder={this.setMessage("DispQueryPrescListCard_number", "message", "请输入病案号(Enter)")} allowClear onPressEnter={this.getTableData} />
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListCard_number", "descripts", "就诊号：")} {...formItemInput}>
										{getFieldDecorator('patAdmNo', {
											initialValue: undefined,
										})(
											<Input placeholder={this.setMessage("DispQueryPrescListCard_number", "message", "请输入就诊号(Enter)")} allowClear onPressEnter={this.getTableData} />
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListStatus", "descripts", "就诊类型：")} {...formItemInput}>
										{getFieldDecorator('patAdmType', {
											initialValue: "O",
										})(
											<Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DispQueryPrescListPlease_choose", "descripts", "请选择")}>
												<Option value="O">
													门诊
												</Option>
												<Option value="EM">
													急诊
												</Option>
												<Option value="I">
													住院
												</Option>
												<Option value="ALL">
													全部
												</Option>
											</Select>
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListStatus", "descripts", "科室：")} {...formItemInput}>
										{getFieldDecorator('admLocID', {
											initialValue: undefined,
										})(
											<Select onChange={this.getWardSelectData} showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DispQueryPrescListPlease_choose", "descripts", "请选择")}>
												{locOption}
											</Select>
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListStatus", "descripts", "病区：")} {...formItemInput}>
										{getFieldDecorator('admWardID', {
											initialValue: undefined,
										})(
											<Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DispQueryPrescListPlease_choose", "descripts", "请选择")}>
												{wardOption}
											</Select>
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListStart_date", "descripts", "入院起始日期：")} {...formItemInput}>
										{getFieldDecorator('admInStartDate', {
											initialValue: undefined,
										})(
											<DatePicker format="YYYY-MM-DD" style={{width: '100%'}} />
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListClosing_date", "descripts", "入院截止日期：")} {...formItemInput}>
										{getFieldDecorator('admInEndDate', {
											initialValue: undefined,
										})(
											<DatePicker format="YYYY-MM-DD" style={{width: '100%'}} />
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListStart_date", "descripts", "出院起始日期：")} {...formItemInput}>
										{getFieldDecorator('admOutStartDate', {
											initialValue: undefined,
										})(
											<DatePicker format="YYYY-MM-DD" style={{width: '100%'}} />
										)}
									</Form.Item>
									<Form.Item label={this.setMessage("DispQueryPrescListClosing_date", "descripts", "出院截止日期：")} {...formItemInput}>
										{getFieldDecorator('admOutEndDate', {
											initialValue: undefined,
										})(
											<DatePicker format="YYYY-MM-DD" style={{width: '100%'}} />
										)}
									</Form.Item>
								</Form>
							</div>
						</Card>
						<div style={{height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%'}}></div>
						<Card
							size="small"
							title={<div className="card-title-left-icon">
								<div></div>
								{this.setMessage("DispQueryPrescListQuery_criteria", "descripts", "定义结果设置")}
								<div style={{float: "right"}}><span className="span" onClick={this.handleArrColumn}>添加列结果</span></div>
							</div>}
							className="card-padding-no"
						>
							<div style={{height: store.getState().tableHeight.y / 2 + 63 + "px", overflow: "auto", padding: "0 12px"}} className="scroll-bar-style">
								<Tree 
									checkable
									checkedKeys={checkedKeys}
									onCheck={this.handleTreeCheck}
									loadData={this.onLoadData}
									onExpand={this.dataSetOnExpand}
									expandedKeys={dataSetExpandedKeys}
								>
									{this.renderCustomDataSetTreeNodes(customDataSet)}
								</Tree>
							</div>
						</Card>
					</Col>
					<Col xs={12} sm={12} md={14} lg={16} xl={18} xxl={20}>
						<div style={{paddingLeft: '6px', position: 'relative', height: "calc(100%-37px)", overflow: "auto"}}>
							<Card
								size="small"
								title={<div className="card-title-left-icon"><div></div>{this.setMessage("DispQueryPrescListPrescription_list", "descripts", "电子病历综合查询结果")}</div>}
								extra={<span style={{color: '#fff'}} className='span' onClick={this.handleCardMain}><Icon type="setting" title={this.setMessage("DispQueryPrescListColumn_permission_settings", "descripts", "列权限设置")} /></span>}
							>
								<div style={{height: store.getState().tableHeight.y + 180 + "px"}}>
									<PubilcTablePagination
										param={param}
										handelThis={this}
										onRef={this.onRef}
									/>
								</div>
							</Card>
							<div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%'}}></div>
						</div>
					</Col>
				</Row>
				<ColumnAuthoritysModel
					clientWidth='800px'
					compontName='CaseSearch'
					configType="C"
					onRef={this.onMainColumnRef}
					reloadData={this.getTableColumns}
				/>
			</div>
		)
	}
};
const CaseSearchForm = Form.create()(CaseSearch);
export default CaseSearchForm;