import React, { Component } from "react";
import { Menu, message, Modal, Tree } from "antd";
import { WeaInputSearch } from "ecCom";
import { i18n } from "../../../public/i18n";
import NewAndEditDialog from "../../NewAndEditDialog";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import "../index.less";

const confirm = Modal.confirm;
const TreeNode = Tree.TreeNode;

@inject("officeManageStore")
@observer
class LeftTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      expandedKeys: [],
      treeData: [],
      copyTree: [],
      copyExpandedKeys: [],
      searchValue: "",
      rightClickNodeTreeItem: null
    };
  }

  componentDidMount() {
    this.getTreeData();
    document.addEventListener("click", this.handleClick);
  }

  componentWillUnmount() {
    document.removeEventListener("click", this.handleClick);
  }

  componentWillReceiveProps(nextProps) {
    if (
      nextProps.deleteOfficeClassifyFlag !== this.props.deleteOfficeClassifyFlag
    ) {
      const { officeManageStore } = this.props;
      const { officeClassifyId } = officeManageStore;
      this.handleDelete(officeClassifyId);
    }
  }

  getTreeData = () => {
    const { officeManageStore } = this.props;
    officeManageStore.getTreeData().then(res => {
      const { code, data, msg } = res;
      if (code === 200) {
        let cp = JSON.stringify([data]);
        this.setState({
          treeData: [data],
          expandedKeys: this.expandedKeysFun([data]),
          copyTree: cp,
          copyExpandedKeys: []
        });
      } else {
        message.error(res.msg);
      }
    });
  };

  handleClick = () => {
    this.setState({ rightClickNodeTreeItem: null });
  };
  onSelect = node => {
    const { officeManageStore } = this.props;
    const [postId] = node;
    const officeId = !postId
      ? officeManageStore.officeClassifyId
      : postId !== "-1" ? postId : "";
    officeManageStore.setOfficeClassifyId(officeId);
    officeManageStore.getPostInfoTable(officeId);
    this.setState({
      rightClickNodeTreeItem: null
    });
  };

  treeNodeonRightClick = e => {
    this.setState({
      rightClickNodeTreeItem: {
        pageX: e.event.pageX,
        pageY: e.event.pageY,
        id: e.node.props["eventKey"],
        categoryName: e.node.props["data-title"]
      }
    });
  };

  arrayTreeFilter = (data, predicate, filterText) => {
    const nodes = data;
    if (!(nodes && nodes.length)) {
      return;
    }
    const newChildren = [];
    for (const node of nodes) {
      if (predicate(node, filterText)) {
        newChildren.push(node);
        node.children = this.arrayTreeFilter(
          node.children,
          predicate,
          filterText
        );
      } else {
        const subs = this.arrayTreeFilter(node.children, predicate, filterText);
        if ((subs && subs.length) || predicate(node, filterText)) {
          node.children = subs;
          newChildren.push(node);
        }
      }
    }
    return newChildren;
  };

  filterFn = (data, filterText) => {
    if (!filterText) {
      return true;
    }
    return new RegExp(filterText, "i").test(data.title);
  };
  flatTreeFun = treeData => {
    let arr = [];
    const flatTree = treeData => {
      treeData.map((item, index) => {
        arr.push(item);
        if (item.children && item.children.length > 0) {
          flatTree(item.children);
          item.children = [];
        }
      });
    };
    flatTree(treeData);
    return arr;
  };
  expandedKeysFun = treeData => {
    if (treeData && treeData.length == 0) {
      return [];
    }
    let arr = [];
    const expandedKeysFn = treeData => {
      treeData.map((item, index) => {
        arr.push(item.key);
        if (item.children && item.children.length > 0) {
          expandedKeysFn(item.children);
        }
      });
    };
    expandedKeysFn(treeData);
    return arr;
  };
  onChange = value => {
    if (_.isEmpty(value)) {
      let { copyTree, copyExpandedKeys, expandedKeys } = this.state;
      this.setState({
        treeData: JSON.parse(copyTree),
        expandedKeys,
        searchValue: value
      });
    } else {
      let { copyTree } = this.state;
      let res = this.arrayTreeFilter(
        JSON.parse(copyTree),
        this.filterFn,
        value
      );
      let expkey = this.expandedKeysFun(res);
      this.setState({
        treeData: res,
        expandedKeys: expkey,
        searchValue: value
      });
    }
  };

  getNodeTreeRightClickMenu = () => {
    const { pageX, pageY } = { ...this.state.rightClickNodeTreeItem };
    const tmpStyle = {
      position: "absolute",
      left: `${pageX}px`,
      top: `${pageY}px`
    };
    const menu = (
      <Menu
        onClick={this.handleMenuClick}
        style={tmpStyle}
        className="rightmenu">
        <Menu.Item key="ADD">新增</Menu.Item>
        <Menu.Item key="DELETE">删除</Menu.Item>
      </Menu>
    );
    return this.state.rightClickNodeTreeItem == null ? "" : menu;
  };

  handleMenuClick = menu => {
    const { officeManageStore } = this.props;
    const { id } = this.state.rightClickNodeTreeItem;
    const { key } = menu;
    switch (key) {
      case "ADD":
        officeManageStore.getPostForm();
        officeManageStore.setOfficeVisible(true);
        break;
      case "DELETE":
        confirm({
          title: i18n.confirm.defaultTitle(),
          content: i18n.confirm.delete(),
          okText: i18n.button.ok(),
          cancelText: i18n.button.cancel(),
          onOk: () => this.handleDelete(id),
          onCancel() {
            return false;
          }
        });
        break;
      default:
        break;
    }
  };

  renderTreeNode = data => {
    //生成树结构函数
    if (data.length == 0) {
      return;
    }
    let { expandedKeys, searchValue } = this.state;
    return data.map(item => {
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);
      const title =
        index > -1
          ? <span>
              {beforeStr}
            <span style={{ color: "red" }}>
                {searchValue}
              </span>
            {afterStr}
            </span>
          : <span>
              {item.title}
            </span>;
      if (item.children && item.children.length > 0) {
        return (
          <TreeNode key={item.key} title={title} className="tree-node">
            {this.renderTreeNode(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} title={title} className="tree-node"/>;
    });
  };

  onExpand = keys => {
    const { expandedKeys } = this.state;
    this.setState({
      expandedKeys: expandedKeys.includes("-1") ? [] : keys
    });
  };

  handleSave = () => {
    const {
      form1,
      savePost,
      updatePost,
      officeClassifyId,
      officeVisible
    } = this.props.officeManageStore;
    form1.validateForm().then(f => {
      if (f.isValid) {
        // 验证通过, balabala业务代码
        const payload = { ...form1.getFormParams(), id: officeClassifyId };
        const result =
          officeClassifyId && officeVisible.type === "editPlan"
            ? updatePost(payload)
            : savePost(payload);
        this.setState({ loading: true });
        result.then(({ code, msg }) => {
          this.setState({ loading: false });
          if (code === 200) {
            message.success(
              officeClassifyId && officeVisible.type === "editPlan"
                ? "编辑成功"
                : "新增成功"
            );
            this.getTreeData();
            this.props.officeManageStore.setOfficeVisible({
              bool: false,
              type: officeVisible.type
            });
          } else {
            message.error(msg || "新增失败");
          }
        });
      } else {
        f.showErrors();
        this.setState({ date: new Date() }); // 改变一个state的变量,强制页面刷新
      }
    });
  };
  handleDelete = ids => {
    const { deleteByIds } = this.props.officeManageStore;
    deleteByIds({ ids }).then(({ code, msg }) => {
      if (code === 200) {
        message.success("删除成功");
        this.props.officeManageStore.setOfficeClassifyId("");
        this.getTreeData();
      } else {
        message.error(msg || "删除失败");
      }
    });
  };

  render() {
    let { expandedKeys, treeData, searchValue, loading } = this.state;
    const { officeManageStore } = this.props;
    const {
      officeCondition,
      form1,
      officeVisible,
      officeClassifyId
    } = officeManageStore;
    return (
      <div>
        <div style={{ padding: 10 }}>
          <WeaInputSearch
            value={searchValue}
            style={{ width: "100%" }}
            onChange={this.onChange}
          />
        </div>
        <Tree
          onExpand={this.onExpand}
          expandedKeys={expandedKeys}
          // 右击注释
          // onRightClick={this.treeNodeonRightClick}
          onSelect={this.onSelect}>
          {this.renderTreeNode(treeData)}
        </Tree>
        {this.getNodeTreeRightClickMenu()}
        <NewAndEditDialog
          ecId={`${(this && this.props && this.props.ecId) ||
          ""}_NewAndEditDialog@q4rrwm`}
          title={
            officeClassifyId && officeVisible.type === "editPlan"
              ? i18n.label.editOfficeClassifyName()
              : i18n.label.newOfficeClassifyName()
          }
          visible={officeVisible.bool}
          condition={toJS(officeCondition)}
          form={form1}
          isFormInit={form1.isFormInit}
          loading={loading}
          isEdit={true}
          height={150}
          conditionLen={1}
          save={() => this.handleSave()}
          onCancel={() =>
            officeManageStore.setOfficeVisible({
              bool: false,
              type: officeVisible.type
            })}
        />
      </div>
    );
  }
}

export default LeftTree;
