//新床位模态框
import React from 'react';
import { Modal, Form, Row, Col, Select, Input, DatePicker, message } from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from '../../../containers/config/https';
import moment from 'moment';
//import PublicModalTable from '../../common/PublicModalTable.jsx';

const { Option } = Select;
class DepartmentFindAdd extends React.Component {
    constructor(props) {
        super(props);
        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.state = {
            visible: false,
            userInfo: {},
            options: {},
            // docterPage: 1,
            // docterPageSize: 10,
            // doctorData: [],
            // doctorTotal: 0,
            // doctorRowData: {}, // 选中的行医生数据
            // doctorValue: '', //
            // docterTop: 0,
            // docterLeft: 0,
        }
        // this.columns = [
		// 		{
		// 			key: 1,
        //             title: 'code',
        //             dataIndex: 'code',
        //             align: "center",
		// 		},
		// 		{
		// 			key: 2,
        //             title: '房间号',
        //             dataIndex: 'descripts',
        //             align: "center",
		// 		}
		// 	];
    }

    componentDidMount() {
       this.props.onRef(this);
        this.getOptions();
        //this.getSelectData();
    }
    // componentWillReceiveProps(nextProps) {
    //     //console.log(nextProps)
    //     if (nextProps.data && JSON.stringify(this.props.data) !== JSON.stringify(nextProps.data) && nextProps.flag === 'compile') {
    //         this.getListData(nextProps.data)
    //     }
    // }
//   //获取房间列表数据
//   getDocterListData(values) {
//     let {docterPage, docterPageSize} = this.state;
//     let data = {
//         params: [
//             {
//                 input: values,
//             }
//         ],
//         pagination:[
//             { 
//                 currentPage: docterPage,
//                 pageSize: docterPageSize
//             }
//         ]

//     }
//     $http.post('urlS', this, {
//         code: "01040005",
//         data: data,
//         success: function (res) {
//             if (+res.errorCode === 0) {
//                 for(var i = 0; i < res.Data.length; i++) {
//                     res.Data[i].key = i
//                 }
//                 this.setState({doctorData: res.Data, doctorTotal: res.TotalCount})
//             }
//         }
//     })
// }


    
    getOptions = () => {
        const data = [{
          locID: this.props.locID,
          roomFlag:'1',
          resDoctorFlag:'1',
          resNurseFlag:'1',
          bedNoFlag:'1',
          buildFlag:'1',
          floorFlag:'1',
          bedCatFlag:'1',
          bedStatusFlag:'1',
          roomTypeFlag:'1',
        }]
        $http.post('urlS', this, {
          code: "01040022",
          data: { params: data },
          success: function (res) {
            if (res.errorCode === '0') {
              this.setState({
                options: res,
                hbLocDesc: res.hbLocDesc,
                hospDesc: res.hospDesc
              })
            } else {
              message.error('查询失败：' + res.errorMessage);
            }
          }
        })
      }
    //重置表单
    handleReset = () => {
        this.props.form.resetFields();
    }

    // 获取单条数据的方法
    getListData(userInfo) {
       //console.log(userInfo)
        let data = {
            params: [{
              bedID: userInfo.bedID,
            }],
            pagination: [{
              pageSize: 10,
              currentPage: 1,
            }]
          }
          $http.post('urlS', this, {
            code: "01050021",
            data: data,
            success: function (res) {
              if (+res.errorCode === 0) {
                  this.setState({userInfo: res.result.Data[0]})
                // this.props.form.setFieldsValue(res.result.Data[0])
              }
            }
          })
    }

    // 下拉框选中事件
    handleOnSelect = (num, query, value) => {
       // console.log(1);
        setTimeout(() => {
            //console.log(this)
            this[`myRef${num + 1}`].current.focus();
        }, 300)

        this.setState({
            [query]: value
        })

    }
      // 下拉框选中事件
  handleOnChange = (num, query, e) => {
    setTimeout(() => {
      this[`myRef${num + 1}`].current.focus();
    }, 300)
    this.setState({
      [query]: e.target.value
    })
  }
    showModal = () => {
        this.handleReset();
        this.setState({
            visible: true,
        }, () => {
            if (this.props.flag === 'compile') {
                this.getListData(this.props.data)
            }
        });
    }

