// 库存转移明细录入列表
import React from 'react';
import { Card, Row, Col, Form, Icon, Table, message, Popconfirm } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from 'containers/config/https';
import store from 'store';
import InventoryFormModal from './../../../common/InventoryFormModal';
import { Resizable } from 'react-resizable';
import DocumentDeliveryModal from './DocumentDeliveryModal';

const ResizeableTitle = props => {
	const { onResize, width, ...restProps } = props;

	if (!width) {
		return <th {...restProps} />;
	}

	return (
		<Resizable
			width={width}
			height={0}
			onResize={onResize}
			draggableOpts={{ enableUserSelectHack: false }}
		>
			<th {...restProps} />
		</Resizable>
	);
};

const ShiftDetailList = Form.create()(
	class extends React.Component {
		constructor() {
			super();
			this.state = {
				unitData: [], // 单位下拉框数据
				modalData: [], // 弹框列表数据
				data: [], // 列表数据
				detailInfo: [], // 入库制单回显至明细列表数据
				tacitlyApproveData: {}, // 初始化数据
				stockID: '', // 回显的描述id
				frLocID: '',
				toLocDr: '',
				stkCatID: '',
				pageSize: 10,
				page: 1,
				inputData: '',
				getBatchDetail: {},
				unitDesc: '',
				unitDate: [],
				columns: [],
				detailWidthTotal: '',
				show: false, //收缩图标
				rpTotal: 0, //进价金额总和
				spTotal: 0, //售价金额总和
				ChineseEnglishSize: {}, //中英翻译
				language: JSON.parse(window.sessionStorage.userData),
			};
			this.columns = [
				{
					key: 1,
					title: '药品名称',
					dataIndex: 'stockDesc',
					align: "center",
					width: '200px'
				},
				{
					key: 2,
					title: '批次/效期',
					dataIndex: 'batExp',
					align: "center",
					width: '100px',
				},
				{
					key: 5,
					title: '转移数量',
					dataIndex: 'qty',
					align: "center",
					width: '100px',
				},
				{
					key: 11,
					title: '转移单位',
					dataIndex: 'unitDesc',
					align: "center",
					width: '200px',
				},
				{
					key: 3,
					title: '生产厂家',
					dataIndex: 'manfDesc',
					align: "center",
					width: '200px',
				},
				{
					key: 6,
					title: '进价',
					dataIndex: 'rp',
					align: "center",
					width: '100px',
				},
				{
					key: 7,
					title: '售价',
					dataIndex: 'sp',
					align: "center",
					width: '100px',
				},
				{
					key: 8,
					title: '可用数量',
					dataIndex: 'avaQtyUom',
					align: "center",
					width: '100px',
				},
				{
					key: 10,
					title: '请求数量',
					dataIndex: 'avaQty2',
					align: "center",
					width: '100px',
				},

				{
					key: 12,
					title: '货位码',
					dataIndex: 'preDate',
					align: "center",
					width: '200px',
				},
				{
					key: 13,
					title: '占用数量',
					dataIndex: 'dirQty',
					align: "center",
					width: '100px',
				},
				{
					key: 14,
					title: '本次占用数量',
					dataIndex: 'preDate2',
					align: "center",
					width: '100px',
				},
				{
					key: 15,
					title: '请求方库存',
					dataIndex: 'toLocQty',
					align: "center",
					width: '100px',
				},
				{
					key: 16,
					title: '批号库存',
					dataIndex: 'batQty',
					align: "center",
					width: '100px',
				},
				{
					key: 17,
					title: '规格',
					dataIndex: 'spec',
					align: "center",
					width: '100px',
				},
				{
					key: 18,
					title: '处方通用名',
					dataIndex: 'GenericName',
					align: "center",
					width: '200px',
				},
				{
					key: 19,
					title: '剂型',
					dataIndex: 'preDate',
					align: "center",
					width: '100px',
				}, {
					title: '操作',
					key: 20,
					fixed: 'right',
					align: "center",
					width: '100px',
					render: (text, record) => (
						<span>
							<Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(record, e)} onClick={this.handlePopconfirm} >
								<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
							</Popconfirm>
						</span>
					),
				}
			];

			this.myRef1 = React.createRef();
			this.myRef2 = React.createRef();
			this.myRef3 = React.createRef();
			this.myRef4 = React.createRef();
			this.myRef5 = React.createRef();
			this.myRef6 = React.createRef();
			this.myRef7 = React.createRef();
			this.myRef8 = React.createRef();
			this.myRef9 = React.createRef();
			this.myRef10 = React.createRef();
			this.myRef11 = React.createRef();
			this.myRef12 = React.createRef();
			this.myRef13 = React.createRef();
			this.myRef14 = React.createRef();
		}
		components = {
			header: {
				cell: ResizeableTitle,
			},
		};

		componentDidMount() {
			this.props.onRef(this);
			this.getDetailTableColumns();
			let leftList = document.querySelectorAll('.shiftHeight  .ant-table-body');
			if (leftList.length > 0) {
				leftList[0].style.height = store.getState().tableHeight.y - 85 + 'px';
			}
		}

		componentWillReceiveProps(props) {
			this.setState({ frLocID: props.inOpLocDr, toLocDr: props.toLocDr });
			if (this.state.tacitlyApproveData) {
				this.setState({ tacitlyApproveData: props.handleThis.state.tacitlyApproveData });
			}
			if (props.detailInfo !== this.state.detailInfo) {
				let arr = [...props.detailInfo];
				this.setState({ data: arr, detailInfo: props.detailInfo }, () => {
					let spNum = 0;
					let rpNum = 0;
					for (var f = 0; f < arr.length; f++) {
						spNum = +arr[f].spAmt + spNum;
						rpNum = +arr[f].rpAmt + rpNum;
					}
					this.setState({ rpTotal: rpNum.toFixed(2), spTotal: spNum.toFixed(2) })
				});
			}
		}

		setSelect = (v) => {
			this.setState({ stkCatID: v })
		}

		// 获取明系列表头数据
		getDetailTableColumns = () => {
			let { language } = this.state;
			let data = {
				params: [{
					reactCode: ['StockTransferMakingForm'],
					compontName: 'ShiftDetailList',
					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.columnRef.onOpenModel(); }}>{language.language == 'EN' ? item.enDescripts : item.title}</div>,
								ellipsis: true
							}
						}) : '';
						let filterArr = arr.filter(function (item) { return item.display === 'Y' });
						let obj = {
							title: language.language == 'EN' ? 'operating' : '操作',
							key: 200,
							fixed: 'right',
							align: "center",
							width: '100px',
							render: (text, record) => (
								<span>
									<Popconfirm title={language.language == 'EN' ? 'Delete is not recoverable, are you sure you want to delete it?' : '删除不可恢复，你确定要删除吗?'} onCancel={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(record, e)} onClick={this.handlePopconfirm} >
										<span className='span' style={{ color: 'rgba(240,65,52,1)' }}>{language.language == 'EN' ? 'Delete' : '删除'}</span>
									</Popconfirm>
								</span>
							),
						};
						filterArr.push(obj);
						this.setState({ columns: filterArr, detailWidthTotal: res.totalWidth, ChineseEnglishSize: language.language == 'EN' ? res.result.language.EN : res.result.language.CN }, () => {
							this.props.handleThis.getChineseEnglishSize(this.state.ChineseEnglishSize)
						})
					}
				}
			})
		};

		// 点击删除时阻止事件冒泡
		handlePopconfirm = (e) => {
			e.stopPropagation();
		};

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

		// 保存成功后清空data数据
		deleteData() {
			this.setState({ data: [], detailInfo: [], rpTotal: 0, spTotal: 0, });
		}

		// 获取描述列表数据
		getModalListData(alias) {
			let data = {
				params: [
					{
						stockAlias: alias, // 库存项描述别名
						stkCatID: this.state.stkCatID ? this.state.stkCatID : undefined,
						locID: this.state.frLocID ? this.state.frLocID : undefined,
					}
				],
				pagination: [
					{
						pageSize: this.state.pageSize,
						currentPage: this.state.page,
					}
				],
			};
			$http.post('urlS', this, {
				code: "02020103",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						for (var i = 0; i < res.result.rows.length; i++) {
							res.result.rows[i].key = i
						}
						this.setState({ modalData: res.result, inputData: alias })
					} else {
						this.setState({ modalData: [], inputData: '' })
					}
				}
			})
		}

		// 新增明细录入
		addHandle = (obj) => {
			let inOpStatusDr = this.props.handleThis.state.userInfo ? this.props.handleThis.state.userInfo.stateID : '';
			if (+inOpStatusDr < 20 || inOpStatusDr === undefined) {
				let arr = [...this.state.data];
				if (obj.key) {
					for (let i = 0, len = arr.length; i < len; i++) {
						if (arr[i].key === obj.key) {
							arr[i] = obj;
						}
					}
				} else {
					arr.push(obj);
					for (let i = 0; i < arr.length; i++) {
						!arr[i].key ? arr[i].key = i + 'detail' : '';
					}
				}
				this.setState({ data: arr }, () => {
					console.log(this.state.data)
					let spNum = 0;
					let rpNum = 0;
					for (var f = 0; f < arr.length; f++) {
						spNum = +arr[f].spAmt + spNum;
						rpNum = +arr[f].rpAmt + rpNum;
					}
					this.setState({ rpTotal: rpNum.toFixed(2), spTotal: spNum.toFixed(2) })
					this.childDesc.resetFields();
					this.resetFields();
					if (this.state.stockID && +inOpStatusDr < 20) {
						this.props.handleThis.saveHandle()
					}
				});
			} else {
				message.error("当单据状态为保存时才可以进行操作");
			}
		};

		// 重置表单
		resetFields = () => {
			this.props.form.resetFields(); //清空所有
			this.setState({ userInfo: {}, rowKey: '', stockID: '', inputData: '', getBatchDetail: {} });
			this.childDesc.resetFields();
		};

		// 删除
		handleDelete = (record, e) => {
			e.stopPropagation();
			if (record.transDetailID) {
				// 当inOpDetailID存在的话则删除接口明细、不存在的话切割数组当中的一个对象
				let inOpStatusDr = this.props.handleThis.state.userInfo ? this.props.handleThis.state.userInfo.stateID : '';
				if (+inOpStatusDr < 20 || inOpStatusDr === undefined) {
					let data = {
						params: {
							detail: [{
								transDetailID: record.transDetailID ? record.transDetailID : undefined,
							}]

						}
					};
					$http.post('urlS', this, {
						code: "02020100",
						data: data,
						success: function (res) {
							if (+res.errorCode === 0) {
								message.success(res.errorMessage);
								// this.props.handleThis.resetFieldsAll();
								this.deleteRow(record.key);
							}
						}
					})
				} else {
					message.error("当单据状态为保存时才可以进行操作");
				}
			} else {
				this.deleteRow(record.key);
			}
		};

		// 本地删除数据
		deleteRow(key) {
			const dataSource = JSON.parse(JSON.stringify(this.state.data));
			this.setState({ data: dataSource.filter(item => item.key !== key), userInfo: {}, rowKey: '', stockID: '', getBatchDetail: {} }, () => {
				let spNum = 0;
				let rpNum = 0;
				for (var f = 0; f < this.state.data.length; f++) {
					spNum = +this.state.data[f].spAmt + spNum;
					rpNum = +this.state.data[f].rpAmt + rpNum;
				}
				this.setState({ rpTotal: rpNum.toFixed(2), spTotal: spNum.toFixed(2) })
			});
		}

		// 设置行属性
		onClickRow = (record) => {
			return {
				// 单击行选中
				onClick: (e) => {
					e.stopPropagation();
					// this.resetFields();
					console.log('行数据123123', record)
					if (this.state.rowKey === '') {
						this.setState({ rowKey: record.key, userInfo: record, stockID: record.stkLocBatID, unitData: record.unit });
					} else {
						if (this.state.rowKey !== record.key) {
							this.setState({ rowKey: record.key, userInfo: record, stockID: record.stkLocBatID, unitData: record.unit }
							);

						} else {
							this.setState({ rowKey: '', userInfo: {}, stockID: '', unitData: [], unitDesc: '' });
							this.resetFields();
							this.childDesc.resetFields();
						}
					}
				}
			}
		};

		// 页码改变的回调，参数是改变后的页码及每页条
		onChange = (page, pageSize) => {
			this.setState({ page: page, pageSize: pageSize }, () => {
				let { inputData } = this.state;
				this.getModalListData(inputData)
			})
		};

		// 条数改变的回调
		onShowSizeChange = (current, size) => {
			this.setState({ page: 1, pageSize: size }, () => {
				let { inputData } = this.state;
				this.getModalListData(inputData)
			})
		};

		// 表格行的类名
		setRowClassName = (record) => {
			return record.key === this.state.rowKey ? 'clickRowStyle' : '';
		};

		//药品名称为空时清除表单数据
		clearData = (val) => {
			if (!val.target.value) {
				this.setState({ userInfo: {}, getBatchDetail: {} });
			}
		};

		// 收起明细录入
		packUpHandle = () => {
			this.setState({ show: !this.state.show })
		};

		//组件权限编辑器
		childDesc = (ref) => {
			this.childDesc = ref;
		};

		//组件权限编辑器
		onColumnRef = (ref) => {
			this.columnRef = ref;
		};

		handleResize = index => (e, { size }) => {
			this.setState(({ columns }) => {
				const nextColumns = [...columns];
				nextColumns[index] = {
					...nextColumns[index],
					width: parseInt(size.width),
				};
				return { columns: nextColumns };
			});
		};

		// 入库单据批量出库ref
		onDocumentDeliveryRef = ref => {
			this.documentDeliveryRef = ref;
		}

		// 打开入库单据批量出库弹窗
		handleShowWarehouseOutModal = () => {
			this.documentDeliveryRef.showModal()
		}

		getEchoData = (id) => {
			this.props.handleThis && this.props.handleThis.getEchoData && this.props.handleThis.getEchoData(id)
		}

		render() {
			let { detailWidthTotal, ChineseEnglishSize } = this.state;
			const columns = this.state.columns.map((col, index) => ({
				...col,
				onHeaderCell: column => ({
					width: parseInt(column.width),
					onResize: this.handleResize(index),
				}),
			}));
			let userInfo = this.state.userInfo ? this.state.userInfo : {};
			return (
				<div>
					<Row>
						<Col span={10} style={{ display: this.state.show ? 'none' : '' }} className={!this.state.show ? "animate-wrap active down-in" : "animate-wrap"}>
							<Card
								size="small"
								title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.StockTransferMakingForminventoryMakingEntry ? ChineseEnglishSize.StockTransferMakingForminventoryMakingEntry.descripts : '库存制单录入'}</div>}
							>
								<div style={{ height: store.getState().tableHeight.y - 36 + 'px', overflow: 'auto' }} className="InPurPlan-detail-left">
									<InventoryFormModal parameter='ShiftVouching' inOpLocDr={this.props.inOpLocDr} stkCatID={this.state.stkCatID} toLocDr={this.state.toLocDr} unitData={this.state.unitData} SelectData={this.props.SelectData} rowKey={this.state.rowKey} userInfo={this.state.userInfo} handelThis={this} onRef={this.childDesc} />
								</div>
							</Card>
						</Col>
						<Col span={this.state.show ? 24 : 14}>
							<Card
								size="small"
								title={<span><Icon onClick={this.packUpHandle} type={this.state.show ? 'double-right' : 'double-left'} />{ChineseEnglishSize.StockTransferMakingForminventoryMaking ? ChineseEnglishSize.StockTransferMakingForminventoryMaking.descripts : '库存制单列表'}</span>}
								extra={
									<div>
										{/* <Button type="primary" ghost style={{ marginRight: '30px', height: "32px" }} onClick={this.handleShowWarehouseOutModal}></Button> */}
										<span onClick={this.handleShowWarehouseOutModal} style={{ color: "#1890ff", marginRight: '30px', cursor: "pointer" }}>入库单据批量出库</span>
										<span style={{ color: '#666' }} className='span'
											onClick={() => { this.columnRef.onOpenModel(); }}>
											<Icon type="setting" title={ChineseEnglishSize.StockTransferMakingFormcolumnSettings ? ChineseEnglishSize.StockTransferMakingFormcolumnSettings.descripts : '列权限设置'} />
										</span>
									</div>
								}
							>
								<div style={{ height: store.getState().tableHeight.y - 57 + 'px' }}>
									<Table
										columns={columns.length > 0 ? columns : this.columns}
										components={this.components}
										dataSource={this.state.data}
										pagination={false}
										bordered
										scroll={{ x: detailWidthTotal ? detailWidthTotal : 2300, y: store.getState().tableHeight.y - 107 }}
										onRow={this.onClickRow}
										rowClassName={this.setRowClassName}
										className="shiftHeight"
									/>
								</div>
								<Col style={{ fontSize: '15px', fontWeight: '700', marginLeft: '18px' }}>
									<span >{ChineseEnglishSize.StockTransferMakingFormrpTotal ? ChineseEnglishSize.StockTransferMakingFormrpTotal.descripts : '进价金额总价'}：</span><span>{this.state.rpTotal} </span>
									<span style={{ marginLeft: '50px' }}>  {ChineseEnglishSize.StockTransferMakingFormspTotal ? ChineseEnglishSize.StockTransferMakingFormspTotal.descripts : '售价金额总价'}：</span><span>{this.state.spTotal}</span>
									<span style={{ marginLeft: '50px' }}> 总条数 ：</span><span>{this.state.data && this.state.data.length ? this.state.data.length : 0}</span>
								</Col>
							</Card>
						</Col>
					</Row>
					<ColumnAuthoritysModel
						clientWidth='800px'
						compontName='ShiftDetailList'
						configType="C"
						onRef={this.onColumnRef}
						reloadData={this.getDetailTableColumns}
					/>
					<DocumentDeliveryModal onRef={this.onDocumentDeliveryRef} SelectData={this.props.SelectData} getEchoData={this.getEchoData} />
				</div>
			)
		}
	}
);

export default ShiftDetailList;