import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AmosValidate } from './../../common/utils/processor';
// import './../common/formStyle.scss';
// import './style/index.scss';
import { Form,Input,Row,Col,TreeSelect,Radio } from 'amos-antd';
import { Select } from 'amos-framework';
import { textLengthValidate } from './../../common/utils/validate';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const userNameText = '用户名';
const nameText = '姓名';
const statusText = '用户状态';
const companyIdText = '所属单位';
const departmentIdText = '所属部门';
const roleIdText = '角色';
const emailText = 'Email';
const mobileText = '手机';
const telephoneText = '固定电话';

const statusOptions = [
  {name: 'enable', value: 0, text: '启用'},
  {name: 'disable', value: 1, text: '禁用'}
];
const nameErrorText = '用户名不能为空！';
const otherNameErrorText = '姓名不能为空！';
const companyErrorText = '所属单位不能为空！';
const roleErrorText = '角色不能为空！';

const dataToTree = (dataList = []) => {
  dataList.map((data)=>{
    data.label = data.text;
    data.key = data.id;
    data.value = data.id;
    if(data.children){
      dataToTree(data.children);
    }
  });
};

/**
 * 用户编辑和新建内容
 * @class UserAddEdit
 * @extends {Component}
 */
class UserAddEdit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      companyList: [],
      selectDepartment: '',
      reset: false
    };
  }

  componentWillReceiveProps (nextProps) {
    let {user} = nextProps;
    if(!this.props.user || this.props.user.id != user.id) {
      this.getOrgData(user);
      this.props.setHandleReset(()=> {
        this.setState({reset: false});
      });

    }
  }

  /**
   * 初始化
   */
  componentDidMount() {
    this.getRole();
    this.props.superiorUnitAction();
    this.props.setHandleReset(()=> {
      this.setState({reset: false});
    });
    // this.getOrgData();
  }

  getRole = () => {
    this.props.getAllRoleAction();
  }

  getOrgData = (user) => {
    let {company} = user;

    company && this.getDepartment(company.id);
  }

  getDepartment = (id) => {
    this.props.getDepartmentByCompanyAction(id);
  }

  /**
   * 校验用户ID
   */
  checkId = (rule, value, callback) => {
    if(value && !AmosValidate.isNum(value)) {
      callback('ID只能是数字格式的！');
    } else {
      callback();
    }
  }

  /**
   * 校验手机号
   */
  checkMobile = (rule, value, callback) => {
    if(value && !AmosValidate.isMobile(value)) {
      callback('请输入正确的手机号格式！');
    } else {
      callback();
    }
  }

  /**
   * 校验固定电话
   */
  checkTelephone = (rule, value, callback) => {
    if(value && !AmosValidate.isPhone(value)) {
      callback('请输入正确的固定电话格式！');
    } else {
      callback();
    }
  }

  /**
   * 校验邮箱
   */
  checkEmail = (rule, value, callback) => {
    if(value && (!AmosValidate.isEmail(value) || value.length > 25)) {
      callback('请输入正确的邮箱格式！');
    } else {
      callback();
    }
  }


  /**
   * 校验原密码
   */
  checkPassword = (rule, value, callback) => {
    if(value && !AmosValidate.isPassword(value)) {
      callback('请输入正确的密码格式！');
    } else {
      callback();
    }
  }

  /**
   * 校验重复密码
   */
  checkRePassword = (rule, value, callback) => {
    const {getFieldValue} = this.props.parentform;
    if(value && value !== getFieldValue('password')) {
      callback('两次输入密码不一致！');
    } else {
      callback();
    }
  }
  render() {
    const {user,parentform,submit,isEdit,departmentTreeData,allRole,superiorCompanyList} = this.props;
    let {userName,enabled,company,department,role,mobile,email,name,telephone} = user;
    let companyId = company && company.id ? company.id + '' : null;
    let departmentId = department ? department.id : null;
    let roleId = role ? role.id : null;
    const {getFieldProps} = parentform;
    const userNameProps = getFieldProps('userName', {
      initialValue: userName == '' ? undefined : userName,
      rules: [
          {required: true, message: nameErrorText},
          {validator: textLengthValidate(255, 2)}
      ]
    });
    const nameProps = getFieldProps('name', {
      initialValue: name == '' ? undefined : name,
      rules: [
          {required: true, message: otherNameErrorText},
          {validator: textLengthValidate(255, 2)}
      ]
    });
    const mobileProps = getFieldProps('mobile', {
      initialValue: mobile == '' ? null : mobile,
      rules: [{validator: this.checkMobile}]
    });
    const telephoneProps = getFieldProps('telephone', {
      initialValue: telephone == '' ? null : telephone,
      rules: [{validator: this.checkTelephone}]
    });
    const emailProps = getFieldProps('email', {
      initialValue: email == '' ? null : email,
      rules: [{validator: this.checkEmail}]
    });
    const companyProps = getFieldProps('companyId', {
      initialValue: companyId,
      rules: [{required: true, message: companyErrorText}],
      onChange: (value)=>{this.getDepartment(value);this.setState({reset: true});parentform.resetFields(['departmentId']);}
    });
    const departmentIdProps = getFieldProps('departmentId', {
      initialValue: this.state.reset ? undefined : (typeof (departmentId) == 'number' ? '' + departmentId : null)
    });
    const roleIdProps = getFieldProps('roleId', {
      initialValue: roleId ? roleId + '' : undefined,
      rules: [{required: true, message: roleErrorText}]
    });
    const enabledProps = getFieldProps('enabled', {
      initialValue: enabled ? statusOptions[0].name : statusOptions[1].name
    });
    const passwordProps = getFieldProps('password', {
      initialValue: null,
      rules: [
         {required: isEdit,  message: '请输入密码'},
         {validator: this.checkPassword}
      ]
    });
    const rePasswordProps = getFieldProps('rePassword', {
      initialValue: null,
      rules: [
        {required: isEdit,  message: '请输入确认密码'},
        {validator: this.checkRePassword}
      ]
    });
    const formItemLayout = {
      labelCol: {span: 7},
      wrapperCol: {span: 16}
    };
    const otherLayout = {
      labelCol: {span: 3},
      wrapperCol: {span: 16}
    };
    let allowClear = true;
    return (
      <div className='user-add-edit amos-grid-from'>
        <Form inline onSubmit={submit}>
          <Row>
            <Col span={12}>
              <FormItem label={userNameText} {...formItemLayout}>
                <Input className='amos-grid-form-input' {...userNameProps} style={{width: 240}} />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label={nameText} {...formItemLayout}>
                <Input className='amos-grid-form-input' {...nameProps} style={{width: 240}} />
              </FormItem>
            </Col>
          </Row>
          {
            // <Row>
            //   <Col span={12}>
            //     <FormItem label={mobileText} {...formItemLayout}>
            //       <Input className='amos-grid-form-input' {...mobileProps} style={{width: 240}} />
            //     </FormItem>
            //   </Col>
            //   <Col span={12}>
            //     <FormItem label={telephoneText} {...formItemLayout}>
            //       <Input className='amos-grid-form-input' {...telephoneProps} style={{width: 240}} />
            //     </FormItem>
            //   </Col>
            // </Row>
        }
          {/*}
          <Row>
            <Col span={12}>
              <FormItem label={emailText} {...formItemLayout}>
                <Input className='amos-grid-form-input' {...emailProps} style={{width: 240}} />
              </FormItem>
            </Col>
          </Row>
          */}
          <hr />
          <Row>
            <Col span={12}>
              <FormItem label={companyIdText} {...formItemLayout}>
                <TreeSelect
                  instanceId="user-company"
                  showSearch
                  className='amos-grid-form-select'
                  style={{width: 240}}
                  dropdownStyle={{maxHeight: 250, overflow: 'auto'}}
                  treeData={superiorCompanyList}
                  placeholder='所有单位'
                  notFoundContent='无匹配结果'
                  treeDefaultExpandAll
                  treeNodeFilterProp='title'
                  {...companyProps}
                />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label={departmentIdText} {...formItemLayout}>
                <TreeSelect instanceId="user-department" {...departmentIdProps} allowClear={allowClear} showSearch optionFilterProp="children" treeNodeFilterProp='title' dropdownStyle={{maxHeight: 300, overflow: 'auto'}} style={{width: 240}}  treeData={departmentTreeData} notFoundContent='无匹配结果'/>
              </FormItem>
            </Col>
          </Row>
          {
            isEdit ? (
              <Row>
                <Col span={12}>
                  <FormItem label='密码' {...formItemLayout}>
                    <Input className='amos-grid-form-input' style={{width: 0,height: 0,padding: 0,border: 0,position: 'absolute'}} />
                    <Input className='amos-grid-form-input' type='password'  {...passwordProps} style={{width: 240}}  />
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label='确认密码' {...formItemLayout}>
                    <Input className='amos-grid-form-input' type='password' {...rePasswordProps} style={{width: 240}} />
                  </FormItem>
                </Col>
              </Row>
            ) : null
          }
          <Row>
            <Col span={12}>
              <FormItem label={roleIdText} {...formItemLayout}>
                <Select instanceId="user-role" className='amos-grid-form-select'   showSearch optionFilterProp="children" {...roleIdProps} style={{width: 240, height: '32px'}} >
                {
                  allRole.map(role=>(<Option key={`${role.id}option`} value={role.id + ''}>{role.name}</Option>))
                }
                </Select>
              </FormItem>
            </Col>
          </Row>
          <hr />
          <Row>
            <FormItem label={statusText} {...otherLayout}>
              <RadioGroup {...enabledProps} style={{width: 240}}>
                {
                  statusOptions.map(e=>(<Radio key={`${e.name}Radio`} value={e.name}>{e.text}</Radio>))
                }
              </RadioGroup>
            </FormItem>
          </Row>
        </Form>
      </div>
    );
  }
}

UserAddEdit.propTypes = {
  user: PropTypes.object,//用户信息对象
  submit: PropTypes.func,//保存事件回调
  cancel: PropTypes.func,//取消事件回调
  getDepartmentByCompanyAction: PropTypes.func,
  parentform: PropTypes.any,
  superiorUnitAction: PropTypes.func,
  allRole: PropTypes.array,
  superiorCompanyList: PropTypes.any,
  getAllRoleAction: PropTypes.func,
  departmentTreeData: PropTypes.array,
  isEdit: PropTypes.bool
};

UserAddEdit.defaultProps = {
  departmentTreeData: [],
  allRole: [],
  superiorCompanyList: [],
  user: {identificationId: '',userName: '',enabled: true,company: '',department: {},role: {},mobile: '',password: '',email: ''}
};

export default UserAddEdit;
