// 主菜单form表单
import React from 'react';
import PropTypes from 'prop-types';
import { $http } from '../../containers/config/https';
import { disposeData } from '../../tools';
import { Drawer, Form, Input, Row, Col, Button, message, DatePicker, Select } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const FormItem = Form.Item;
const Option = Select.Option;


const FormHandel = Form.create()(
    // eslint-disable-next-line
    class extends React.Component {
        constructor(props){
            super(props);
            this.state = { 
                visible: false,
                selectRowId : '',
                medGroupId : props.selectGroupId,
            };
            this.userInfoData=[];
            this.myRef1 = React.createRef();
        }
      
        componentWillMount(){
            this.GetUserInfoData()
        }
        componentWillReceiveProps(nextProps){
            this.setState({
                selectGroupId: nextProps.selectGroupId,
            });
        }
        componentDidMount() {
            this.props.onRef(this);
        }

        GetUserInfoData = () =>{
            let data = {
                params: [{}]
            }
            $http.post("urlS",this, {
                code: "10004nzs",
                data: data,
                success: function (res) { 
                    if (+res.errorCode === 0) {
                        this.userInfoData=res.result
                    } else {
                        message.error('失败：' + res.errorMessage);
                    }
                }
            }) 
        }

        showDrawer = () => {
            this.setState({
                visible: true,
            });
        };

        onClose = () => {
            this.setState({
                    visible: false,
            }, () => {
                // 如果为编辑，则关闭后清除表单
                if (this.props.flag === 'compile') {
                    setTimeout(() => {
                        this.props.handelThis.resetUserInfo()
                    }, 500)
                }
            });
        };

      // 显示弹出层
      showModal = () => {
        this.setState({
            visible: true,
        });
      }
              // 关闭抽屉
              onClose = () => {
                this.setState({
                        visible: false,
                }, () => {
                    // 如果为编辑，则关闭后清除表单
                    if (this.props.flag === 'compile') {
                        setTimeout(() => {
                            this.props.handelThis.resetUserInfo()
                        }, 500)
                    }
                });
            };
            

      // 取消
      handleCancel = () => {
        this.setState({
            visible: false,
        }, () => {
            if (this.props.flag === 'compile') {
                this.props.handelThis.resetUserInfo()
            }
        });
      }
      
      // 重置表单
      resetFields() {
          //清空所有
        this.props.form.resetFields(); 
      }

      handelFunction = (code, msg) => {
        const { form: { validateFields } } = this.props;
            validateFields((errors, values) => {
                // 验证成功
                if (errors === null) {
                    let data = {
                        params: []
                    }
                    if(Object.getPrototypeOf(values.StartDate).constructor.name==='Moment'){
                        values.StartDate=values.StartDate.format('YYYY-MM-DD');
                    }
                    if(Object.getPrototypeOf(values.StopDate).constructor.name==='Moment'){
                        values.StopDate=values.StopDate.format('YYYY-MM-DD');
                    }
                    if(Object.getPrototypeOf(values.UpdateDate).constructor.name==='Moment'){
                        values.UpdateDate=values.UpdateDate.format('YYYY-MM-DD');
                    }
                    values.MedStaffDr=this.state.selectRowId
                    //obj.ID = this.props.userInfo.ID
                    values.MedGroupID =this.props.handelThis.state.selectGroupId;
                    let obj = JSON.parse(JSON.stringify(values));
                    //obj.UpdateUserDr = this.props.flag === 'add' ? 1 : this.props.userInfo.UpdateUserDr;
                    obj.UpdateUserDr = "1";
                    if (this.props.flag === 'compile') {
                        obj.ID = this.props.userInfo.ID;
                        obj.MedStaffDr = this.props.userInfo.medStaffDr;
                    }
                    if(obj.IPFlag === "Null"){obj.IPFlag = ""}
                    if(obj.OPFlag === "Null"){obj.OPFlag = ""}
                    if(obj.LeaderFlag === "Null"){obj.LeaderFlag = ""}
                    // 处理需要传递的obj
                    data.params.push(disposeData(obj));
                    $http.post('urlADS', this, {
                        code: code,
                        data: data,
                        success: function (res) { 
                            if (+res.errorCode === 0) {
                                // 关闭抽屉
                                this.onClose();
                                // 提示
                                message.success(msg + '成功');
                                // 刷新列表数据
                                this.props.handelThis.handleQuery();
                                // 新增或编辑成功重置form表单
                                this.resetFields();
                                this.setState({
                                    selectRowId : '',
                                })
                            }
                        }
                    })
                }
            });
      }

      // 保存
      handelSave = () => {
        let { flag } = this.props;
        if (flag === 'add') {
            this.handelFunction('10002nzs', '新增')
        } else if (flag === 'compile') {
            this.handelFunction('10006nzs', '编辑')
        }
       }

       changeValue =(value) =>{
           if(value === "Y") return "Yes"
           else if(value === "N") return "No"
           else return null
       }
       onSelectChange=(value)=>{
           this.setState({
               selectRowId : value,
           })
       }
      render() {
        const { getFieldDecorator } = this.props.form;
        let userInfo = this.props.userInfo? this.props.userInfo : {}
        let selectIPFlag = "Null";
        let selectMedStaffDr = "Null";
        let selectLeaderFlag = "Null";
        if (this.props.flag === 'compile') {
            selectMedStaffDr = this.changeValue(userInfo.oPFlag);
            selectIPFlag = this.changeValue(userInfo.iPFlag);
            selectLeaderFlag = this.changeValue(userInfo.leaderFlag);
            this.state.selectRowId = userInfo.medStaffDesc;
        }
        return (
            <Drawer
            title={this.props.title + "数据明细"}
            width={620}
            onClose={this.onClose}
            visible={this.state.visible}
            style={{
                overflow: 'auto',
                height: 'calc(100% - 108px)',
                paddingBottom: '108px',
            }}
        >
        <Form layout="vertical">
            <Row gutter={16}>
                <Col span={12}>
                    <FormItem label="医务人员">
                        {getFieldDecorator('MedStaffDr', {
                            initialValue:this.state.selectRowId=""?null:this.state.selectRowId,
                            rules: [{ required: true, message: '医务人员不能为空' }],
                        })(
                            <Select
                                showSearch
                                onChange={this.onSelectChange}
                                style={{ width: '100%' }}
                                //placeholder="Select a person"
                                optionFilterProp="children"
                                //disabled={this.state.selectRowId?true:false}
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            >
                                { 
                                this.userInfoData.map(d => <Option key={d.id} value={d.id}>{d.descript}</Option>) 
                                }   
                            </Select>
                        )}
                    </FormItem>
                </Col>
                <Col span={12}>
                    <FormItem label="门诊标志">
                        {getFieldDecorator('OPFlag', {
                            initialValue:selectMedStaffDr,
                            //rules: [{ required: true, message: '描述不能为空' }],
                        })(
                            <Select>
                                <Option key="Yes" value="Yes">Yes</Option>
                                <Option key="No" value="No">No</Option>
                                <Option key="Null" value="Null"> </Option>
                            </Select>
                        )}
                    </FormItem>
                </Col>
            </Row>
            <Row gutter={16}>
                <Col span={12}>
                    <FormItem label="住院标志">
                        {getFieldDecorator('IPFlag', {
                            initialValue:selectIPFlag,
                        })(
                            <Select>
                                <Option key="Yes" value="Yes">Yes</Option>
                                <Option key="No" value="No">No</Option>
                                <Option key="Null" value="Null"> </Option>
                            </Select>
                        )}
                    </FormItem>
                </Col>
                <Col span={12}>
                    <FormItem label="组长标志">
                        {getFieldDecorator('LeaderFlag', {
                            initialValue:selectLeaderFlag,
                        })(
                            <Select>
                                <Option key="Yes" value="Yes">Yes</Option>
                                <Option key="No" value="No">No</Option>
                                <Option key="Null" value="Null"> </Option>
                            </Select>
                        )}
                    </FormItem>
                </Col>
                
            </Row>
            <Row gutter={16}>
            <Col span={12}>
                    <FormItem label="开始日期">
                        {getFieldDecorator('StartDate', {
                            //initialValue : moment(new Date(), 'YYYY-MM-DD'),
                            initialValue:userInfo.startDate? moment(userInfo.startDate, 'YYYY-MM-DD') : moment(new Date(), 'YYYY-MM-DD'),
                            rules: [{ required: true, message: '开始日期不能为空' }],
                        })(
                            //<Input placeholder="请输入链接地址" className='input' />
                            <DatePicker />
                        )}
                    </FormItem>
                </Col>
                <Col span={12}>
                    <FormItem label="失效日期">
                        {getFieldDecorator('StopDate', {
                            initialValue:userInfo.stopDate? moment(userInfo.stopDate, 'YYYY-MM-DD') : null,
                        })(
                            <DatePicker />
                        )}
                    </FormItem>
            </Col>
            </Row>
            <Row gutter={16}>
                <Col span={12}>
                    <FormItem label="更新日期">
                        {getFieldDecorator('UpdateDate', {
                            initialValue:userInfo.updateDate? moment(userInfo.updateDate, 'YYYY-MM-DD') : moment(new Date(), 'YYYY-MM-DD'),
                        })(
                            <DatePicker onChange={this.onChange} />
                        )}
                    </FormItem>
                </Col>
                <Col span={12}>
                    <FormItem label="更新人">
                        {getFieldDecorator('UpdateUserDr', {
                            initialValue:userInfo.UpdateUserDr,
                        })(
                            <Input placeholder="请输入" className='input' disabled/>
                        )}
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <div
            style={{
                position: 'absolute',
                left: 0,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                padding: '10px 16px',
                background: '#fff',
                textAlign: 'right',
            }}
        >
            <Button onClick={this.onClose} style={{ marginRight: 8 }}>
                返回
            </Button>
            <Button onClick={this.handelSave} type="primary">
                保存
            </Button>
        </div>
      </Drawer>
        );
      }
    }
  );
export default FormHandel;

FormHandel.propTypes = {
  // 验证userInfo的属性
  userInfo: PropTypes.object
}