import React from 'react';
import { FormBuilder, Connect, Tree, Input, Checkbox, Button } from 'amos-framework';
import { getSceneValue, recursive } from 'amos-designer';
import ImageConsts from '@gm/graphmod-assets';
import { fastDeepEqual } from 'amos-tool';
import { CommonModal, FireTree } from './../../index';
import './index.scss';

const BasicForm = FormBuilder.BasicForm;
const enhanceForm = Connect.enhanceForm;
const TreeNode = Tree.TreeNode;
/**
 * TreeSelectModelBeaut
 * 下拉树弹框-方框
 * @class TreeSelectModelBeaut
 * @extends {Component}
 */
@enhanceForm
class TreeSelectModelBeaut extends BasicForm {
  constructor(props) {
    super(props);
    this.state = {
      defaultvalue: '',
      posVisible: false,
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      treeData: [],
      searchData: [],
      value: '',
      selectedDataRef: {}
    };
  }

  componentDidMount() {
    const treeData = getSceneValue(this.props, 'data.items', []);
    const tarItem = recursive(this.props.data.items).find(e => e.key === this.props.value) || {};
    this.setState({
      treeData,
      defaultvalue: this.props?.valueName ?? tarItem.title,
      searchData: treeData,
      value: tarItem.value
    });
  }

  componentWillReceiveProps(nextProps) {
    const tarItem = recursive(this.props.data.items).find(e => e.key === nextProps.value) || {};
    console.log(nextProps);
    this.setState({
      expandedKeys: nextProps.expandedKeys,
      defaultvalue: nextProps?.valueName ?? tarItem.title,
      // defaultvalue: nextProps?.valueName,
      value: tarItem.value
    });

    if (nextProps.data?.items && !fastDeepEqual(nextProps.data.items, this.state.treeData)){
      this.initData(nextProps);
    }
  }

  initData = (props) => {
    const treeData = getSceneValue(props, 'data.items', []);
    console.log(props);
    this.setState({
      treeData,
      searchData: treeData
    });
  }

  showModel = () => {
    this.setState({
      posVisible: true
    });
  }

  cancel = () => {
    this.setState({
      posVisible: false
    });
  }

  onExpand = (expandedKeys, ...args) => {
    console.log('onExpand', args);
    this.setState({
      expandedKeys
    });
  }

  onSelect = (selectedKeys, info) => {
    console.log('onSelect', selectedKeys, info);
    this.setState({
      selectedKeys,
      value: selectedKeys[0],
      selectedDataRef: info?.node?.props?.dataRef
    });
  }

  ok = () => {
    const { value, selectedDataRef } = this.state;

    if (value) {
      this.props.onChange(value, selectedDataRef);
    }
    this.cancel();
  };

  // renderTitle = item => {
  //   const { value } = this.state;
  //   return (
  //     <span title={item.title}>
  //       {item.children ? (<span>{item.title}</span>) : (
  //         <Checkbox
  //           key={item.key}
  //           value={item.key}
  //           onChange={e => this.onCheck(e.target.checked, item)}
  //           checked={value === item.key}
  //         >
  //           {item.title}
  //         </Checkbox>
  //       )}
  //     </span>
  //   );
  // };

  renderTitle = item => {
    const { value } = this.state;
    return (
      <span title={item.title}>
        <Checkbox
          key={item.key}
          value={item.key}
          onChange={e => this.onCheck(e.target.checked, item)}
          checked={value === item.key}
        >
          {item.title}
        </Checkbox>
      </span>
    );
  };

  onCheck = (checked, info) => {
    if (checked) {
      this.setState({ value: info.key });
    } else {
      this.setState({ value: undefined });
    }
  };

  handleSearchChange = e => {
    this.setState({ searchValue: e.target.value }, () => {
      const { searchValue, treeData } = this.state;
      const { searchData, expandedKeys } = FireTree.getSearchData(searchValue, treeData, 'title', ['0'], 'key', this.state.expandedKeys, true);
      this.setState({ searchData, expandedKeys });
    });
  };

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={this.renderTitle(item)} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={this.renderTitle(item)} key={item.key} dataRef={item} />;
    });
  }

  renderContent() {
    const { selectedKeys, expandedKeys, value, searchData } = this.state;
    return (
      <Tree
        selectedKeys={selectedKeys}
        expandedKeys={expandedKeys}
        onSelect={this.onSelect}
        defaultSelectedKeys={[value]}
        onExpand={this.onExpand}
      >
        {searchData.length > 0 ? this.renderTreeNodes(searchData) : <div>暂无数据</div>}
      </Tree>
    );
  }

  render() {
    const { posVisible, defaultvalue, searchValue } = this.state;
    const { disabled } = this.props;
    const modelTitle = getSceneValue(this.props, 'data.modelTitle', '请选择');
    return (
      <div className="tree-select-model-box">
        <div className="tree-select-model">
          <div className="tree-select-model-input">
            <div class="amos-tree-select-title amos-text-overflow amos-popover-trigger">{defaultvalue ? defaultvalue : '请选择'}</div>
          </div>
          <Button className="mods-modelinput-btn" size="sm" disabled={disabled} onClick={this.showModel}>选择</Button>
        </div>
        <CommonModal title={modelTitle} visible={posVisible} destroyContent outterClosable={false} width={320} onOk={this.ok} onCancel={this.cancel} >
          <div className="eh-listselect-modal">
            <div className="eh-listselect-search">
              <Input onChange={this.handleSearchChange} value={searchValue} />
              <img src={ImageConsts.common.search} alt="" />
            </div>
            <div className="eh-listselect-list mod-com-scrollbar">
              {this.renderContent()}
            </div>
          </div>
        </CommonModal>
      </div>
    );
  }
}

export default TreeSelectModelBeaut;
