import React, { Component } from 'react';
import { connect } from 'dva';
import Drawer from 'react-motion-drawer';
import { Form, Input, Button, TreeSelect } from 'antd';

import PartmentButton from '../../../components/PartmentButton';
import $perModal from '../../../utils/modal/perModal';
import './less/depart.less';
import {
  systemComDepartSave //部门新增-添加子部
} from '../../../services/api';

const FormItem = Form.Item;
const style = {
  background: '#F9F9F9',
  boxShadow: '0 2px 11px 0 rgba(15, 113, 255, 0.2)'
};
const drawerProps = {
  overlayColor: 'rgba(0,0,0,0)',
  drawerStyle: style
};
// const { MenuItemGroup } = Menu;

@connect(state => ({
  profile: state.profile
}))
@Form.create()

/**
 * 部门管理组件
 */
export default class AddDepartment extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open: this.props.open,
      perID: '',
      perLabel:'',
      DepartTree: this.props.treeData || [], //部门树
      departId: this.props.departId
    };
  }
  componentDidMount() {}
  componentWillReceiveProps(nextProps) {
    // console.log(nextProps, "componentWillReceiveProps-nextProps");
    if (
      JSON.stringify(this.state.DepartTree) !==
      JSON.stringify(nextProps.treeData)
    ) {
      this.setState({ DepartTree: nextProps.treeData });
    }
    if (nextProps.open !== this.state.open) {
      this.setState({ open: nextProps.open });
    }
    if (nextProps.departId !== this.state.departId) {
      const { setFieldsValue } = this.props.form;
      setFieldsValue({ parentDepartId: nextProps.departId });
      this.setState({ departId: nextProps.departId });
    }
  }
  //部门新增-添加子部门
  systemComDepartSave = values => {
    systemComDepartSave({
      departName: values.departName,
      perID: values.perID ? this.state.perID : '',
      parentDepartId: values.parentDepartId
    }).then(
      response => {
        console.log(
          response,
          'systemComDepartSave--response-部门新增-添加子部门'
        );
        this.props.addSuccess();
        this.setState({ open: false });
        this.props.ok(false);
        this.props.form.setFieldsValue({ perID: '', departName: '' });
      },
      err => {
        console.log(err, 'systemComDepartSave-err-部门新增-添加子部门');
      }
    );
  };

  //保存编辑部门表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values, 'handleSubmit-values');
      if (!err) {
        this.systemComDepartSave(values);
        console.log('Received values of form: ', values);
      }
    });
  };

  render() {
    const { getFieldDecorator, setFieldsValue } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };
    return (
      <Drawer
        {...drawerProps}
        right
        open={this.state.open}
        noTouchClose
        width={594}
        zIndex={2}
        onChange={open => {
          this.setState({ open });
          this.props.ok(open);
        }}
      >
        <div
          style={{
            backgroundColor: '#fff',
            width: '100%',
            height: '100%'
          }}
          className="edit-department"
        >
          <header className="edit-header">
            <h2>新增部门</h2>
          </header>
          <div className="edit-form">
            <Form
              onSubmit={this.handleSubmit}
              style={{ marginTop: 24 }}
              className="edit-form"
            >
              <FormItem {...formItemLayout} label="部门名称">
                {getFieldDecorator('departName', {
                  rules: [
                    {
                      required: true,
                      message: '请输入'
                    },
                    // {
                    //   pattern: /[\u4e00-\u9fa5]/,
                    //   message: '请输入汉字'
                    // }
                  ]
                })(<Input placeholder="请输入" maxLength={30} />)}
              </FormItem>
              <FormItem {...formItemLayout} label="上级部门">
                {getFieldDecorator('parentDepartId', {
                  initialValue: this.state.departId,
                  rules: [
                    {
                      required: true,
                      message: '请选择'
                    }
                  ]
                })(
                  <TreeSelect
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={this.state.DepartTree}
                    placeholder="请选择上级部门"
                    treeDefaultExpandAll
                    onChange={this.onChange}
                  />
                )}
              </FormItem>
              {/* {console.log(this.state.perLabel)} */}
              <FormItem {...formItemLayout} label="设置主管">
                {getFieldDecorator('perID', {
                  initialValue:this.state.perLabel
                })(
                  <Input
                    onClick={() => {
                      $perModal({
                        type: 'radio',
                        value: this.state.perID,
                        onOk: (values, close) => {
                          close();
                          if(values[0]) {
                            this.setState({
                              perID: values[0].perId,
                              perLabel: values[0].name,
                            }, () => {
                              setFieldsValue({ perID: values[0].name });
                            });
                          }
                        }
                      });
                    }}
                    placeholder="请选择"
                  />
                )}
              </FormItem>
              
              <div className="edit-option">
                <Button
                  onClick={() => {
                    this.props.ok(false);
                    setFieldsValue({ perID: '', departName: '' });
                  }}
                >
                  取消
                </Button>
                <Button
                  type="primary"
                  style={{ marginLeft: 8 }}
                  htmlType="submit"
                >
                  保存
                </Button>
              </div>
            </Form>
          </div>
        </div>
      </Drawer>
    );
  }
}
