// 添加分组
import React from 'react';
import { Select, Input, Row, Col, Button, message, Form, DatePicker } from 'antd';
import { $http } from '../../../containers/config/https';
import Moment from 'moment';
import DatePickerFormat from '../../../components/datePicker/DatePickerFormat';


// 组件const
const { Option } = Select;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
};


class PersGroupingModal extends React.Component {
    constructor( props ) {
        super(props)
 
        this.state = {
            hospitalData: [], // 医院集合
            deptDrData: [], // 科室集合
            defaultHos: JSON.parse(window.sessionStorage.userData).hospID,   // 医院
            medGroupId: '', // 回显id
            persGroupingDate: '', // 回显数据
            disabled: true, // 不可选
        };

    }

    componentDidMount() {

        // 医院列表加载
        this.searachHospDr()

        // 科室加载
        this.hospDrChange(this.state.defaultHos)

        if (this.props.persGroupingDate && JSON.stringify(this.props.persGroupingDate) !== "{}") {
            let data = this.props.persGroupingDate
            this.callbackData(data) //回显数据

        }
    }

    // 实时更新
    componentWillReceiveProps(nextProps) {
        const { persGroupingDate } = this.state
        const newdata = nextProps.persGroupingDate

        if (JSON.stringify(newdata) === "{}") {
            this.setState({
                disabled: false,// 不可选
            })
        } else {
            this.setState({
                disabled: true,// 不可选
            })
        }

        if (persGroupingDate !== newdata) {
            this.callbackData(nextProps.persGroupingDate) //回显数据
        }

    }

    //回显数据
    callbackData = (data) => {
        console.log(data)
        this.hospDrChange(data.hospID ? data.hospID : this.state.defaultHos) //科室
        this.setState({
            persGroupingDate: data,
            medGroupId: data.medGroupID, //  回显数据
        })


        this.props.form.setFieldsValue({
            medGrpHospId: data.hospID || this.state.defaultHos, //所属医院
            medGrpLocId: data.locID || '', //所属科室
            medGrpDescripts: data.medGroupDesc || '', //人员分组
            medGrpStDate: data.medGroupStartDate ? (data.medGroupStartDate !== '' ? Moment(data.medGroupStartDate, 'YYYY-MM-DD') : undefined) : undefined,        //生效日期//生效日期
            medGrpSpDate: data.medGroupEndDate ? (data.medGroupEndDate !== '' ? Moment(data.medGroupEndDate, 'YYYY-MM-DD') : undefined) : undefined,        //生效日期 //失效日期
        });

    }

    // 医院列表加载
    searachHospDr = () => {
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        var data = {
            params: [{
                hospID: '', // 医院id
                logonGroupID: user.groupID, //登录角色id
                logonHospID: user.hospID, // 登录医院id
            }]
        }
        $http.post('urlS', this, {
            code: "01040001",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        hospitalData: res.depDoctor, //  医院列表
                    })
                }
            }
        });
    }

    // 医院切换
    hospDrChange = (value) => {
        this.props.form.setFieldsValue({
            medGrpLocId: '',
        });

        this.setState({
            deptDrData: [], //清空下拉框
        })

        if (!value) {
            return false
        }

        let data = {
            "params": [{
                'hospID': value,
            }]
        };
        $http.post('urlDeault', this, {
            code: "04020008",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        deptDrData: res.result.Data, // 科室集合
                    })
                }
            }
        });
    }



    // 保存用户信息表单提交
    handleSubmit = (e) => {

        e.preventDefault();

        this.props.form.validateFields((err, values) => {
            if (!err) {  //!err

                let data = {
                    "params": [{
                        hospID: values.medGrpHospId || '', //所属医院
                        locID: values.medGrpLocId || '', //所属科室
                        medGroupDesc: values.medGrpDescripts || '', //人员分组
                        medGroupStartDate: values.medGrpStDate ? Moment(values.medGrpStDate).utcOffset(480).format('YYYY-MM-DD') : '',        //生效日期//生效日期
                        medGroupEndDate: values.medGrpSpDate ? Moment(values.medGrpSpDate).utcOffset(480).format('YYYY-MM-DD') : '',        //生效日期 //失效日期
                        updateUserID: JSON.parse(window.sessionStorage.userData).userID, //修改人
                        medGroupID: this.state.medGroupId || '', //回显id
                    }]
                };
                $http.post('urlADS', this, {
                    code: "01040030",
                    data: data,
                    success: function (res) {
                        let errorCode = res.errorCode;
                        if (errorCode === '0') {
                            this.props.handleOk();
                            message.success(res.errorMessage);
                        }
                    }
                });
            }

        });
    }




    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form layout="vertical" className="depart-form" onSubmit={this.handleSubmit}  >
                <Row>
                    <Col span={24} >

                        <Form.Item label="所属医院："  {...formItemLayout} >
                            {getFieldDecorator('medGrpHospId', {
                                initialValue: this.state.defaultHos,
                                rules: [{ required: true, message: '请输入所属医院' }],
                            })(
                                <Select allowClear showSearch optionFilterProp="title1" onChange={(event) => { this.hospDrChange(event) }} placeholder="所属医院" disabled={this.state.disabled} >
                                    {this.state.hospitalData.map(item => <Option title={item.descripts} title1={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={24} >
                        <Form.Item label="所属科室："  {...formItemLayout} >
                            {getFieldDecorator('medGrpLocId', {
                                initialValue: '',
                                rules: [{ required: true, message: '请输入所属科室' }],
                            })(
                                <Select allowClear showSearch optionFilterProp="title1" placeholder="所属科室" disabled={this.state.disabled}>
                                    {this.state.deptDrData.map(item => <Option title={item.descripts} title1={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={24} >
                        <Form.Item label="分组名称："  {...formItemLayout} >
                            {getFieldDecorator('medGrpDescripts', {
                                initialValue: '',
                                rules: [{ required: true, message: '请输入分组名称' }],
                            })(
                                <Input allowClear placeholder="分组名称" className='input' />
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={24} className="dpW100">
                        <Form.Item label="生效日期："  {...formItemLayout} >
                            {getFieldDecorator('medGrpStDate', {
                                initialValue: undefined,
                                rules: [{ required: true, message: '请输入生效日期' }],
                            })(
                                <DatePickerFormat />
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={24} className="dpW100">
                        <Form.Item label="失效日期："  {...formItemLayout} >
                            {getFieldDecorator('medGrpSpDate', {
                                initialValue: undefined,
                            })(
                                <DatePickerFormat />
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Row >
                    <Col span={24}>
                        <Row style={{ width: '100%', textAlign: 'center', marginBottom: '10px' }}>
                            <Button onClick={this.handleSubmit} style={{ marginRight: '15px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存</Button>
                        </Row>
                    </Col>
                </Row>
            </Form>
        )
    }
}

const PersGroupingModalFrom = Form.create()(PersGroupingModal);

export default PersGroupingModalFrom