import React, { Component } from 'react';
import PropTypes from 'prop-types';
import GridButton from './../../common/btns/GridButton';
import SimpleModal from './../../common/modal/SimpleModal';
import UserAddEdit from './UserAddEdit';
import {objOfStrPropTrim} from './../../common/utils/validate';
import {Modal,Form} from 'amos-antd';
const createForm = Form.create();
/**
 * 用户信息编辑
 * @class EditUser
 * @extends {Component}
 */
class EditUser extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      user: {},
      selectId: -1,
      handleReset: () => {}
    };
  }

  setHandleReset = (handleReset) => {
    this.setState({handleReset: handleReset})
  }

  onClick = () => {
    let {selectRows} = this.props;
    if(selectRows.length == 0){
      Modal.warning({
        title: '提示',
        content: '请先选中要编辑的用户。'
      });
    } else {
      if(selectRows.length > 1){
        Modal.warning({
          title: '提示',
          content: '一次只能编辑一个用户'
        });
      } else {
        if(selectRows[0].userName === 'admin' && selectRows[0].role.name === 'admin'){
          Modal.warning({
            title: '提示',
            content: '不能操作管理员用户'
          });
        } else {
          this.props.getUserByIdAction(selectRows[0].id);
          this.setState({visible: true,selectId: selectRows[0].id});
        }
      }
    }
  }

  handleSave = (obj) => {
    obj.id = this.state.selectId;
    this.props.userEditAction(obj);this.handCancel();
  }

  handCancel = () => {
    this.props.form.resetFields();
    this.setState({visible: false, selectId: ''});
    this.state.handleReset();
  }
  /**
   * 保存按钮事件
   */
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((errors, values) => {
      if(errors) {
        return;
      }
      values.enabled =  values.enabled == 'enable';
      values = objOfStrPropTrim(values);
      this.handleSave(values);
    });
  }

  render() {
    let {text,form,userInfo} = this.props;
    let isEdit = false;
    return (
      <span>
        <GridButton text={text} color='#FFF' icon='edit' onClick={this.onClick} />
        <SimpleModal title='编辑用户' visible={this.state.visible} onOk={this.handleSubmit} onCancel={this.handCancel}  width={685} >
          <UserAddEdit user={userInfo.user || {}} isEdit={isEdit} submit={this.handleSubmit} parentform={form} {...this.props} setHandleReset={this.setHandleReset} />
        </SimpleModal>
      </span>
    );
  }
}

EditUser.propTypes = {
  text: PropTypes.string,
  reload: PropTypes.func,
  selectRows: PropTypes.array,
  imgUrl: PropTypes.any,
  getUserByIdAction: PropTypes.func,
  userInfo: PropTypes.object,
  userEditAction: PropTypes.func,
  form: PropTypes.any
};

EditUser.defaultProps = {
  selectRows: [],
  userInfo: {}
};

export default createForm(EditUser);
