// 医嘱项---等效单位
import React from 'react';
import { Form, Button, Input, Table, Card, Popconfirm, Select, Divider, message } from 'antd';
import { $http } from 'containers/config/https';
import { Util } from 'tools/index';

let { Option } = Select;

const EditableContext = React.createContext();

class EditableCell extends React.Component {
	getInput = () => {
		if (this.props.dataIndex === 'doseUnitDesc') {
			return <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '80%' }}>
				{this.props.option}
			</Select>;
		}
		return <Input style={{ width: '80%' }} type="number" className="input-number" />;
	};

	renderCell = ({ getFieldDecorator }) => {
		const {
			editing,
			dataIndex,
			title,
			record,
			option,
			index,
			children,
			...restProps
		} = this.props;
		return (
			<td {...restProps}>
				{editing ? (
					<Form.Item style={{ margin: 0 }}>
						{getFieldDecorator(dataIndex, {
							rules: [
								{
									required: (dataIndex === 'doseUnitDesc' || dataIndex === 'doseQty') ? true : false,
									message: `${title + (JSON.parse(window.sessionStorage.userData).language == 'EN' ? ' Can not be empty!' : '不能为空!')}`,
								},
							],
							initialValue: record[dataIndex],
						})(this.getInput())}
					</Form.Item>
				) : (
						children
					)}
			</td>
		);
	};

	render() {
		return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
	}
}

