// 采购计划制单-依据请求单
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Modal, Table, Switch, message, Pagination, Input, Checkbox, Icon } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import '../style/index.less';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
	labelCol: { span: 7 },
	wrapperCol: { span: 17 },
};
const formItemSwitch = {    // label 和input宽度
	labelCol: { span: 12 },
	wrapperCol: { span: 12 },
};
const AccordingToWarehouseByRet = Form.create()(
	class extends React.Component {
		constructor() {
			super();
			this.state = {
				userInfo: JSON.parse(window.sessionStorage.userData),
				data: [],
				queryCondition: {},
				SelectData: {},
				inOpLocDr: '',
				vendor: '',
				checkedDataDetails: [], //请求单单明细数据
				CheckedData: [], //请求单数据
				size: 'small',
				pageSize: 10,
				pageSize2: 10,
				page: 1,
				page2: 1,
				total: 0,
				total2: 0,
				detailTotal: 0,
				show: false,
				modalColumns: [],
				visible: false,
				detailWidthTotal: '', // 明细表头长度
				stockID: '', //主表格id
				rowKey: '', //行key值
				language: JSON.parse(window.sessionStorage.userData),
				parameterCode: '',
				ChineseEnglishSize: {},
				columns: [],
				columnsWidth: '',
				checkData: [],
				selectedRowKeys:[]
			};

			// 药品的数据表头
			this.columns = [
				{
					key: 1,
					title: '供应商',
					dataIndex: 'vendorDesc',
					align: "center",
					width: '28%'
				},
				{
					key: 2,
					title: '入库科室',
					dataIndex: 'inOperLocDesc',
					align: "center",
					width: '16%',
				},
				{
					key: 3,
					title: '入库单号',
					dataIndex: 'No',
					align: "center",
					width: '20%',
				},
				{
					key: 4,
					title: '单据状态',
					dataIndex: 'statusDesc',
					align: "center",
					width: '16%',
				},
				{
					key: 5,
					title: '入库日期',
					dataIndex: 'createDate',
					align: "center",
				}
			]
			// 付款单详细表头
			this.modalColumns = [
				{
					key: 1,
					title: '代码',
					dataIndex: 'stockCode',
					align: "center",
					width: '150px'
				},
				{
					key: 2,
					title: '描述',
					dataIndex: 'stockDesc',
					align: "center",
					width: '150px'
				},
				{
					key: 3,
					title: '包装规格',
					dataIndex: 'stockSpec',
					align: "center",
					width: '150px'
				},
				{
					key: 4,
					title: '生产厂家',
					dataIndex: 'manfDesc',
					align: "center",
					width: '300px',
					render: (text, record, index) => {
						return (<Select style={{ width: '100%' }} value={text} onChange={(e) => this.handleFieldSelect(e, 'manfID', record.inOperDetailID)}>
							{this.state.SelectData.vendor && this.state.SelectData.vendor.map((item, i) => {
								return <Option value={item.id} key={i}>{item.descripts}</Option>
							})}
						</Select>
						)
					}
				},
				{
					key: 5,
					title: '批号',
					dataIndex: 'batNo',
					align: "center",
					width: '150px',
					render: (text, record, index) => {
						return (<Input min={0} style={{ width: '90%' }} type="number" value={text} onChange={(e) => this.handleFieldChange(e, 'batNo', record.inOperDetailID)} />)
					}
				},
				{
					key: 6,
					title: '有效期',
					dataIndex: 'expDate',
					align: "center",
					width: '150px',
					render: (text, record, index) => {
						return (<DatePicker style={{ width: '90%' }} value={Moment(text, 'YYYY-MM-DD')} onChange={(e) => this.onChangeTime(e, 'expDate', record.inOperDetailID)} />)
					}
				},
				{
					key: 7,
					title: '生产日期',
					dataIndex: 'produceDate',
					align: "center",
					width: '150px'
				},
				{
					key: 8,
					title: '数量',
					dataIndex: 'qty',
					align: "center",
					width: '100px'
				},
				{
					key: 9,
					title: '单位',
					dataIndex: 'unitDesc',
					align: "center",
					width: '100px'
				},
				{
					key: 10,
					title: '进价',
					dataIndex: 'rp',
					align: "center",
					width: '100px',
					render: (text, record, index) => {
						return (<Input min={0} style={{ width: '90%' }} type="number" value={text} onChange={(e) => this.handleFieldChange(e, 'rp', record.inOperDetailID)} />)
					}
				},
				{
					key: 11,
					title: '售价',
					dataIndex: 'sp',
					align: "center",
					width: '150px'
				},
				{
					key: 12,
					title: '发票号',
					dataIndex: 'invNo',
					align: "center",
					width: '150px',
					render: (text, record, index) => {
						return (<Input min={0} style={{ width: '90%' }} type="number" value={text} onChange={(e) => this.handleFieldChange(e, 'invNo', record.inOperDetailID)} />)
					}
				},
				{
					key: 13,
					title: '发票日期',
					dataIndex: 'invDate',
					align: "center",
					width: '150px',
					render: (text, record, index) => {
						return (<DatePicker style={{ width: '90%' }} value={Moment(text, 'YYYY-MM-DD')} onChange={(e) => this.onChangeTime(e, 'invDate', record.inOperDetailID)} />)
					}
				},
				{
					key: 14,
					title: '进价金额',
					dataIndex: 'rpAmt',
					align: "center",
					width: '150px'
				},
				{
					key: 15,
					title: '售价金额',
					dataIndex: 'spAmt',
					align: "center",
					width: '150px'
				},
				{
					key: 16,
					title: '进销差额',
					dataIndex: 'difAmt',
					align: "center",
					width: '150px'
				}
			]
		}

		componentDidMount() {
			this.props.onRef(this);
			// 初始化数据
			this.getTacitlyApproveData();
			this.getDetailTableColumns();
		}
		// 获取明系列表头数据
		getDetailTableColumns = () => {
			let { language } = this.state;
			let data = {
				params: [{
					compontName: 'CurrStkBatch',
					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.setState({ parameterCode: 'CurrStkBatch' }, () => {
										this.columnRef.onOpenModel();
									})
								}}>{language.language == 'EN' ? item.enDescripts : item.title}</div>,
							}
						}) : '';
						let filterArr = arr.filter(function (item) { return item.display === 'Y' });
						this.setState({ modalColumns: filterArr, detailWidthTotal: res.totalWidth })
					}
				}
			});
		};


		//获取操作行数据对象
		getRowByKey(key, newData) {
			const { checkedDataDetails } = this.state;
			return (newData || checkedDataDetails).filter(item => item.inOperDetailID === key)[0];
		}
		//文本框数据修改
		handleFieldChange = (e, fieldName, key) => {
			const { checkedDataDetails } = this.state;
			const newData = checkedDataDetails.map(item => ({ ...item }));
			const target = this.getRowByKey(key, newData);
			if (target) {
				target[fieldName] = e.target.value;
				this.setState({ checkedDataDetails: newData });
			}
		};
		//日期数据修改
		onChangeTime = (e, fieldName, key) => {
			const { checkedDataDetails } = this.state;
			const newData = checkedDataDetails.map(item => ({ ...item }));
			const target = this.getRowByKey(key, newData);
			if (target) {
				target[fieldName] = Moment(e).format('YYYY-MM-DD');
				this.setState({ checkedDataDetails: newData });
			}
		};
		//下拉框数据修改
		handleFieldSelect = (e, fieldName, key) => {
			const { checkedDataDetails } = this.state;
			const newData = checkedDataDetails.map(item => ({ ...item }));
			const target = this.getRowByKey(key, newData);
			if (target) {
				target[fieldName] = e;
				this.setState({ checkedDataDetails: newData });
			}
		};
		//清空表格内容
		handleReset = () => {
			this.setState({ CheckedData: [], checkedDataDetails: [], total: 0 });
			this.props.form.setFieldsValue({ stockDr: undefined });
			this.props.form.resetFields();
		};

		// 获取界面默认值
		getTacitlyApproveData() {
			let data = {
				params: []
			};
			// 获取下拉数据
			$http.post('urlS', this, {
				code: "02060005",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ SelectData: res.result[0] })
					}
				}
			})
		}


		// 获取请求单详情
		getRequestForm = () => {
			this.setState({ detailsLoading: true })
			let listData = document.querySelectorAll('.detailsHeight  .ant-table-body');
			if (listData.length > 0) {
				listData[0].style.height = store.getState().tableHeight.y - 255 + 'px';
			}
			this.props.form.validateFields((err, val) => {
				let obj = JSON.parse(JSON.stringify(val));
				if (err == null) {
					let data = {
						params: [{
							locID: obj.locDr ? obj.locDr : undefined,
							vendorID: obj.vendorDr ? obj.vendorDr : undefined,
						}],
					};
					$http.post('urlS', this, {
						code: "02060208",
						data: data,
						success: function (res) {
							if (res.result.length > 0) {
								for (var i = 0; i < res.result.length; i++) {
									res.result[i].key = i;
								}
								this.setState({ checkedDataDetails: res.result,  detailsLoading: false });
							} else {
								this.setState({ checkedDataDetails: [] });
								message.error("没数据")
							}
						}
					});
				}
			});
		};

		// 页码改变的回调，参数是改变后的页码及每页条数
		onChange = (e) => {
			this.setState({ page: e, pageSize: this.state.pageSize }, () => {
				// 重新调用查询方法
				this.getWarehouseList();
			});
		};

		onShowSizeChange = (current, size) => {
			this.setState({ page: current, pageSize: size }, () => {
				// 重新调用查询方法
				this.onChange(current, size);
			})
		};

		// 页码改变的回调，参数是改变后的页码及每页条数
		onChange2 = (e) => {
			this.setState({ page2: e, pageSize2: this.state.pageSize2 }, () => {
				// 重新调用查询方法
				this.getRequestForm();
			});
		};

		onShowSizeChange2 = (current, size) => {
			this.setState({ page2: current, pageSize2: size }, () => {
				// 重新调用查询方法
				this.onChange(current, size);
			})
		};

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

		//组件权限编辑器
		onColumnRef = (ref) => {
			this.columnRef = ref;
		};
		// 关闭
		handleCancel = (e) => {
			this.setState({
				visible: false,
				getBatchDetail: [],
				checkedDataDetails:[],
				total2: 0,
				rowKey: '',
				rowId: '',
				data: [],//主列表数据
				total: 0,
				page: 1,
				pageSize: 10,
				locId: '',
				toLocID: '',
				checkData: [],
				selectedRowKeys:[]
			});
		};
		// 确定
		handleOk = (e) => {
			this.handleCancel()
		};
		// 打开弹框
		showModal = (v) => {
			this.setState({
				visible: true,
				ChineseEnglishSize: v
			});
		};

		// 设置行属性
		onClickRow = (record) => {
			return {
				// 单击行选中
				onClick: (e) => {
					e.stopPropagation();
					if (this.state.rowKey === '') {
						// 保存行数据以及ID
						this.setState({ rowKey: record.key, stockID: record.inOperID }, () => {
							this.getRequestForm();
						});
					} else {
						if (this.state.rowKey !== record.key) {
							this.setState({ rowKey: record.key, stockID: record.inOperID }, () => {
								this.getRequestForm();
							});
						} else {
							this.setState({ rowKey: '', stockID: '', checkedDataDetails: [] });
						}
					}
				}
			}
		};

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

		//保存
		save = () => {
			let locDr = this.props.form.getFieldValue('locDr');
			let data = {
				params: [{
					stkLocBatchIDArr: this.state.selectedRowKeys ? this.state.selectedRowKeys : undefined,
					locID: locDr ? locDr : undefined,
				}]
			};
			$http.post('urlS', this, {
				code: "02060206",
				data: data,
				success: function (res) {
					if (res.errorCode == 0) {
						message.success('保存成功')
						this.handleOk();
						this.props.handleThis.getEchoData(res.result);

					}
				}
			});
		}
		render() {
			const { getFieldDecorator } = this.props.form;
			let userInfo = this.state.userInfo ? this.state.userInfo : {};
			let { ChineseEnglishSize, columns, modalColumns } = this.state;

			//下拉列表
			let loc = [];
			this.state.SelectData.inOpLoc && this.state.SelectData.inOpLoc.map((item, i) => {
				loc.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
			});
			const rowSelection = {
                selectedRowKeys: this.state.selectedRowKeys,
                selectedRows: this.state.checkData,
                onChange: (selectedRowKeys, selectedRows) => {
                    this.setState({ selectedRowKeys: selectedRowKeys, checkData: selectedRows },()=>{
						console.log("selectedRowKeys",this.state.selectedRowKeys)
						console.log("selectedRows",this.state.selectedRows)
					})
                }
            };
			return (
				<Modal
					visible={this.state.visible}
					onCancel={this.handleCancel}
					width='75%'
					footer={null}
					className="AccordingToChecked"
				>
					<Row>
						<Card
							size="small"
							title={<div className="card-title-left-icon"><div></div>{'已审核入库单查询'}</div>}
						>
							<Col >
								<Form>

									<Row >
										<Col span={6}>
											<FormItem {...formItemLayout} label={'科室'}>
												{getFieldDecorator('locDr', {
													initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,
													rules: [{ required: true, message: '科室不能为空' }]
												})(
													<Select allowClear={true}>
														{loc}
													</Select>
												)}
											</FormItem>
										</Col>
										<Col span={6}>
											<FormItem {...formItemLayout} label={'供应商'}>
												{getFieldDecorator('vendorDr', {
													initialValue: undefined,
													rules: [{ required: false, message: '供应商不能为空' }]
												})(
													<Select showSearch allowClear placeholder={'请选择供应商'} >
														{this.state.SelectData.vendor && this.state.SelectData.vendor.map(item => {
															return <Option key={item.id} value={item.id} >{item.descripts}</Option>
														})}
													</Select>
												)}
											</FormItem>
										</Col>
										<Col  span={12} style={{ marginTop: '4px'}} >
											<Button style={{ marginLeft: '30px' }} onClick={this.getRequestForm}>{ChineseEnglishSize.MaterialStorageOrderMakingsearch ? ChineseEnglishSize.MaterialStorageOrderMakingsearch.descripts : '查询'}</Button>
											<Button style={{ marginLeft: '30px' }} onClick={this.save}>{ChineseEnglishSize.MaterialStorageOrderMakingsave ? ChineseEnglishSize.MaterialStorageOrderMakingsave.descripts : '保存为退货单'}</Button>
											<Button style={{ marginLeft: '30px' }} onClick={this.handleReset}>{ChineseEnglishSize.MaterialStorageOrderMakingclean ? ChineseEnglishSize.MaterialStorageOrderMakingclean.descripts : '清空'}</Button>
										</Col>
									</Row>
								</Form>
							</Col>
						</Card>
					</Row>
					<Row>
						<Card
							size="small"
							title={<span><Icon onClick={this.packUpHandle} type={this.state.show ? 'double-right' : 'double-left'} />{ChineseEnglishSize.MaterialStorageOrderMakingstartDated ? ChineseEnglishSize.MaterialStorageOrderMakingstartDated.descripts : '入库单明细'}</span>}
							extra={<span style={{ color: '#666' }} className='span' onClick={() => {
								this.setState({ parameterCode: 'CurrStkBatch' }, () => {
									this.columnRef.onOpenModel();
								})
							}}><Icon type="setting" title={ChineseEnglishSize.MaterialStorageOrderMakingdelete ? ChineseEnglishSize.MaterialStorageOrderMakingdelete.descripts : '列权限设置'} /></span>}
						>
							<div style={{ height: store.getState().tableHeight.y - 200 + 'px' }}>
								<Table
									rowSelection={rowSelection}
									columns={modalColumns.length > 0 ? modalColumns : this.modalColumns}
									dataSource={this.state.checkedDataDetails}
									pagination={false}
									bordered
									style={{ height: (store.getState().tableHeight.y - 238) }}
									scroll={{ x: 2400, y: store.getState().tableHeight.y - 295 }}
									rowKey={record => record.ID}
									className='detailsHeight'
								/>
								{/* <CommonPagination size={this.state.size} current={this.state.page2} total={this.state.total2} search='search'
									onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.checkedDataDetails}
									loading={this.state.detailsLoading} onChange={this.onChange2.bind(this)} /> */}
							</div>
						</Card>
					</Row>

					{/*//显示表头修改弹窗*/}
					<ColumnAuthoritysModel
						clientWidth='800px'
						compontName={this.state.parameterCode}
						configType="C"
						onRef={this.onColumnRef}
						reloadData={() => {
							if (this.state.parameterCode == 'CurrStkBatch') {
								this.getDetailTableColumns()
							}
						}
						}
					/>
				</Modal>
			)
		}
	}
);
export default AccordingToWarehouseByRet;