// 角色管理form页面
import React from 'react';
import {
    Form, Button, Col, Row, Input, Select, DatePicker, message, Switch
} from 'antd';
import Moment from 'moment';
import { $http } from '../../containers/config/https';
import { disposeData } from '../../tools';

const { Option } = Select;

const AddInvoiceMaintenance = Form.create()(
    // eslint-disable-next-line
    class extends React.Component {

        constructor (props) {
            super(props);
            this.myRef1 = React.createRef();
            this.myRef2 = React.createRef();
          }

        // 重置表单
        resetFields = () => {
            // console.log("触发了")
           this.props.form.resetFields(); //清空所有
        }
        resetFieldsNew = () => {
            // console.log("触发了")
           this.props.handleThis.resetUserInfo();
        }


        // 新增保存调的方法
        handelFunction(code, msg) {
            const { form: { validateFields } } = this.props;
            validateFields((errors, values) => {
                // 验证成功
                if (errors === null) {
                    let data = {
                        params: []
                    }
                    let obj = values;

                    if(obj.stDate){obj.stDate=obj.stDate.format('YYYY-MM-DD');}
                    if(obj.stopDate){ obj.stopDate=obj.stopDate.format('YYYY-MM-DD');}
                    if(obj.ifAssignInvNo){obj.ifAssignInvNo="Y"}
                    if(obj.ifPrint){obj.ifPrint="Y"}
                    let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
                    //let obj = JSON.parse(JSON.stringify(values));
                    obj.createUserDr = msg === '新增' ? user.userId : this.props.userInfo.CreateUserName;
                    obj.updateUserDr =  msg === '新增'? user.userId: this.props.userInfo.CreateUserName;
                    obj.id= msg === '新增' ? '' : this.props.userInfo.ID;
                    // 处理需要传递的obj
                    data.params.push(disposeData(obj));
                    $http.post('urlADS', this, {
                        code: code,
                        data: data,
                        success: function (res) { 
                            console.log(res);
                            if (+res.errorCode === 0) {
                              // 提示
                              message.success(msg + '成功');
                              // 新增或编辑成功重置form表单
                              this.resetFields();
                              // 刷新列表数据
                              this.props.handelThis.handleQuery();
                            }
                        },
                        error:function (error) {
                            message.error(msg + '失败：' + error);
                        }
                    })
                }
            });
          }





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

        changeEnter() {
            var inputs = document.getElementsByClassName('input');
            let _this = this;
            function init() {
                for(let i = 0; i < inputs.length; i++){
                    inputs[i].onkeydown = focus(_this, i)
                }
            }
            // console.log(inputs)
            var focus = function handle(_this, i) {
                return function(event) {
                    var next = (i + 1) < inputs.length ? i + 1 : 0;  // 判断是否为最后一个输入框，是则返回第一个，否则继续下一个
                    var eve = event ? event : window.event;
                    if (eve.keyCode === 13) {
                        // console.log(inputs[next].tagName)
                        if (inputs[next].tagName === 'INPUT') {
                            inputs[next].focus();    //获取焦点
                        } else if (inputs[next].tagName === 'DIV') {
                            // console.log(inputs[next])
                            if (inputs[next].id === 'DefaultMenuType') {
                                _this.myRef1.current.focus();
                            } else {
                                _this.myRef1.current.blur();
                            }
                        }
                    }
                }
            }
            init()
        }

        handleOnSelect = () => {
            // console.log('选中了')
            // console.log(this.myRef2)
            this.myRef2.current.focus();
        }

        handleOnBlur = () => {
            this.myRef2.current.focus();
        }

        componentDidUpdate() {
            this.changeEnter();
        }

        componentDidMount(){
            this.props.onRef(this);
        }

        render() {
            const formItemLayout = {
                labelCol: {span: 10},
                wrapperCol: {span: 14}
            };
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.props.userInfo ? this.props.userInfo : {};
            return (
                <div>
                    {/* hideRequiredMark--隐藏所有表单项的必选标记 initialValue--初始值 */}
                    <Form layout="vertical">
                        <Row gutter={16}>
                            <Col span={8}>
                                 <Form.Item label="发票类型代码">
                                 {getFieldDecorator('code', {
                                  initialValue:userInfo.Code,
                                 rules: [{ required: true, message: '请选择' }]
                                  })( <Input /> )}
                                 </Form.Item>
                            </Col>
                            <Col span={8}>
                               <Form.Item label="发票类型描述">
                                  {getFieldDecorator('descripts', {
                                  initialValue:userInfo.Descripts,
                                  rules: [{ required: true, message: '请选择' }]
                                  })(
                                <Input /> )}
                               </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={8}>
                                <Form.Item label="生效日期">
                                    {getFieldDecorator('stDate', {
                                        initialValue: userInfo.StartDate ? Moment(userInfo.StartDate, 'YYYY-MM-DD') : null,
                                        rules: [{ required: true, message: '请选择' }],
                                    })(
                                        <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item label="失效日期">
                                    {getFieldDecorator('stopDate', {
                                        initialValue: userInfo.StopDate ? Moment(userInfo.StopDate, 'YYYY-MM-DD') : null
                                    })(
                                        <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                             <Col span={8}>
                                <Form.Item label="打印模板">
                                    {getFieldDecorator('printTemplet', {
                                    initialValue:userInfo.PrintTemplet,
                                    })(<Input /> )}
                                </Form.Item>
                            </Col>   
                        </Row>
                        <Row gutter={16}>
                        <Col span={8}>
                             <Form.Item label="是否走号" {...formItemLayout}>
                                {getFieldDecorator('ifAssignInvNo', {valuePropName: 'checked',
                                    initialValue: userInfo.IfAssignInvNo === "Y" ? true : false, })(
                                        <Switch checkedChildren="是" unCheckedChildren="否" />
                                )}
                            </Form.Item>
                            </Col>
                               
                            <Col span={8}>
                                <Form.Item label="是否打印" {...formItemLayout}>
                                    {getFieldDecorator('ifPrint', {valuePropName: 'checked',
                                        initialValue: userInfo.IfPrint === "Y" ? true : false, })(
                                            <Switch checkedChildren="是" unCheckedChildren="否" />
                                    )}
                                </Form.Item>
                               
                            </Col>  
                        </Row>
                    </Form>
                    <div
                        style={{
                        textAlign: 'center',
                        marginBottom: '20px'
                        }}
                    >
                        <Button onClick={this.handelSave} type="primary" style={{ marginRight: 80 }}>
                            {this.props.flag === 'compile' ? '编辑' : '新增'}
                        </Button>
                        <Button onClick={this. resetFieldsNew} type="primary">
                            重置
                        </Button>
                    </div>
                </div>
            )
        }
    }
  );
export default AddInvoiceMaintenance;