// 新增医嘱项
import React from 'react';
import { Button, Icon, message } from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';

import ADAEssentialInformation from './component/ADAEssentialInformation.jsx'; // 基本信息
import ADAPharmaceuticalInformation from './component/ADAPharmaceuticalInformation.jsx'; // 药学相关信息
import ADAEquivalentUnit from './component/ADAEquivalentUnit.jsx'; // 等效单位
import ADADoctorAdviceAlias from './component/ADADoctorAdviceAlias.jsx'; // 医嘱项别名
import ADADrugRestriction from './component/ADADrugRestriction.jsx'; // 限制用药

import '../style/index.less';

class AddDoctorAdvice extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			active: 'all',
			scroll: 'all',
			essentialInformationSubValue: {}, // 基本信息form表单数据
			pharmaceuticalInformationSubValue: {}, // 药学相关信息form表单数据
			equivalentUnitTableData: [], // 等效单位表格数据
			doctorAdviceAliasTableData: [], // 医嘱项别名表格数据
			drugRestrictionTableData: [], // 限制用药表格数据
			rowId: '',
			medDetailData: {}, // 医嘱项明细
			isSaveAnother: '',
			ChineseEnglishSize: {}, //中英翻译
		}
	}

	componentDidMount() {
		this.props.onRef(this);
		document.getElementById("advice-floor-box").addEventListener('scroll', this.bindHandleScroll)
	}

	componentWillReceiveProps(newData) {
		if (JSON.stringify(this.state.ChineseEnglishSize) !== JSON.stringify(newData.ChineseEnglishSize)) {
			this.setState({ ChineseEnglishSize: newData.ChineseEnglishSize })
		}
		if (this.state.rowId !== newData.rowId) {
			this.setState({ rowId: newData.rowId, isSaveAnother: newData.isSaveAnother }, () => {
				this.getMedDetailData();
				this.pharmaceuticalInformationChild.getMedicalOrder(newData.rowId);
			})
		}
	}

	componentWillUnmount() {
		document.getElementById("advice-floor-box").removeEventListener('scroll', this.bindHandleScroll);
	}

	bindHandleScroll = event => {
		if (event.target.scrollTop === 0) {
			this.setState({ scroll: 'all' })
		} else if (event.target.scrollTop > 0 && event.target.scrollTop < 280) {
			this.setState({ scroll: '1' })
		} else if (event.target.scrollTop > 288 && event.target.scrollTop < 480) {
			this.setState({ scroll: '2' })
		} else if (event.target.scrollTop > 480 && event.target.scrollTop < 660) {
			this.setState({ scroll: '3' })
		} else if (event.target.scrollTop > 660) {
			this.setState({ scroll: '4' })
		}
	}

	// 获取医嘱项明细
	getMedDetailData = () => {
		if (!(this.state.rowId)) {
			return;
		}
		this.essentialInformationChild.resetFields();
		this.pharmaceuticalInformationChild.resetFields()
		var data = {
			params: [{
				medID: this.state.rowId
			}],
		}
		$http.post('url', this, {
			code: "02020223",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let medDetailData = res.result;
					let doseUnitTableData = medDetailData && medDetailData.doseUnit && medDetailData.doseUnit.rows ? medDetailData.doseUnit.rows : [];
					let medAliasTableData = medDetailData && medDetailData.medAlias && medDetailData.medAlias.rows ? medDetailData.medAlias.rows : [];
					let medAutTableData = medDetailData && medDetailData.medAut && medDetailData.medAut.rows ? medDetailData.medAut.rows : [];
					this.equivalentUnitChild.getTableData(doseUnitTableData);
					this.doctorAdviceAliasChild.getTableData(medAliasTableData);
					this.drugRestrictionChild.getTableData(medAutTableData);
					this.setState({ medDetailData })
				}
			}
		});
	}

	// 切换显示组件
	handleToggleActive = (key) => {
		this.setState({ active: key, scroll: key }, () => {
			if (this.state.active === "all") {
				document.getElementById("advice-floor-box").scrollTop = 0
			}
		})
	}

	resetFields = () => {
		this.essentialInformationChild.resetFields();
		this.pharmaceuticalInformationChild.resetFields();
		this.equivalentUnitChild.resetFields();
		this.doctorAdviceAliasChild.resetFields();
		this.drugRestrictionChild.resetFields();
	}

	// 重置编辑状态
	resetFieldsEditingKey = () => {
		this.equivalentUnitChild.resetFieldsEditingKey();
		this.doctorAdviceAliasChild.resetFieldsEditingKey();
		this.drugRestrictionChild.resetFieldsEditingKey();
	}

	// 新增
	handleNewlyAdded = (isQuery) => {
		this.setState({
			active: 'all', medDetailData: {},
			essentialInformationSubValue: {},
			pharmaceuticalInformationSubValue: {},
			equivalentUnitTableData: [],
			doctorAdviceAliasTableData: [],
			drugRestrictionTableData: [],
		}, () => {
			this.resetFields();
			isQuery ? this.props.handleQuery() : "";
		})
	}

	// 基本信息
	essentialInformationOnRef = ref => {
		this.essentialInformationChild = ref
	}

	// 药学相关信息
	pharmaceuticalInformationOnRef = ref => {
		this.pharmaceuticalInformationChild = ref
	}

	// 等效单位
	equivalentUnitOnRef = ref => {
		this.equivalentUnitChild = ref
	}

	// 医嘱项别名
	doctorAdviceAliasOnRef = ref => {
		this.doctorAdviceAliasChild = ref
	}

	// 限制用药
	drugRestrictionOnRef = ref => {
		this.drugRestrictionChild = ref
	}

	// 接收子组件form表单中的值
	receiveSubcomponentsValue = (values, flag) => {
		if (flag === 'essentialInformation') { // 基本信息
			this.setState({ essentialInformationSubValue: values })
		} else if (flag === 'pharmaceuticalInformation') { // 药学相关信息
			this.setState({ pharmaceuticalInformationSubValue: values })
		} else if (flag === 'equivalentUnit') {
			this.setState({ equivalentUnitTableData: values })
		} else if (flag === 'doctorAdviceAlias') {
			this.setState({ doctorAdviceAliasTableData: values })
		} else if (flag === 'drugRestriction') {
			this.setState({ drugRestrictionTableData: values })
		}
	}

	// 保存  flag -- 保存方式（另存，保存，默认保存） isReset -- 是否重置数据 tableRecord - 行内编辑行数据
	handleSave = (flag = "save", isReset, tableRecord) => {
		// 调用子组件获取值的方法
		this.essentialInformationChild.handleValidateFields();
		this.pharmaceuticalInformationChild.handleValidateFields();
		this.equivalentUnitChild.handleValidateFields();
		this.doctorAdviceAliasChild.handleValidateFields();
		this.drugRestrictionChild.handleValidateFields();

		setTimeout(() => {
			let { essentialInformationSubValue, pharmaceuticalInformationSubValue, equivalentUnitTableData, doctorAdviceAliasTableData, drugRestrictionTableData, ChineseEnglishSize } = this.state;
			// console.log("tableRecord", tableRecord, pharmaceuticalInformationSubValue)
			/**
			* @ByShizi: 保存等效单位时如果等效单位为ml并且含量规格为空的话（含量规格 = 等效数量 + 等效单位）
			* 需求 #734
			* Create 2022-07-28
			*/
			if (tableRecord && tableRecord.doseUnitDesc && tableRecord.doseUnitDesc === 'ml' && !(pharmaceuticalInformationSubValue && pharmaceuticalInformationSubValue.medSpec)) {
				let medSpec = (tableRecord?.doseQty || '') + tableRecord.doseUnitDesc;
				this.pharmaceuticalInformationChild && this.pharmaceuticalInformationChild.setFieldsValue({ medSpec });
			}
			if (!(essentialInformationSubValue && essentialInformationSubValue.errors)) {
				message.info(ChineseEnglishSize.DrugMaintenanceimproveBasicInfoMeg ? ChineseEnglishSize.DrugMaintenanceimproveBasicInfoMeg.descripts : "请完善基本信息必填项")
				return;
			}
			if (!(pharmaceuticalInformationSubValue && pharmaceuticalInformationSubValue.medSpec)) {
				message.info(ChineseEnglishSize.DrugMaintenanceimproveDrugRelatedInfoMeg ? ChineseEnglishSize.DrugMaintenanceimproveDrugRelatedInfoMeg.descripts : "请完善药品相关必填项")
				return;
			}
			let obj = { ...essentialInformationSubValue, ...pharmaceuticalInformationSubValue };
			let data = {
				params: []
			}
			obj.medID = this.state.rowId ? (flag === 'save' ? this.state.rowId : '') : '';
			obj.doseUnit = flag === 'save' ? equivalentUnitTableData : equivalentUnitTableData && equivalentUnitTableData.map(item => {
				return {
					doseUnitDesc: item.doseUnitDesc,
					doseUnitID: item.doseUnitID,
					doseQty: item.doseQty,
					defaultQty: item.defaultQty,
				}
			});
			obj.medAlias = flag === 'save' ? doctorAdviceAliasTableData : doctorAdviceAliasTableData && doctorAdviceAliasTableData.map(item => {
				return {
					medAlias: item.medAlias,
				}
			});
			obj.medAut = flag === 'save' ? drugRestrictionTableData : drugRestrictionTableData && drugRestrictionTableData.map(item => {
				return {
					operTypeID: item.operTypeID, // 类型ID
					pointerID: item.pointerID, // 类型值ID
					operateID: item.operateID, // 操作ID
					levelID: item.levelID, // 管控级别ID
				}
			});
			data.params.push(obj);
			$http.post('urlADS', this, {
				code: "02020224",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						// 成功提示
						message.success(res.errorMessage);
						if (isReset === "reset") {
							this.handleNewlyAdded(true);
						} else {
							this.getMedDetailData();
						}
					} else {
						this.getMedDetailData();
					}
				},
				error: function () {
					this.getMedDetailData();
				}
			})
		}, 500)
	}

	render() {
		let { active, medDetailData, ChineseEnglishSize, scroll } = this.state;
		let isSaveAnother = this.props.isSaveAnother;
		return (
			<div className="dm-common-style">
				<div className="handle-save">
					<span onClick={() => this.handleNewlyAdded(true)} style={{ color: "#1999db" }}><Icon type="plus" />{ChineseEnglishSize.DrugMaintenanceadd ? ChineseEnglishSize.DrugMaintenanceadd.descripts : '新增'}</span>
					{isSaveAnother === "saveAnother" ? (
						<span onClick={() => this.handleSave('saveAs', "reset")} style={{ color: "#1890ff" }}><Icon type="nordered-list" />{ChineseEnglishSize.DrugMaintenancesaveAs ? ChineseEnglishSize.DrugMaintenancesaveAs.descripts : '另存'}</span>) : (
						<span onClick={() => this.handleSave('save', "reset")} style={{ color: "#1890ff" }}><Icon type="file" />{ChineseEnglishSize.DrugMaintenancesave ? ChineseEnglishSize.DrugMaintenancesave.descripts : '保存'}</span>
					)}

					{/* <span><Icon type="api" />最大码</span> */}
				</div>
				<div className="header-button">
					<Button onClick={() => this.handleToggleActive('all')} className={(scroll === 'all') ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenancecompleteInfo ? ChineseEnglishSize.DrugMaintenancecompleteInfo.descripts : '全部信息'}
					</Button>
					<Button onClick={() => this.handleToggleActive('1')} className={(scroll === '1') ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenancessentialInfo ? ChineseEnglishSize.DrugMaintenancessentialInfo.descripts : '基本信息'}
					</Button>
					<Button onClick={() => this.handleToggleActive('2')} className={(scroll === '2') ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenancepharmacyRelatedInfo ? ChineseEnglishSize.DrugMaintenancepharmacyRelatedInfo.descripts : '药学相关信息'}
					</Button>
					<Button onClick={() => this.handleToggleActive('3')} className={(scroll === '3') ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenanceequivalentUnit ? ChineseEnglishSize.DrugMaintenanceequivalentUnit.descripts : '等效单位'}
					</Button>
					<Button onClick={() => this.handleToggleActive('4')} className={(scroll === '4') ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenanceorderItemAlias ? ChineseEnglishSize.DrugMaintenanceorderItemAlias.descripts : '医嘱项别名'}
					</Button>
					<Button onClick={() => this.handleToggleActive('5')} className={(scroll === '5') ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenancedrugRestriction ? ChineseEnglishSize.DrugMaintenancedrugRestriction.descripts : '限制用药'}
					</Button>
				</div>
				<div style={{ height: store.getState().tableHeight.y + 122 + 'px', overflow: 'auto' }} id="advice-floor-box">
					<div style={{ display: (active === 'all' || active === '1') ? 'block ' : 'none' }}>
						<ADAEssentialInformation
							userInfo={medDetailData}
							onRef={this.essentialInformationOnRef}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							selectData={this.props.medicalOrderSelectData}
							ChineseEnglishSize={ChineseEnglishSize}
						/>
					</div>
					<div style={{ display: (active === 'all' || active === '2') ? 'block ' : 'none' }}>
						<ADAPharmaceuticalInformation
							userInfo={medDetailData}
							onRef={this.pharmaceuticalInformationOnRef}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							selectData={this.props.medicalOrderSelectData}
							ChineseEnglishSize={ChineseEnglishSize}
						/>
					</div>
					<div style={{ display: (active === 'all' || active === '3') ? 'block ' : 'none' }}>
						{/* 等效单位 */}
						<ADAEquivalentUnit
							onRef={this.equivalentUnitOnRef}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							selectData={this.props.medicalOrderSelectData}
							isSaveAnother={isSaveAnother}
							ChineseEnglishSize={ChineseEnglishSize}
							handleSave={this.handleSave}
						/>
					</div>
					<div style={{ display: (active === 'all' || active === '4') ? 'block ' : 'none' }}>
						{/* 医嘱项别名 */}
						<ADADoctorAdviceAlias
							onRef={this.doctorAdviceAliasOnRef}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							isSaveAnother={isSaveAnother}
							ChineseEnglishSize={ChineseEnglishSize}
							handleSave={this.handleSave}
						/>
					</div>
					<div style={{ display: (active === 'all' || active === '5') ? 'block ' : 'none' }}>
						{/* 限制用药 */}
						<ADADrugRestriction
							onRef={this.drugRestrictionOnRef}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							selectData={this.props.medicalOrderSelectData}
							isSaveAnother={isSaveAnother}
							ChineseEnglishSize={ChineseEnglishSize}
							handleSave={this.handleSave}
						/>
					</div>
				</div>
			</div>
		)
	}
};
export default AddDoctorAdvice;