//科室外院开单项目
import React from 'react';
import {
    Form, Select, Input, Button,Row,Col,Popconfirm,DatePicker,Spin,message
  } from 'antd';
import { $http } from '../../../containers/config/https';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx'; // 公共table组件
import EntryName from './EntryName.jsx';//项目名称子组件
import {Util,dayFormat} from 'tools/index';
import moment from 'moment';
import store from '../../../store';

const Option = Select.Option;
const FormItem = Form.Item;
let timeout;
let user;
class ExtermalDepartments extends React.Component {

    constructor(props) {
		super(props);
		this.state = {
			// 表格数据
			locDr: "",//科室id
			medItemInput:'',
			tableData: [],
			// 表格数据总条数
			total: 0,
			showLoading: true,
			page: 1,
			pageSize: 10,
			medData:[],
			StartDate:"",
			StopDate:"",
			price:"",
			medItemId:"",
			toOutId:'',

		};
		user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		this.columns = [
			{
			  key: 1,
			  title: '项目代码',
			  dataIndex: 'toOthMedCode',
				align: "center",
				width: 130
			},
			{
			  key: 2,
			  title: '项目名称',
			  dataIndex: 'toOthMedDesc',
				align: "center",
				width: 130
			},
			{
			  key: 3,
			  title: '项目单价',
			  dataIndex: 'toOthMedPrice',
				align: "center",
				width: 130
			},
			{
			  title: '操作',
			  key: 9,
			  align: "center",
			  width: 130,
			  render: (text, record) => (
				<span>
				  <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
						<span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
				  </Popconfirm>
				</span>
			  ),
			}
		]
	}

	componentDidMount() {
		this.setState({showLoading: false});
		if(this.props.locID !== ''){
			// 初始化列表数据
			//this.handleQueryMed();
			this.handleQuery();
			}		
		}
		
