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

import PartmentButton from "../../../components/PartmentButton";
import $perModal from '../../../utils/modal/perModal';
import "./less/depart.less";
import {
  systemComDepartGet, //通过ID获取部门功能
  systemComDepartUpdate //部门更新--编辑保存
} 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 EditDepartment extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open: this.props.open,
      departName: "", //部门名称
      departId: "", //部门Id
      perID: "", //新人员ID
      perIDName: "",//设置主管对应的名称
      oldPerID: "", //原部门主管人员ID
      parentDepartId: "", //上级部门ID
      seq:null,//排序序号
      DepartTree: this.props.treeData || [], //部门树
      checkedkeys: "",
    };
  }
  componentDidMount() {}
  componentWillReceiveProps(nextProps) {
    //console.log(nextProps, this.state, "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) {
      if (nextProps.departId === "-1" || nextProps.departId === undefined) {
        return;
      }
      this.setState({ departId: nextProps.departId });
      this.systemComDepartGet(nextProps.departId);
    }
  }
  //部门更新--编辑保存
  systemComDepartUpdate = values => {
    systemComDepartUpdate({
      departName: values.departName, //部门名称
      departId: this.state.departId, //部门Id
      perID: values.perID ? this.state.perID : "",
      oldPerID: this.state.oldPerID, //原部门主管人员ID
      parentDepartId: values.parentDepartId, //上级部门ID
      seq: values.seq
    }).then(
      response => {
        // console.log(
        //   response,
        //   "systemComDepartUpdate--response-部门更新--编辑保存"
        // );
        this.setState({ open: false, departId: "" });
        this.props.editSuccess(values.departName);
      },
      err => {
        console.log(err, "systemComDepartUpdate-err-部门更新--编辑保存");
      }
    );
  };

  // 通过ID获取部门功能
  systemComDepartGet = departId => {
    systemComDepartGet({ departId }).then(
      response => {
        // console.log(
        //   response,
        //   "systemComDepartGet--response- 通过ID获取部门功能"
        // );
        const { data } = response;
        const { setFieldsValue } = this.props.form;
        setFieldsValue({
          parentDepartId: data.parentDepartId || "",
          departName: data.departName || "",
          perID: data.oldPerName,
          seq: data.seq || null
        });
        this.setState({
          departName: data.departName || "", //部门名称
          departId: data.departId || "", //部门Id
          perID: data.oldPerID || "", //新人员ID
          oldPerID: data.oldPerID || "", //原部门主管人员ID
          checkedkeys: data.oldPerID || "", //原部门主管人员ID
          parentDepartId: data.parentDepartId || "", //上级部门ID
          perIDName: data.oldPerName || "", // 设置主管的名称
          seq: data.seq || null
        });
      },
      err => {
        console.log(err, "systemComDepartGet-err- 通过ID获取部门功能");
      }
    );
  };

  //保存编辑部门表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      // console.log(values, "handleSubmit-values");
      if (!err) {
        this.systemComDepartUpdate(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}
        placement="right"
        visible={this.state.open}
        destroyOnClose
        width={594}
        zIndex={11}
        onChange={open => {
          this.setState({ open });
          this.props.ok(open);
        }}
        onClose={()=>{
          this.setState({
            open:false
          });
        }}
      >
        <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", {
                  initialValue: this.state.departName,
                  rules: [
                    {
                      required: true,
                      message: "请输入"
                    },
                    {
                      // pattern: /[\u4e00-\u9fa5]/,
                      // pattern: /[\u4E00-\u9FA5A-Za-z]/,
                      message: "请输入汉字"
                    }
                  ]
                })(<Input placeholder="请输入" maxLength={30} />)}
              </FormItem>
              <FormItem {...formItemLayout} label="上级部门">
                {getFieldDecorator("parentDepartId", {
                  initialValue: this.state.parentDepartId,
                  rules: [
                    {
                      required: true,
                      message: "请选择"
                    }
                  ]
                })(
                  <TreeSelect
                    dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                    treeData={this.state.DepartTree}
                    placeholder="请选择上级部门"
                    treeDefaultExpandAll
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="设置主管">
                {getFieldDecorator("perID", {
                  initialValue: this.state.perIDName
                })(
                  <Input
                    onClick={() => {
                      $perModal({
                        type:"radio",
                        value: this.state.checkedkeys,
                        onOk: (values, close) => {
                          close();
                          if(values[0]) {
                            this.setState({
                              perID: values[0].perId,
                              checkedkeys: [values[0].perId]
                            });
                            setFieldsValue({perID: values[0].name});
                          }
                        }
                      });
                    }}
                    placeholder="请选择"
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="排序序号" extra={<span>排序大小：1~999</span>}>
                {getFieldDecorator("seq", {
                  initialValue: this.state.seq
                })(
                  <InputNumber min={1} max={999}/>
                )}
              </FormItem>
              <div style={{
                position: 'absolute',
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e8e8e8',
                padding: '10px 16px',
                textAlign: 'right',
                left: 0,
                background: '#fff',
                borderRadius: '0 0 4px 4px',
              }}>
                <Button
                  onClick={() => {
                    this.props.ok(false);
                    this.setState({ open: false, departId: "" });
                  }}
                >
                  取消
                </Button>
                <Button
                  style={{ marginLeft: 8 }}
                  type="danger"
                  onClick={() => this.props.delete()}
                >
                  删除
                </Button>
                <Button
                  style={{ marginLeft: 8 }}
                  type="primary"
                  htmlType="submit"
                >
                  保存
                </Button>
              </div>
            </Form>
          </div>
        </div>
      </Drawer>
    );
  }
}
