// 药品消耗统计
import React from 'react';
import { Card, Form, DatePicker, TimePicker, Select, Row, Col, Button, Input, message } from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import { handleExcel } from 'tools/handleExcel.js';
import PubilcTablePagination from 'pages/common/PubilcTablePagination';
import PublicModalTable from 'pages/common/PublicModalTable';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import 'assets/css/common.css';

class DrugConsumptionStatistics extends React.Component {
	constructor() {
		super();
		this.state = {
			basicHeight: 0,
			parameterSetting: {}, // 界面默认数据
			searchOrdLocData: [], // 开单科室下拉框数据
			typeSelectData: [], // 类型下拉框数据
			columns: [],
			page: 1,
			pageSize: 20,
			total: 0,
			widthTotal: 0, // table总宽度
			modalData: [], // 弹框列表数据
			rowId: '', // 弹框列表选中行ID
			top: 0,
			left: 0,
			ModalRowData: {}, // 弹框双击选中行数据
			loading: false
		};
		this.modalColumns = [
			{
				key: 1,
				title: '库存项代码',
				dataIndex: 'stockCode',
				align: "center",
				width: '22%'
			},
			{
				key: 2,
				title: '库存项描述',
				dataIndex: 'stockDesc',
				align: "center",
				width: '24%',
			},
			{
				key: 5,
				title: '库存分类',
				dataIndex: 'stkSubCatDesc',
				align: "center",
				width: '16%',
			},
			{
				key: 3,
				title: '包装规格',
				dataIndex: 'stockSpec',
				align: "center",
				width: '12%',
			},
			{
				key: 6,
				title: '基本单位',
				dataIndex: 'baseUnitDesc',
				align: "center",
				width: '12%',
			},
			{
				key: 7,
				title: '入库单位',
				dataIndex: 'purUnitDesc',
				align: "center",
			}
		];
	}

	componentDidMount() {
		this.getParameterSetting();
		this.getMainTableColumns();
		// 关闭loading
		this.child.handleLoading();
		this.setState({ basicHeight: document.getElementById("drug-consumotion-statistics-basic").clientHeight })
	}

	onRef = (ref) => {
		this.child = ref
	}