class ADAEquivalentUnit extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			dataSource: [],
			columns: [],
			editingKey: '',
			language: JSON.parse(window.sessionStorage.userData),
		}
	}

	componentDidMount() {
		this.props.onRef(this);
		this.getColumnsData();
	}

	// 根据下拉框描述找出对应的id
	fildID = (desc, data) => {
		if (!(data && data.length > 0)) {
			return;
		}
		for (var i = 0; i < data.length; i++) {
			if (data[i].descripts === desc) {
				return data[i].id
			}
		}
	}

	handleValidateFields = () => {
		let data = this.state.dataSource;
		for (var i = 0; i < data.length; i++) {
			data[i].doseUnitID = this.fildID(data[i].doseUnitDesc, this.props.selectData && this.props.selectData.unit);
		}
		this.props.receiveSubcomponentsValue(data, 'equivalentUnit')
	}

	// 获取表格数据
	getTableData = (tableData) => {
		let dataSource = JSON.parse(JSON.stringify(tableData));
		for (var i = 0; i < dataSource.length; i++) {
			dataSource[i].key = i + 1;
		}
		this.setState({ dataSource });
	}

	// 获取表头数据
	getColumnsData = () => {
		let ChineseEnglishSize = this.props.ChineseEnglishSize;
		let { language } = this.state;
		let columns = [
			{
				title: this.state.language.language == 'EN' ? 'Equivalent unit' : '等效单位',
				dataIndex: 'doseUnitDesc',
				editable: true,
				width: '150px',
				align: 'center'
			},
			{
				title: this.state.language.language == 'EN' ? 'Equivalent quantity' : '等效数量',
				dataIndex: 'doseQty',
				editable: true,
				width: '150px',
				align: 'center'
			},
			{
				title: this.state.language.language == 'EN' ? 'Default quantity' : '默认数量',
				dataIndex: 'defaultQty',
				editable: true,
				width: '150px',
				align: 'center'
			},
			{
				title: this.state.language.language == 'EN' ? 'operating' : '操作',
				dataIndex: 'operation',
				width: '130px',
				align: 'center',
				render: (text, record) => {
					const { editingKey } = this.state;
					const editable = this.isEditing(record);
					return editable ? (
						<span>
							<EditableContext.Consumer>
								{form => (
									<span
										className="span"
										onClick={() => this.handleSave(form, record.key)}
									>
										{language.language == 'EN' ? 'save' : '保存'}
									</span>
								)}
							</EditableContext.Consumer>
							<Divider type="vertical" />
							<Popconfirm title={language.language == 'EN' ? 'Do you cancel editing?' : "是否取消编辑?"} okText={language.language == 'EN' ? "Yes" : '是'} cancelText={language.language == 'EN' ? "No" : '否'} onConfirm={() => this.handleCancel(record)}>
								<span className="span" style={{ color: 'rgba(240,65,52,1)' }}> {language.language == 'EN' ? 'cancel' : '取消'}</span>
							</Popconfirm>
						</span>
					) : (
							<span>
								<a className="span" disabled={editingKey !== ''} onClick={() => this.handleEdit(record.key)}>
									{language.language == 'EN' ? 'edit' : '编辑'}
								</a>
								<Divider type="vertical" />
								<Popconfirm title={language.language == 'EN' ? 'Delete is not recoverable, are you sure you want to delete it?' : "删除不可恢复，你确定要删除吗?"} okText={language.language == 'EN' ? "Yes" : '是'} cancelText={language.language == 'EN' ? "No" : '否'} onConfirm={() => this.handleDelete(record)}>
									<span className="span" style={{ color: 'rgba(240,65,52,1)' }}> {language.language == 'EN' ? 'delete' : '删除'}</span>
								</Popconfirm>
							</span>
						);
				},
			},
		];
		this.setState({ columns })
	}

	isEditing = record => record.key === this.state.editingKey;

	// 取消
	handleCancel = (record) => {
		let status = Util.checkAttributeIsEmpty(this.props.form.getFieldsValue());
		if (status) {
			// 都为空则删除该条记录
			this.setState({ editingKey: '' }, () => {
				this.handleDelete(record);
			})
		} else {
			this.setState({ editingKey: '' })
		}
	};

	// 保存
	handleSave = (form, key) => {
		form.validateFields((error, row) => {
			if (error) {
				return;
			}
			const newData = JSON.parse(JSON.stringify(this.state.dataSource));
			const index = newData.findIndex(item => key === item.key);
			if (index > -1) {
				const item = newData[index];
				newData.splice(index, 1, {
					...item,
					...row,
				});
				this.setState({ dataSource: newData, editingKey: '' }, () => {
					this.props && this.props.handleSave && this.props.handleSave('save', '', row);
				});
			} else {
				newData.push(row);
				this.setState({ dataSource: newData, editingKey: '' }, () => {
					this.props && this.props.handleSave && this.props.handleSave('save', '', row);
				});
			}
		});
	}

	// 编辑
	handleEdit = (key) => {
		this.setState({ editingKey: key });
	}

	// 本地删除数据
	deleteRow(key) {
		const dataSource = JSON.parse(JSON.stringify(this.state.dataSource));
		this.setState({ dataSource: dataSource.filter(item => item.key !== key) });
	}

	// 删除
	handleDelete = (record) => {
		let isSaveAnother = this.props.isSaveAnother;
		if (record.doseID && isSaveAnother !== "saveAnother") {
			let data = {
				params: [
					{
						doseID: record.doseID,
					}
				]
			}
			$http.post('urlS', this, {
				code: "02020227",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						message.success(res.errorMessage);
						this.deleteRow(record.key);
					}
				}
			})
		} else {
			this.deleteRow(record.key)
		}
	}

	// 新增表格数据
	handleAddTableData = () => {
		const { dataSource } = this.state;
		let leg = dataSource && dataSource.length ? dataSource.length + 1 : 1;
		let arr = [];
		const newData = {
			key: leg,
			doseUnitDesc: '',
			doseQty: '',
			defaultQty: '',
		};
		arr.push(newData)
		this.setState({
			dataSource: dataSource && dataSource.length > 0 ? [...dataSource, newData] : arr
		}, () => {
			if (!this.state.editingKey) {
				this.setState({ editingKey: leg })
			}
		});
	}

	// 重置数据
	resetFields = () => {
		this.setState({ dataSource: [], editingKey: '' })
	}

	resetFieldsEditingKey = () => {
		this.setState({ editingKey: '' })
	}

	handleOnRow = (record) => {
		return {
			onDoubleClick: () => {
				this.props.form.resetFields();
				this.setState({ editingKey: record.key });
			}
		}
	}

	render() {
		let { dataSource, columns } = this.state;
		let selectData = this.props.selectData;
		let ChineseEnglishSize = this.props.ChineseEnglishSize;
		// 等效单位
		let doseUnitDescOption = selectData && selectData.unit && selectData.unit.map((item, index) => {
			return (<Option key={index} value={item.descripts} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
		})
		const components = {
			body: {
				cell: EditableCell,
			},
		};
		const filterColumns = columns.map(col => {
			if (!col.editable) {
				return col;
			}
			return {
				...col,
				onCell: record => ({
					record,
					dataIndex: col.dataIndex,
					option: doseUnitDescOption,
					title: col.title,
					editing: this.isEditing(record),
				}),
			};
		});

		return (
			<Card
				type="inner"
				title={<div style={{ position: 'relative' }}>
					{ChineseEnglishSize.DrugMaintenanceequivalentUnit ? ChineseEnglishSize.DrugMaintenanceequivalentUnit.descripts : '等效单位'}
					<span style={{ position: 'absolute', top: '-6px', right: '4px' }}><Button onClick={this.handleAddTableData}>{ChineseEnglishSize.DrugMaintenanceadd ? ChineseEnglishSize.DrugMaintenanceadd.descripts : '新增'}</Button></span>
				</div>}
				size="small"
			>
				<div style={{ padding: '8px 15px' }}>
					{/* <div style={{textAlign: 'right', margin: '8px 0'}}>
                        <Button onClick={this.handleAddTableData}>新增</Button>
                    </div> */}
					<EditableContext.Provider value={this.props.form}>
						<Table
							style={{ minHeight: '220px' }}
							components={components}
							bordered
							dataSource={dataSource}
							columns={filterColumns}
							rowClassName="editable-row"
							pagination={{
								onChange: this.handleCancel,
							}}
							onRow={this.handleOnRow}
						/>
					</EditableContext.Provider>
				</div>
			</Card>
		)
	}
};
let ADAEquivalentUnitForm = Form.create()(ADAEquivalentUnit);
export default ADAEquivalentUnitForm;