/*
  * 自定义组件
  * 下拉树选择框
  * @Author:    黎永顺
  * @Date:      2024/9/24
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { WeaLocaleProvider } from "ecCom";
import { TreeSelect } from "antd";
import classNames from "classnames";

const getLabel = WeaLocaleProvider.getLabel;

class AssociativeTreeMult extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
    this.selectedData = {};
  }

  componentDidMount() {
    const { treeData } = this.props;
    this.setState({ data: this.filterTree(treeData) });
  }

  handleChange = (values) => {
    this.selectedData = {};
    values.forEach((v) => {
      let item = this.getItemById(v);
      if (item) this.selectedData[v] = item;
    });
    this.props.onChange && this.props.onChange(values, this.selectedData);
  };
  getItemById = (id) => {
    const { data } = this.state, { datas } = this.props;
    if (datas[id]) return datas[id];
    if (!_.isEmpty(data)) {
      for (let i = 0; i < data.length; i++) {
        if (id === data[i].id) return data[i];
      }
    }
  };
  filterTree = (nodes) => {
    const selectableNodes = [];
    const recurse = (nodes) => {
      nodes.forEach((node) => {
        if (node.selectable) selectableNodes.push(node);
        if (node.children) recurse(node.children);
      });
    };
    recurse(nodes);
    return selectableNodes;
  };

  render() {
    const { viewAttr, selectedValues, datas, isSingle, treeData } = this.props;
    const clsname = classNames({
      "required": (viewAttr === 3 || viewAttr === "3") && _.isEmpty(selectedValues)
    });
    const tProps = {
      treeData,
      multiple: true,
      allowClear: false,
      treeCheckable: true,
      style: { width: "100%" },
      treeDefaultExpandAll: true,
      value: selectedValues,
      onChange: this.handleChange,
      dropdownMatchSelectWidth: true,
      dropdownStyle: { minWidth: 200, maxHeight: 280, overflowY: "auto" },
      getPopupContainer: (triggerNode) => triggerNode.parentNode
    };
    return (
      <span className={`${clsname}`} ref="treeSelectWrapperMui"><TreeSelect {...tProps} /></span>
    );
  }
}

export default AssociativeTreeMult;