	// 获取默认参数配置
	getParameterSetting = () => {
		let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02050009",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						parameterSetting: res.result[0] ? res.result[0] : {}
					})
				}
			}
		})
	}

	// 3.2.1.9.2.获取管制药品统计界面类型下来数据集
	getTypeSelectData = () => {
		if (this.state.typeSelectData && this.state.typeSelectData.length > 0) {
			return;
		}
		let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02050002",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ typeSelectData: res.result })
				}
			}
		})
	}

	// 3.2.1.12.3.根据别名获取库存项
	handleStockAliasSearch = (value) => {
		if (timeout) {
			clearTimeout(timeout);
			timeout = null;
		}
		timeout = setTimeout(() => {
			if (value) {
				let data = {
					params: [{
						stockAlias: value
					}]
				}
				$http.post('urlS', this, {
					code: "02030007",
					data: data,
					success: function (res) {
						if (+res.errorCode === 0) {
							this.setState({ searchOrdLocData: res.result })
						}
					}
				})
			}
		}, 300)
	}

	// 获取主列表columns
	getMainTableColumns = () => {
		let data = {
			params: [{
				compontName: "DrugConSumList", // 病人登记号/证件号
				type: 'C', // 卡类型id
			}]
		}
		$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.mainColumnRef.onOpenModel()}>{item.title}</div>
						}
					}) : '';
					let filterArr = arr.filter(function (item) { return item.display === 'Y' });
					this.setState({ columns: filterArr, widthTotal: res.totalWidth })
				}
			}
		})
	}

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

	// 请求列表数据
	getTableData() {
		this.setState({ loading: true });
		const { form: { validateFields } } = this.props;
		validateFields((errors, values) => {
			if (errors === null) {
				let { page, pageSize } = this.state;
				let EndDate = Moment(values.endDate).format('YYYY-MM-DD HH:mm:ss');
				let StartDate = Moment(values.startDate).format('YYYY-MM-DD HH:mm:ss');
				let startDate = StartDate.split(" ")[0];
				let endDate = EndDate.split(" ")[0];
				let endTime = EndDate.split(" ")[1];
				let startTime = StartDate.split(" ")[1];
				let data = {
					params: [{
						startDate: startDate ? startDate : Moment(), // 开始日期
						endDate: endDate ? endDate : '', // 截止日期
						endTime: endTime, // 开始日期
						startTime: startTime, // 截止日期
						phaTypeID: values.phaTypeID, // 类型ID
						stockID: this.state.ModalRowData && this.state.ModalRowData.stockID ? this.state.ModalRowData.stockID : '', // 科室
					}],
					pagination: [{
						pageSize: pageSize,
						currentPage: page,
						sortColumn: "Describe",
						sortOrder: "asc"
					}]
				}
				$http.post('urlS', this, {
					code: "02050010",
					data: data,
					success: function (res) {
						if (+res.errorCode === 0 && res.result) {
							let arr = res.result[0].rows ? res.result[0].rows : [];
							for (var i = 0; i < arr.length; i++) {
								arr[i].key = i + 1
							}
							this.setState({ tableData: arr, total: res.result[0].total, loading: false }, () => {
								// 数据加载成功关闭loading
								this.child.handleLoading()
							})
						} else {
							this.setState({ tableData: [], total: 0, loading: false }, () => {
								// 数据加载成功关闭loading
								this.child.handleLoading();
							})
						}
					},
					error: function () {
						this.setState({ tableData: [], total: 0, loading: false }, () => {
							// 数据加载成功关闭loading
							this.child.handleLoading();
						})
					}
				})
			}
		})

	}

	// 查询
	handleQuery = () => {
		this.setState({ page: 1 }, () => {
			this.getTableData()
		})
	}
	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			this.getTableData();
		})
	}

	// 导出
	exportTableData = () => {
		let { tableData, columns } = this.state;
		if (!(tableData && tableData.length > 0)) {
			message.info("统计列表有数据时才支持导出功能");
			return;
		}
		const { form: { validateFields } } = this.props;
		validateFields((errors, values) => {
			if (errors === null) {
				let EndDate = Moment(values.endDate).format('YYYY-MM-DD HH:mm:ss');
				let StartDate = Moment(values.startDate).format('YYYY-MM-DD HH:mm:ss');
				let startDate = StartDate.split(" ")[0];
				let endDate = EndDate.split(" ")[0];
				let endTime = EndDate.split(" ")[1];
				let startTime = StartDate.split(" ")[1];
				let data = {
					params: [{
						startDate: startDate ? startDate : Moment(), // 开始日期
						endDate: endDate ? endDate : '', // 截止日期
						endTime: endTime, // 开始日期
						startTime: startTime, // 截止日期
						phaTypeID: values.phaTypeID, // 类型ID
						stockID: this.state.ModalRowData && this.state.ModalRowData.stockID ? this.state.ModalRowData.stockID : '', // 科室
					}],
					pagination: [{
						pageSize: 10000,
						currentPage: 1,
						sortColumn: "Describe",
						sortOrder: "asc"
					}]
				}
				$http.post('urlS', this, {
					code: "02050010",
					data: data,
					success: function (res) {
						if (+res.errorCode === 0 && res.result) {
							let arr = res.result[0].rows ? res.result[0].rows : [];
							handleExcel.exportExcel(columns, arr, '药品消耗统计');
						}
					}
				})
			}
		})
	}

	// 清屏
	resetFields = () => {
		this.props.form.resetFields();
		this.setState({ ModalRowData: {}, tableData: [], total: 0 })
	}

	onModalRef = (ref) => {
		this.modalChild = ref;
	}

	// 获取描述列表数据
	getModalListData(alias) {
		let data = {
			params: [
				{
					stockAlias: alias, // 库存项描述别名
				}
			]
		}
		$http.post('urlS', this, {
			code: "02020042",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					for (var i = 0; i < res.result.length; i++) {
						res.result[i].key = i + 1
					}
					this.setState({ modalData: res.result, rowId: res.result[0].key })
				} else {
					this.setState({ modalData: [] })
				}
			}
		})
	}

	// 描述回车事件
	stockDescOnPressEnter = (e) => {
		let top = document.getElementById('stock-desc').getBoundingClientRect().top + 40 + 'px';
		let left = document.getElementById('stock-desc').getBoundingClientRect().left + 85 + 'px';
		this.setState({
			top: top,
			left: left
		});
		this.getModalListData(e.target.value);
		this.modalChild.showModal();
	}

	// 当描述失去焦点的时候
	stastockDescOnBlure = (e) => {
		if (this.state.ModalRowData && (e.target.value !== this.state.ModalRowData.stockDesc)) {
			this.props.form.setFieldsValue({ stockDesc: undefined });
			this.setState({ ModalRowData: {} })
		}
	}

	// 操作弹框
	onClickRowPublic = (record) => {
		return {
			// 单击行选中
			onClick: () => {
				if (this.state.rowId === '') {
					// 保存行数据以及ID
					this.setState({ rowId: record.key })
				} else {
					if (this.state.rowId !== record.key) {
						this.setState({ rowId: record.key })
					}
				}
			},
			onDoubleClick: () => {
				this.confirmSelection(record);
			}
		}
	}

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

	// 双击选中行数据的回调
	confirmSelection = (record) => {
		this.setState({ ModalRowData: record }, () => {
			// 关闭弹窗
			this.modalChild.handleCancel();
			this.props.form.setFieldsValue({ stockDesc: record.stockDesc });
		})
	}

	handleOnKeydown = (e) => {
		var e = window.event || e;
		let id = '';
		let oneArr = this.state.modalData && this.state.modalData.length > 0 ? this.state.modalData : [];
		switch (e.keyCode) {
			case 13:
				if (this.state.rowId) {
					let obj = {}
					for (var i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.rowId) {
							obj = i > 0 ? oneArr[i] : oneArr[0];
							break;
						}
					}
					this.confirmSelection(obj);
				} else {
					message.info("请选择一条需要操作的数据")
				}
				break;
			case 38: //上
				if (this.state.rowId) {
					for (var i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.rowId) {
							id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
							break;
						}
					}
					this.setState({ rowId: id })
				} else {
					this.setState({ rowId: oneArr[0].key })
				}
				break;
			case 40: //下
				if (this.state.rowId) {
					for (let i = 0; i < oneArr.length; i++) {
						if (oneArr[i].key === this.state.rowId) {
							id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
							break;
						}
					}
					this.setState({ rowId: id })
				} else {
					this.setState({ rowId: oneArr[0].key })
				}
				break;
		}
	};

	render() {
		let { parameterSetting, typeSelectData, basicHeight, columns, tableData, total, page, widthTotal, loading } = this.state;
		const { getFieldDecorator } = this.props.form;
		const formItemInput = {
			labelCol: { span: 9 },
			wrapperCol: { span: 15 }
		};
		// 组件所需参数
		const param = {
			// 表头配置
			columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			total,
			// 当前页数
			page,
			// 表格的宽度
			x: widthTotal,
			y: store.getState().tableHeight.y + 202 - 123 - basicHeight,
			height: store.getState().tableHeight.y + 202 - 77 - basicHeight + 'px',
			loading,
			pageSize: "20"
		}
		let modalParam = {
			width: '600px',
			top: this.state.top,
			left: this.state.left,
			columns: this.modalColumns,
			data: this.state.modalData,
			isOnRow: true,
			TableClassName: 'tab-placeholder',
			rowClassName: true
		}

		// 类型
		let typeOption = typeSelectData && typeSelectData.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
		})
		return (
			<div>
				<Card
					size="small"
					title={<div className="card-title-left-icon"><div></div>基本操作</div>}
					id="drug-consumotion-statistics-basic"
				>
					<Form>
						<Row style={{ marginTop: '12px' }}>
							<Col span={4}>
								<Form.Item label="开始日期" {...formItemInput}>
									{getFieldDecorator('startDate', {
										initialValue: parameterSetting.startDate ? Moment(parameterSetting.startDate + parameterSetting.startTime, 'YYYY-MM-DD HH:mm:ss') : Moment(),
									})(
										<DatePicker style={{ width: '100%' }} showTime format="YYYY-MM-DD HH:mm:ss" />
									)}
								</Form.Item>
							</Col>
							<Col span={4}>
								<Form.Item label="截止日期" {...formItemInput}>
									{getFieldDecorator('endDate', {
										initialValue: parameterSetting.endDate ? Moment(parameterSetting.endDate + parameterSetting.endTime, 'YYYY-MM-DD HH:mm:ss') : Moment(),
									})(
										<DatePicker style={{ width: '100%' }} showTime format="YYYY-MM-DD HH:mm:ss" />
									)}
								</Form.Item>
							</Col>
							<Col span={3}>
								<Form.Item label="类型" {...formItemInput}>
									{getFieldDecorator('phaTypeID', {
										initialValue: undefined,
									})(
										<Select
											showSearch optionFilterProp="seatchprop"
											allowClear
											placeholder="请选择"
											onFocus={this.getTypeSelectData}
											style={{ width: '100%' }}
										>
											{typeOption}
										</Select>
									)}
								</Form.Item>
							</Col>
							<Col span={4} id="stock-desc">
								<Form.Item label="药品名称" {...formItemInput}>
									{getFieldDecorator('stockDesc', {
										initialValue: undefined,
									})(
										<Input
											ref={this.myRef1}
											placeholder="回车检索药品相关信息"
											onPressEnter={this.stockDescOnPressEnter}
											onBlur={this.stastockDescOnBlure}
											style={{ width: '100%' }}
											allowClear
											title={this.state.ModalRowData && this.state.ModalRowData.stockDesc ? this.state.ModalRowData.stockDesc : '回车检索药品相关信息'}
										/>
									)}
								</Form.Item>
							</Col>
							<Col span={6} style={{ marginTop: '4px', }}>
								<Button type="primary" onClick={this.handleQuery} style={{ marginLeft: '150px' }}>查询</Button>

								<Button
									onClick={this.exportTableData}
									type="primary"
									style={{ margin: '0 46px' }}
								>导出</Button>
								<Button
									type="danger"
									ghost
									onClick={this.resetFields}
								>清屏</Button>
								{/* <Button
									type="dashed"
									style={{ margin: '0 15px' }}
								>打印</Button> */}

							</Col>
						</Row>
					</Form>
				</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>统计列表</div>}
				>
					<div style={{ height: store.getState().tableHeight.y + 202 - 30 - basicHeight + 'px', overflow: 'auto' }}>
						<PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
					</div>
				</Card>
				<div
					tabIndex={1}
					onKeyDown={this.handleOnKeydown}
					style={{ outline: 'none' }}
				>
					<PublicModalTable
						onClickRowPublic={this.onClickRowPublic}
						setRowClassNamePublic={this.setRowClassNamePublic}
						param={modalParam}
						onRef={this.onModalRef}
					/>
				</div>
				<ColumnAuthoritysModel
					clientWidth='800px'
					compontName='DrugConSumList'
					configType="C"
					onRef={this.onMainColumnRef}
					reloadData={this.getMainTableColumns}
				/>
			</div>
		)
	}
};
const DrugConsumptionStatisticsForm = Form.create()(DrugConsumptionStatistics);
export default DrugConsumptionStatisticsForm;