    // handleOk = (e) => {
    //   //console.log(e);
    //   this.setState({
    //     visible: false,
    //   });
    // }

    handleCancel = (e) => {
        this.setState({
            visible: false,
        });
    }
 
    handelFunction(id, msg) {
        //console.log(roomTypeDr)
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
                let data = {
                    params: [
                        {
                            bedID: id,
                            locID: this.props.locID,
                            bedRoomID: values.bedRoomID,
                            bedCBID: values.bedCBID,
                            bedBuildID: values.bedBuildID,
                            bedFloorID: values.bedFloorID,
                            bedStatusID: values.bedStatusID,
                            bedCatID: values.bedCatID,
                            bedResDocID: values.bedResDocID,
                            bedResNurID: values.bedResNurID,
                            bedStartDate: values.bedStartDate ? moment(values.bedStartDate).format('YYYY-MM-DD') : '',
                            bedStopDate: values.bedStopDate ? moment(values.bedStopDate).format('YYYY-MM-DD') : '',
                            updateUserID: user.userID,
                            bedRoomTypeID:values.bedRoomTypeID,
                        }
                    ]

                }

                $http.post('urlADS', this, {
                    code: "01050020",
                    data: data,
                    success: function (res) {
                        //console.log(res)
                        if (+res.errorCode === 0) {
                            // 成功提示
                            message.success(msg + '成功');
                            //新增或编辑成功重置form表单
                            this.handleReset();
                            this.setState({userInfo: {}})
                            // 关闭弹框
                            this.handleCancel();
                            // 刷新列表数据
                            this.props.handleThis.handleQuery();
                            //this.props.handleThis.compileLocId(res.locid)

                        }
                    }
                })
            }
        });
    }

    // 保存
    handelSave = (e) => {
        e.preventDefault();
        let { flag } = this.props;
        if (flag === 'compile') {
            this.handelFunction(this.props.data.bedID, '编辑');
        } else {
            this.handelFunction("", '新增');
        }
    }

    // 选择房间号将房间类型显示出来
		handelDirectorDr = (key) => {
            // console.log(key)
            // console.log(this.props.selectData.roomNo)
			for (var i = 0; i < this.state.options.roomNo.length; i++) {
				if (+this.state.options.roomNo[i].id === +key) {
					this.props.form.setFieldsValue({roomTypeDesc: this.state.options.roomNo[i].roomTypeDesc})
				}
			}
        }
        
    // 获取房间号信息信息
//     getDoctorData = (e) => {
//         this.setState({
//             docterTop: '258px',
//             docterLeft: '773px',
//             docterPage: 1,
//             docterPageSize: 10,
//             doctorValue: e.target.value
//         }, () => {
//             let {doctorValue} = this.state;
//             this.getDocterListData(doctorValue);
//         });
//         this.child.showModal();
//     }

//     compileDoctorPage = (page, pageSize) => {
//         this.setState({docterPage: page, docterPageSize: pageSize}, () => {
//             this.getDocterListData()
//         })
//     }
//    // 当房间号失去焦点后
// 		onBlurDirector = (e) => {
//             let descripts = this.state.doctorRowData && this.state.doctorRowData.descripts ? this.state.doctorRowData.descripts : (this.state.userInfo ? this.state.userInfo.roomDesc : '')
//             if (e.target.value !== descripts) {
//                 this.props.form.setFieldsValue({locRoomNo: undefined});
//             }
// 		}
//     // 房间号操作弹框
//     onClickRowDoctor = (record) => {
//         return {
//             onDoubleClick: () => {
//                this.confirmSelectionDoctor(record);
//             }
//         }
//     }