		componentWillReceiveProps(nextProps) {
			// 当修改选择的数据后刷新数据
			if (nextProps.locID !== '') {
				// this.handleQuery(this.props.locid);
			} else {
			//		this.setState({ locid: "" })
			}

	}

	
	// 查询tab数据 
	handleQuery = () => {
		let { page, pageSize,medItemInput} = this.state;
	//	console.log(this.state.medItemInput)
     //console.log(this.props.locid)
		let data = {
			params: [{
				  locID:this.props.locID,
					medDesc:medItemInput
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page
			}]
		}
		$http.post('urlS', this, {
			code: "01050014",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0  && res.result) {
					for(var i = 0; i < res.result.Data.length; i++) {
						res.result.Data[i].key = i
					}
					this.setState({ tableData: res.result.Data,total: res.result.TotalCount })
					// 数据加载成功关闭loading
					this.child.handleLoading();
				} else {
					this.setState({tableData: [], total: 0})
						// 数据加载成功关闭loading
						this.child.handleLoading();
				}
			},
			error: function (error) {
				this.setState({tableData: [], total: 0}, () => {
					// 数据加载成功关闭loading
						this.child.handleLoading();
				})
			}   
		})
	}

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
	//	console.log(page,pageSize);

		this.setState({page: page, pageSize: pageSize}, () => {
			// 重新调用查询方法
			this.handleQuery();
		//	this.getTableData(status, hospitalDr, locDesc)
		})
	}

	updateState=(name,value)=>{
		this.setState({[name]:value});
	}
		// 调用公共组件的连接事件
		onRef = (ref) => {
			this.child = ref
		}
			
		// 新增对外开单项目
		handelSave = (e) => {
			e.preventDefault();
			this.props.form.validateFields((err, values) => {
				if(err){
					return;
				}
				const startDate = moment(values.StartDate).format(dayFormat)
				let stopDate = "";
				if((values.StopDate!=null)&&(values.StopDate!=""))stopDate=moment(values.StopDate).format(dayFormat)
				let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
				let data = {
					params:[{
										locID:this.props.locID,//科室id
										medID: this.state.medItemId,//医嘱项id
										startDate: startDate,//生效时间
										stopDate: stopDate,//失效时间
										toOutID:this.state.toOutId,//对外开单项目的id
										updateUserID:user.userID
								}]
				}
				$http.post('urlS', this, {
						code: "01050015",
						data: data,
						success: (res) => {
								if (res.errorCode === '0') {
										message.success('新增成功');
									// 刷新列表数据
										this.handleQuery();		
								}
						}
				})

			});

			
	}
			// 删除
	handleDelete = (record) => {
		let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		//console.log(user)
		let data = {
			params: [{
				toOthID: record.toOthID,
				updateUserID: user.userID
			}]
		}
		$http.post('urlADS', this, {
			code: '01050016',
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
					// 刷新列表数据
					this.handleQuery();
				}
			}
		})
	}
	// handleQueryMed=()=>
	// {
	
	// 	let data = {
	// 		params: [{
	// 			// findCode:"氯化钠",
	// 			// detailFlag:""
	// 		}]
	// 	}
	// 	$http.post('urlS', this, {
	// 		code: "01010002",
	// 		data: data,
	// 		success: function (res) {
	// 			if (+res.errorCode === 0) {
	// 				//this.setState({ medData: res.result.Data})
	// 			} 
	// 		}
	// 	})
	// }

		onSelctChange = (id)=>{
			this.state.medData.forEach((item)=>{
				if(item.id==id){
					let startDate=item.startDate;
					let stopDate=item.stopDate;
					if(startDate!=="")startDate=moment(startDate)
					if(stopDate!=="")stopDate=moment(stopDate)
						this.setState({
						price:item.price,
						medItemId:item.id,
						toOutId:item.toOutId,
						StartDate:startDate,
						StopDate:stopDate,
					})
				}
			})
		
		}
	  
		GetMedItem=(value,callback)=>{
			if (timeout) {
				clearTimeout(timeout);
				timeout = null;
			}
			function getMedItemData(){
					if(value===""){
						this.setState({ medData: []})
						return 
					}
					let data = {
						params: [{
							hospID:user.hospID,
							findCode:value,
							// detailFlag:"1"
						}]
					}
					$http.post('urlS', this, {
						code: "01010002",
						data: data,
						success: function (res) {
							if (+res.errorCode === 0) {
								callback(res.result.Data)

							} 
						}
					})
				}
				timeout = setTimeout(getMedItemData, 1000);
			}
		

		handleSerach=(value)=>{
			var reg = /\s/g;
			if(reg.test(value)) {
				message.error('不能输入空字符')
				return 
			}
 			this.GetMedItem(value,data => this.setState({ medData:data}))
		
	 } 
	 
		render() {
					const { getFieldDecorator } = this.props.form;
					const formItemInput  = {
							labelCol: {span: 5},
							wrapperCol: {span: 16}
					};
							// 组件所需参数
				const param = {
					// 表头配置
					columns: this.columns,
					// 表格数据
					data: this.state.tableData,
					// 数据总条数
					total: this.state.total,
					page: this.state.page,
					// 表格的宽度
					x: 900,
					y: store.getState().tableHeight.y -70,
					height: store.getState().tableHeight.y -25 + 'px',
				}
        return (
					<Spin tip="加载中..." spinning={this.state.showLoading}>
            <div>
            <div style={{padding:'30px 30px 0',boxSizing:'border-box'}}>
            <Form style={{width:'60%'}} layout="vertical"  onSubmit={this.handelSave}>
				<Row gutter={24}>
						<Col span={16}>
								<Form.Item label="项目：" {...formItemInput} style={{padding:0,margin:0}}>
									{getFieldDecorator('Descripts', {
													rules: [{ required: true, message: '请输入项目' }],
									})(
										<Select
										allowClear
										showSearch
										optionFilterProp="title"
										style={{marginTop:"-10px"}}
										placeholder="请输入"
										onChange={this.onSelctChange}
										onSearch={this.handleSerach}
										filterOption={false}
										>
										{
											this.state.medData.map(
												(item)=>{
													return <Option key={item.id} value={item.id} title={item.descripts + "^"+item.descriptsSPCode}>{item.descripts}</Option>
												}
											)

										}
										</Select>
									)}
							</Form.Item>
						</Col>
                      <Col span={8}>
							<Form.Item label="单价:" 
										labelCol={{span: 6}}
										wrapperCol={{span: 16}} 
										style={{padding:0,margin:0}}>
										{getFieldDecorator('price',{
											initialValue: this.state.price,
										})(
											<p style={{padding:0,margin:0}}>{this.state.price}</p> 
										)}
							</Form.Item> 
						</Col>
                  </Row>
                  <Row gutter={24}>
							<Col span={16}>
								<Form.Item label="生效日期：" {...formItemInput}  style={{padding:0,margin:0}}>
										{getFieldDecorator('StartDate', {
														initialValue: this.state.StartDate,
														rules: [{ required: true, message: '生效日期不能为空' }],
										})(
											<DatePicker style={{width:'100%'}} format="YYYY-MM-DD" />
										)}
								</Form.Item>
							</Col>
                  </Row>
                  <Row gutter={24}>
							<Col span={16}>
								<Form.Item  label="&nbsp;&nbsp;&nbsp;失效日期：" {...formItemInput} style={{padding:0,margin:0}}>
											{getFieldDecorator('StopDate', {
																initialValue: undefined,
											})(
												<DatePicker style={{width:'100%'}} format="YYYY-MM-DD" />
											)}
									</Form.Item>
								</Col>

					</Row>
						<Form.Item
							wrapperCol={{ span: 12, offset: 7}}
						>
							<Button type="primary" htmlType="submit">
								保存
							</Button>
						</Form.Item>
            </Form>
            </div>
            <div style={{widht: '100%', height: '10px', background: '#f0f2f5'}}></div>
						<EntryName updateState={this.updateState} handleQuery={this.handleQuery}></EntryName>
					
							<div style={{ padding: 10}}>
								{/* handelThis将夫组件的属性与方法给子组件访问 */}
										<PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
							</div>
				
					</div>
					</Spin>
        );
    }
}

export default Form.create({ name: 'ExtermalDepartments' })(ExtermalDepartments);