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

import AIIEssentialInformation from './component/AIIEssentialInformation.jsx'; // 基本信息
import AIITollItem from './component/AIITollItem.jsx'; // 收费项
import AIIStorageCondition from './component/AIIStorageCondition.jsx'; // 存储条件
import AIIInventoryItemAlias from './component/AIIInventoryItemAlias.jsx'; // 库存项别名
import AIIUnitMaintenance from './component/AIIUnitMaintenance.jsx'; // 发药单位维护

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

class AddInventoryItem extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			active: 'all',
			scroll: "all",
			inventoryDetailData: [], // 库存项明细数据
			essentialInformationSubValue: {},
			tollItemSubValue: {},
			storageConditionSubValue: {},
			inventoryItemAliasTableData: [],
			unitMaintenanceTableData: [],
			ChineseEnglishSize: {},
		}
	}

	componentDidMount() {
		this.props.onRef(this);
		document.getElementById("inventory-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 }, () => {
		// 		this.getInventoryDetailData();
		// 	})
		// }
		this.setState({ rowId: newData.rowId }, () => {
			this.getInventoryDetailData();
		})
	}

	componentWillUnmount() {
		document.getElementById("inventory-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 < 200) {
			this.setState({ scroll: '1' })
		} else if (event.target.scrollTop > 200 && event.target.scrollTop < 360) {
			this.setState({ scroll: '2' })
		} else if (event.target.scrollTop > 360 && event.target.scrollTop < 515) {
			this.setState({ scroll: '3' })
		} else if (event.target.scrollTop > 515) {
			this.setState({ scroll: '4' })
		}
	}

	getInventoryDetailData = () => {
		if (!(this.state.rowId)) {
			return;
		}
		this.essentialInformationChild.resetFields();
		this.tollItemChild.resetFields();
		this.storageConditionChild.resetFields();
		var data = {
			params: [{
				stockID: this.state.rowId
			}],
		}
		$http.post('url', this, {
			code: "02020234",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					let inventoryDetailData = res.result;
					if (this.props&&this.props.isSaveAnother=== "saveAnother"){
						inventoryDetailData.medID=""
						inventoryDetailData.medDesc=""
						inventoryDetailData.itemDesc=""
						inventoryDetailData.itemCode=""
					}
					let stockAliasTableData = inventoryDetailData && inventoryDetailData.stockAlias && inventoryDetailData.stockAlias.rows ? inventoryDetailData.stockAlias.rows : [];
					let dispUomTableData = inventoryDetailData && inventoryDetailData.dispUom && inventoryDetailData.dispUom.rows ? inventoryDetailData.dispUom.rows : [];
					this.inventoryItemAliasChild.getTableData(stockAliasTableData);
					this.unitMaintenanceChild.getTableData(dispUomTableData);
					this.setState({ inventoryDetailData })
				}
			}
		});
	}

	// 切换医嘱项页签
	handleToggleActive = key => {
		this.setState({ active: key, scroll: key }, () => {
			if (this.state.active === "all") {
				document.getElementById("inventory-floor-box").scrollTop = 0
			}
		})
	}

	resetFields = () => {
		this.essentialInformationChild.resetFields();
		this.tollItemChild.resetFields();
		this.storageConditionChild.resetFields();
		this.inventoryItemAliasChild.resetFields();
		this.unitMaintenanceChild.resetFields();
	}

	// 重置编辑状态
	resetFieldsEditingKey = () => {
		this.inventoryItemAliasChild.resetFieldsEditingKey();
		this.unitMaintenanceChild.resetFieldsEditingKey();
	}

	// 新增
	handleNewlyAdded = (isQuery) => {
		this.setState({ active: 'all', inventoryDetailData: {} }, () => {
			this.resetFields();
			isQuery ? this.props.handleQuery() : "";
		})
	}

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

	// 收费项
	tollItemOnRef = ref => {
		this.tollItemChild = ref;
	}

	// 存储条件
	storageConditionOnRef = ref => {
		this.storageConditionChild = ref;
	}

	// 库存项别名
	inventoryItemAliasOnRef = ref => {
		this.inventoryItemAliasChild = ref;
	}

	// 发药单位维护
	unitMaintenanceOnRef = ref => {
		this.unitMaintenanceChild = ref;
	}

	// 接收子组件form表单中的值
	receiveSubcomponentsValue = (values, flag) => {
		if (flag === 'essentialInformation') {
			this.setState({ essentialInformationSubValue: values })
		} else if (flag === 'tollItem') {
			this.setState({ tollItemSubValue: values })
		} else if (flag === 'storageCondition') {
			this.setState({ storageConditionSubValue: values })
		} else if (flag === 'inventoryItemAlias') {
			this.setState({ inventoryItemAliasTableData: values })
		} else if (flag === 'unitMaintenance') {
			this.setState({ unitMaintenanceTableData: values })
		}
	}

	// 保存 flag -- 保存方式（另存，保存，默认保存） isReset -- 是否重置数据
	handleSave = (flag = "save", isReset) => {
		let { ChineseEnglishSize } = this.state;
		// 调用子组件获取值的方法
		this.essentialInformationChild.handleValidateFields();
		this.tollItemChild.handleValidateFields();
		this.storageConditionChild.handleValidateFields();
		this.inventoryItemAliasChild.handleValidateFields();
		this.unitMaintenanceChild.handleValidateFields();

		setTimeout(() => {
			let { essentialInformationSubValue, tollItemSubValue, storageConditionSubValue, inventoryItemAliasTableData, unitMaintenanceTableData } = this.state;
			// console.log("tollItemSubValue", essentialInformationSubValue, "tollItemSubValue",tollItemSubValue)
			if (!(essentialInformationSubValue && essentialInformationSubValue.errors)) {
				message.info(ChineseEnglishSize.DrugMaintenanceimproveBasicInfoMeg ? ChineseEnglishSize.DrugMaintenanceimproveBasicInfoMeg.descripts : "请完善基本信息必填项")
				return;
			}
			if (!(tollItemSubValue && tollItemSubValue.errors)) {
				message.info(ChineseEnglishSize.DrugMaintenanceimproveChargingInfoMeg ? ChineseEnglishSize.DrugMaintenanceimproveChargingInfoMeg.descripts : "请完善收费项必填项")
				return;
			}
			let obj = { ...essentialInformationSubValue, ...tollItemSubValue, ...storageConditionSubValue };
			let data = {
				params: []
			}
			obj.stockID = this.state.rowId ? (flag === 'save' ? this.state.rowId : '') : '';
			obj.dispUom = flag === 'save' ? unitMaintenanceTableData : unitMaintenanceTableData && unitMaintenanceTableData.map(item => {
				return {
					dispLocID: item.dispLocID,
					dispUnitID: item.dispUnitID,
					factor: item.factor,
				}
			});
			obj.stockAlias = flag === 'save' ? inventoryItemAliasTableData : inventoryItemAliasTableData && inventoryItemAliasTableData.map(item => {
				return {
					stockAlias: item.stockAlias,
				}
			});
			data.params.push(obj);
			$http.post('urlADS', this, {
				code: "02020235",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						// 成功提示
						message.success(res.errorMessage);
						if (flag === "saveAs") {
							this.props.handleQuery();
						} else {
							this.getInventoryDetailData();
						}
						if (isReset === "reset") {
							this.handleNewlyAdded(true);
						}
					} else {
						this.getInventoryDetailData();
					}
				},
				error: function () {
					this.getInventoryDetailData();
				}
			})
		}, 500)
	}

	render() {
		let { active, inventoryDetailData, 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')} style={{ color: "#1890ff" }}><Icon type="nordered-list" /> {ChineseEnglishSize.DrugMaintenancesaveAs ? ChineseEnglishSize.DrugMaintenancesaveAs.descripts : '另存'}</span>) : (
							<span onClick={() => this.handleSave('save')} 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.DrugMaintenancetollItem ? ChineseEnglishSize.DrugMaintenancetollItem.descripts : '收费项'}
					</Button>
					<Button onClick={() => this.handleToggleActive('3')} className={scroll === '3' ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenancestorageCondition ? ChineseEnglishSize.DrugMaintenancestorageCondition.descripts : '存储条件'}
					</Button>
					<Button onClick={() => this.handleToggleActive('4')} className={scroll === '4' ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenanceinventoryItemAlias ? ChineseEnglishSize.DrugMaintenanceinventoryItemAlias.descripts : '库存项别名'}
					</Button>
					<Button onClick={() => this.handleToggleActive('5')} className={scroll === '5' ? 'active' : ''}>
						{ChineseEnglishSize.DrugMaintenancedrugDeliveryUnitMaintenance ? ChineseEnglishSize.DrugMaintenancedrugDeliveryUnitMaintenance.descripts : '发药单位维护'}
					</Button>
				</div>
				<div style={{ height: store.getState().tableHeight.y + 122 + 'px', overflow: 'auto' }} id="inventory-floor-box">
					<div style={{ display: (active === 'all' || active === '1') ? 'block ' : 'none' }}>
						<AIIEssentialInformation
							userInfo={inventoryDetailData}
							onRef={this.essentialInformationOnRef}
							selectData={this.props.inventoryItemSelectData}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							ChineseEnglishSize={ChineseEnglishSize}
						/>
					</div>
					<div style={{ display: (active === 'all' || active === '2') ? 'block ' : 'none' }}>
						<AIITollItem
							userInfo={inventoryDetailData}
							onRef={this.tollItemOnRef}
							selectData={this.props.inventoryItemSelectData}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							ChineseEnglishSize={ChineseEnglishSize}
						/>
					</div>
					<div style={{ display: (active === 'all' || active === '3') ? 'block ' : 'none' }}>
						<AIIStorageCondition
							userInfo={inventoryDetailData}
							onRef={this.storageConditionOnRef}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							ChineseEnglishSize={ChineseEnglishSize}
						/>
					</div>
					<div style={{ display: (active === 'all' || active === '4') ? 'block ' : 'none' }}>
						{/* 库存项别名 */}
						<AIIInventoryItemAlias
							onRef={this.inventoryItemAliasOnRef}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							isSaveAnother={isSaveAnother}
							ChineseEnglishSize={ChineseEnglishSize}
							handleSave={this.handleSave}
						/>
					</div>
					<div style={{ display: (active === 'all' || active === '5') ? 'block ' : 'none' }}>
						{/* 发药单位维护 */}
						<AIIUnitMaintenance
							onRef={this.unitMaintenanceOnRef}
							selectData={this.props.inventoryItemSelectData}
							receiveSubcomponentsValue={this.receiveSubcomponentsValue}
							isSaveAnother={isSaveAnother}
							ChineseEnglishSize={ChineseEnglishSize}
							handleSave={this.handleSave}
						/>
					</div>
				</div>
			</div>
		)
	}
};
export default AddInventoryItem;