//     // 双击选中房间号行数据的回调
//     confirmSelectionDoctor = (record) => {
//         this.setState({doctorRowData: record}, () => {
//             this.props.form.setFieldsValue({locRoomNo: record.descripts})
//             // 关闭弹窗
//             this.child.handleCancel();
//         })
//     }

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

    render() {
        
        const { getFieldDecorator } = this.props.form;
        let userInfo = this.state.userInfo;
        if(this.props.flag==="add"){
            userInfo={};
        }
        var date = new Date();
       
        const formItemInput = {
            labelCol: { span: 8 },
            wrapperCol: { span: 16 }
        };
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        // let param = {
        //     width: 540,
        //     top:this.state.docterTop,
        //     left:this.state.docterLeft,
        //     height: 400,
        //     columns: this.columns,
        //     data:this.state.doctorData,
        //     isOnRow: true,
        //     showPagination: true,
        //     total:this.state.doctorTotal,
        //     page:this.state.docterPage
        // }
        return (
            <div>
            <Modal
                width={600}
                title="添加科室床位"
                visible={this.state.visible}
                onOk={this.handelSave}
                onCancel={this.handleCancel}
            >
                <div style={{ paddingLeft: '24px' }}>
                    <span>所属医院：{this.props.hospDesc}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <span>所属科室：{this.props.hbLocDesc}</span>
                </div>
                <Form
                    style={{ paddingTop: '20px', paddingBottom: '0' }}
                // className="ant-advanced-search-form"
                // onSubmit={this.handleSearch}
                >
                    <Row gutter={24}>
                        <Col span={12}>
                        <Form.Item
                                label="房间号"
                                {...formItemInput}
                            >
                                {getFieldDecorator('bedRoomID', {
                                    initialValue: userInfo.bedRoomID ? userInfo.bedRoomID : undefined,
                                    rules: [{ required: true, message: '请输入房间号' }],
                                })(
                                    <Select allowClear optionFilterProp="title"  showSearch placeholder="请选择房间号" ref={this.myRef1} onChange={this.handleOnSelect.bind(this, 1, 'locRoomDr')} onSelect={this.handelDirectorDr}>
                                        {this.state.options.roomNo && this.state.options.roomNo.map(item => {
                                            return <Option value={item.id} key={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>

                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="床位号"
                                {...formItemInput}
                            >
                                {getFieldDecorator('bedCBID', {
                                    initialValue: userInfo.bedCBID ? userInfo.bedCBID : undefined,
                                    rules: [{ required: true, message: '请输入床位号' }],
                                })(
                                    <Select allowClear optionFilterProp="title"	showSearch placeholder="请选择床位号" ref={this.myRef2} onChange={this.handleOnSelect.bind(this, 2, 'locBedDr')}>
                                        {this.state.options.bedNo && this.state.options.bedNo.map(item => {
                                            return <Option value={item.id} key={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col span={12}>
                            <Form.Item
                                label="楼号"
                                {...formItemInput}
                            >
                                {getFieldDecorator('bedBuildID', {
                                    initialValue: userInfo.bedBuildID ? userInfo.bedBuildID : undefined,
                                    //rules: [{ required: true, message: '请选择科室楼号' }]
                                })(
                                    <Select allowClear optionFilterProp="title"	showSearch placeholder="请选择科室楼号" ref={this.myRef3} onChange={this.handleOnSelect.bind(this, 3, 'locBuildDr')}>
                                        {this.state.options.build && this.state.options.build.map(item => {
                                            return <Option value={item.id} key={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>

                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="楼层"
                                {...formItemInput}
                            >
                                {getFieldDecorator('bedFloorID', {
                                    initialValue: userInfo.bedFloorID ? userInfo.bedFloorID : undefined,
                                    //rules: [{ required: true, message: '请选择科室楼层' }]
                                })(
                                    <Select allowClear optionFilterProp="title"	showSearch placeholder="请选择科室楼层" ref={this.myRef4} onChange={this.handleOnSelect.bind(this, 4, 'locFloorDr')}>
                                        {this.state.options.floor && this.state.options.floor.map(item => {
                                            return <Option value={item.id} key={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col span={12}>
                            <Form.Item
                                label="床位状态"
                                {...formItemInput}
                            >
                                {getFieldDecorator('bedStatusID', {
                                    initialValue: userInfo.bedStatusID ? userInfo.bedStatusID : this.state.options.defaultBedStatusDr,
                                    rules: [{ required: true, message: '请输入床位状态' }],
                                })(
                                    <Select placeholder="请选择床位状态"   ref={this.myRef5} onChange={this.handleOnSelect.bind(this, 5, 'bedStatus')}>
                                        {this.state.options.bedStatus && this.state.options.bedStatus.map(item => {
                                            return <Option value={item.id} key={item.id}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>

                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="类别"
                                {...formItemInput}
                            >
                                {getFieldDecorator('bedCatID', {
                                    initialValue: userInfo.bedCatID ? userInfo.bedCatID : this.state.options.defaultBedCatDr,
                                    rules: [{ required: true, message: '请输入类别' }],
                                })(
                                    <Select placeholder="请选择类别"  ref={this.myRef6} onChange={this.handleOnSelect.bind(this, 6, 'bedCat')}>
                                        {this.state.options.bedCat && this.state.options.bedCat.map(item => {
                                            return <Option value={item.id} key={item.id}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col span={12}>
                            <Form.Item
                                label="责任医生"
                                {...formItemInput}
                            >
                                {getFieldDecorator('bedResDocID', {
                                    initialValue: userInfo.bedResDocID ? userInfo.bedResDocID : undefined,
                                })(
                                    <Select allowClear optionFilterProp="title"	showSearch placeholder="请选择责任医生" ref={this.myRef7} onChange={this.handleOnSelect.bind(this, 7, 'locResDocDr')}>
                                        {this.state.options.resDoc && this.state.options.resDoc.map(item => {
                                            return <Option value={item.id} key={item.id} title={item.descripts + item.descriptsSPCode.toLowerCase()}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>

                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="责任护士"
                                {...formItemInput}
                            >
                                {getFieldDecorator('bedResNurID', {
                                    initialValue: userInfo.bedResNurID ? userInfo.bedResNurID : undefined,
                                })(
                                    <Select allowClear optionFilterProp="title"	showSearch placeholder="请选择责任护士" ref={this.myRef8} onChange={this.handleOnSelect.bind(this, 8, 'locResNurDr')}>
                                        {this.state.options.resNur && this.state.options.resNur.map(item => {
                                            return <Option value={item.id} key={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col span={12}>
                            <Form.Item label="生效日期：" {...formItemInput} style={{ padding: 0, margin: 0 }}>
                                {getFieldDecorator('bedStartDate', {
                                    initialValue: userInfo.bedStartDate  ? moment(userInfo.bedStartDate, 'YYYY-MM-DD') : moment(),
                                    // initialValue:this.state.startDate,
                                    rules: [{ required: true, message: '生效日期不能为空' }],
                                })(
                                    <DatePicker style={{ width: '100%' }} ref={this.myRef9} onChange={this.handleOnSelect.bind(this, 9, 'startDate')} />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="失效日期：" {...formItemInput} style={{ padding: 0, margin: 0 }}>
                                {getFieldDecorator('bedStopDate', {
                                    initialValue: userInfo.bedStopDate ? moment(userInfo.bedStopDate, 'YYYY-MM-DD') : undefined,
                                    // initialValue:moment(date,dayFormat),
                                    //initialValue: this.state.StopDate,
                                })(
                                    <DatePicker style={{ width: '100%' }} ref={this.myRef10} onChange={this.handleOnSelect.bind(this, 10, 'stopDate')} />
                                )}
                            </Form.Item>

                        </Col>
                        <Col span={12}>
                              <Form.Item
                                label="房间类型"
                                {...formItemInput}
                            >
                                 {getFieldDecorator('bedRoomTypeID', {
                                    initialValue: userInfo.bedRoomTypeID ? userInfo.bedRoomTypeID: undefined,
                                    rules: [{ required: true, message: '请选择房间类型' }],
                                    })(
                                    <Select  allowClear placeholder="请选择房间类型" ref={this.myRef11} onChange={this.handleOnSelect.bind(this, 11, 'roomTypeDr')}>
                                        {this.state.options.roomType && this.state.options.roomType.map(item => {
                                        return <Option value={item.id} key={item.id}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                    )}
                            </Form.Item> 

                        </Col>
                    </Row>
                </Form>
            </Modal>
            {/* <PublicModalTable
                onClickRowPublic={this.onClickRowDoctor}
                compilePage={this.compileDoctorPage}
                param={param} onRef={this.onRef}
            /> */}
        </div>
        )
    }
}
export default Form.create({ name: 'departmentfind_add' })(DepartmentFindAdd);
