import React, { useEffect, useState, useRef } from 'react';
import Tree from '../../components/Tree';
import TreeTitle from '../TreeTitle';
import IconFont from '../../themeComponents/IconFont';
import { inject } from 'mobx-react';
import CBox from '../../themeComponents/CBox';
import { Select, Tooltip } from 'antd';
import './index.less';
const { Option } = Select


const OrgTree = ({ expandedKeys, launchFlag, showCount, org, className = '', title, inputPlaceholder = '请输入组织名称', renderHeader, treeNodeClass, activeKey, treeData, onSelect, ...props }) => {
  const [keyword, setKeyword] = useState()
  const [orgSelectValue, setOrgSelectValue] = useState()
  const [treeExpandedKeys, setTreeExpandedKeys] = useState(expandedKeys || (treeData[0] ? [treeData[0].id] : null))
  const treeBoxRef = useRef();

  useEffect(() => {
    if (!treeExpandedKeys && expandedKeys) {
      setTreeExpandedKeys(expandedKeys)
    }
  }, [expandedKeys, treeExpandedKeys])
  useEffect(() => {
    const ids = launchFlag ? org.orgList.map(v => v.id) : [org.orgList[0]?.id];
    setTreeExpandedKeys(ids)
  }, [launchFlag])

  const onChange = (value) => {
    let expandedKeyArr = [];
    if (!value) {
      expandedKeyArr = [org.orgList[0] ? org.orgList[0].id : ''];
    } else {
      let keys = [];
      const orgs = org.orgList.filter((v) => v.name.indexOf(value) > -1);
      orgs.forEach((v) => {
        let ids = org.getParentOrgListByOrgId(v.id).map((v) => v.id);
        keys = [].concat(keys, ids);
      });
      expandedKeyArr = [...new Set([...keys])];
    }
    setTreeExpandedKeys(expandedKeyArr)
    setKeyword(value)

  };

  const renderSuffix = (node) => {
    const { renderSuffix } = props;
    return (
      <span className="tree-node-suffix">
        {showCount && (
          <>
            <i className="online-count">{node.deviceCount.onlineCount}/</i>
            <i className="count">{node.deviceCount.count}</i>
          </>
        )}
        {renderSuffix && renderSuffix(node)}
      </span>
    );
  };
  const getTreeIndex = (data, ids) => {
    let ind = 0
    let item = data
    ids.forEach((id, k) => {
      let itemInd = item.findIndex(v => v.id === id) //计算在同层节点中的位置
      ind += itemInd
      if (k !== ids.length - 1) {
        ind += 1 //加上本节点的高度
      }
      item = item.find(v => v.id === id)?.children || []
    })
    return ind
  }
  const getTreeIds = (orgList, id) => {
    return orgList.find(v => v.id === id)?.treeId?.split('/').filter(v => v)
  }
  const handleChange = (id) => {
    console.log(id);
    onSelect([id])
    setOrgSelectValue(id)
    let ids = getTreeIds(org.orgList, id)
    ids.push(id)
    setTreeExpandedKeys(ids)
    let ind = getTreeIndex(treeData, ids)
    setTimeout(() => {
      let scrollDom = treeBoxRef.current.getElementsByClassName('ant-tree')[0]
      scrollDom.scrollTop = ind * 29
    }, 200);
  }

  const onTreeSelect = (keys) => {
    setOrgSelectValue()
    onSelect && onSelect(keys)
  }

  return (
    <CBox boxRef={treeBoxRef} className={`lm-organization-tree ${className}`}>
      {title ? <TreeTitle hasInput={false} titleExt={
        <Select
          showSearch
          allowClear
          value={orgSelectValue}
          style={{ flex: 1 ,maxWidth: '189px' }}
          filterOption={(input, option) =>
            (option?.label ?? '').includes(input)
          }
          placeholder={`请输入组织机构查询`}
          onChange={handleChange}
        >
          {
            org.orgList.map(v => {
              const treeDescription = v.treeDescription.replace('null', '')
              return <Option key={v.id} value={v.id} label={v.name}>
                <Tooltip placement="bottom" title={v.name}>
                  <div style={{ width: '100%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} >
                    {v.name}
                  </div>
                </Tooltip>
                <Tooltip placement="bottom" title={treeDescription}>
                  <div style={{ color: '#999', fontSize: '12px', width: '100%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} >
                    {treeDescription}
                  </div>
                </Tooltip>
              </Option>
            })
          }

        </Select>
      } title={title} inputPlaceholder={inputPlaceholder} onChange={onChange} /> : null}
      {renderHeader && renderHeader()}
      <Tree
        {...props}
        treeData={treeData}
        onExpand={setTreeExpandedKeys}
        selectedKeys={activeKey ? (Array.isArray(activeKey) ? activeKey : [activeKey]) : undefined}
        onSelect={onTreeSelect}
        expandedKeys={treeExpandedKeys}
        defaultExpandedKeys={treeData[0] ? [treeData[0].id] : undefined}
        treeNodeProps={{
          treeNodeIcon: (node) => <IconFont type={`${node.id === treeData[0].id ? 'icon-S_Bar_Home' : 'icon-S_Photo_ListTree'}`} />,
          keyword: keyword,
          suffix: renderSuffix,
          treeNodeClass: treeNodeClass,
        }}
      />
    </CBox>
  );

}


export default inject('org')(OrgTree);


// @inject('org')
// class OrgTree extends React.Component {
//   constructor(props) {
//     super(props);
//     const { expandedKeys, treeData } = this.props;
//     this.state = {
//       keyword: null,
//       expandedKeys: expandedKeys || (treeData[0] ? [treeData[0].id] : null),
//     };
//   }
//   static getDerivedStateFromProps(props, state) {
//     if (!state.expandedKeys && props.expandedKeys) {
//       return { expandedKeys: props.expandedKeys };
//     }
//     return null;
//   }
//   onChange = (value) => {
//     const { org } = this.props;
//     let expandedKeys = [];
//     if (!value) {
//       expandedKeys = [org.orgList[0] ? org.orgList[0].id : ''];
//     } else {
//       let keys = [];
//       const orgs = org.orgList.filter((v) => v.name.indexOf(value) > -1);
//       orgs.forEach((v) => {
//         let ids = org.getParentOrgListByOrgId(v.id).map((v) => v.id);
//         keys = [].concat(keys, ids);
//       });
//       expandedKeys = [...new Set([...keys])];
//     }
//     this.setState({
//       expandedKeys,
//       keyword: value,
//     });
//   };
//   onExpand = (expandedKeys) => {
//     this.setState({
//       expandedKeys,
//     });
//   };
//   renderSuffix = (node) => {
//     const { showCount, renderSuffix } = this.props;
//     return (
//       <span className="tree-node-suffix">
//         {showCount && (
//           <>
//             <i className="online-count">{node.deviceCount.onlineCount}/</i>
//             <i className="count">{node.deviceCount.count}</i>
//           </>
//         )}
//         {renderSuffix && renderSuffix(node)}
//       </span>
//     );
//   };

//   handleChange = (id) => {
//     console.log(id);
//     // setOrgSelectValue(id)
//     // changeForm({ orgId: id })
//     // setOrgTreeKey(Math.random())
//     // let ids = getTreeIds(orgList, id)
//     // ids.push(id)
//     // let ind = getTreeIndex(orgTreeData, ids)
//     // setTimeout(() => {
//     //   let scrollDom = treeBoxRef.current.getElementsByClassName('ant-tree')[0]
//     //   scrollDom.scrollTop = ind * 29
//     // }, 200);
//   }


//   render() {
//     const { org, className = '', title, inputPlaceholder = '请输入组织名称', renderHeader, treeNodeClass, activeKey, treeData, ...props } = this.props;
//     const { expandedKeys } = this.state;
//     return (
//       <CBox className={`lm-organization-tree ${className}`}>
//         {title ? <TreeTitle hasInput={false} titleExt={
//           <Select
//             showSearch
//             allowClear
//             // value={orgSelectValue}
//             style={{ flex: 1 }}
//             filterOption={(input, option) =>
//               (option?.label ?? '').includes(input)
//             }
//             placeholder={`请输入组织机构查询`}
//             onChange={this.handleChange}
//           >
//             {
//               org.orgList.map(v => {
//                 const treeDescription = v.treeDescription.replace('null', '')
//                 return <Option key={v.id} value={v.id} label={v.name}>
//                   <Tooltip placement="bottom" title={v.name}>
//                     <div style={{ width: '100%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} >
//                       {v.name}
//                     </div>
//                   </Tooltip>
//                   <Tooltip placement="bottom" title={treeDescription}>
//                     <div style={{ color: '#999', fontSize: '12px', width: '100%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} >
//                       {treeDescription}
//                     </div>
//                   </Tooltip>
//                 </Option>
//               })
//             }

//           </Select>
//         } title={title} inputPlaceholder={inputPlaceholder} onChange={this.onChange} /> : null}
//         {renderHeader && renderHeader()}
//         <Tree
//           {...props}
//           treeData={treeData}
//           onExpand={this.onExpand}
//           selectedKeys={activeKey ? (Array.isArray(activeKey) ? activeKey : [activeKey]) : undefined}
//           expandedKeys={expandedKeys}
//           defaultExpandedKeys={treeData[0] ? [treeData[0].id] : undefined}
//           treeNodeProps={{
//             treeNodeIcon: (node) => <IconFont type={`${node.id === treeData[0].id ? 'icon-S_Bar_Home' : 'icon-S_Photo_ListTree'}`} />,
//             keyword: this.state.keyword,
//             suffix: this.renderSuffix,
//             treeNodeClass: treeNodeClass,
//           }}
//         />
//       </CBox>
//     );
//   }
// }

// export default OrgTree;
