/* eslint-disable */
/* eslint-disable no-param-reassign */
import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
import file from '@/assets/file.svg';
import file_single from '@/assets/file_single.svg';
import process from '@/assets/treeprocess.svg';
import material from '@/assets/treematerial.svg';
// import '@ant-design/compatible/assets/index.css';
import { Tree, Button, Input, Checkbox } from 'antd-v4';
import StaticEditTable from '../CommonTable';/* 可编辑表格 */
import * as commonUtils from '../../../utils/utils';
import styles from './Tree.css';
import AntdDraggableModal from '../AntdDraggableModal';
import * as commonFunc from "@/components/Common/commonFunc";


const SearchModule = Input.Search;
const { TreeNode } = Tree;
const FormItem = Form.Item;

class TreeComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: props.name,
      treeData: props.treeData || [],
      sFieldName: 'showName',
      sKeyName: 'key',
      autoExpandParent: true,
      showLine: true,
      checkable: true,
      searchValue: '',
      disabled: false,
      isSearch: false, // 是否可以t搜索 ，默认不可以进行搜索
      selectedKeys: props.selectedKeys,
      allCheckKeys: props.allCheckKeys,
      checkedKeys: props.checkedKeys,
      expandedKeys: props.expandedKeys,
      disabledCheckedKeys: props.disabledCheckedKeys,
      treeHeight: 0,
    };
    this.tableCollapsed = true;
  }

  componentDidMount() {
    if (location.pathname === '/indexPage/systemPermission') {
      if (this.treeRef) {
        const { isSearch } = this.state;
        const { height } = this.treeRef.getBoundingClientRect();
        this.setState({ treeHeight: height - (isSearch ? 75 : 0) });
      }
    }
  }

  componentWillMount() {
    this.assignmentWillProps(this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.assignmentWillProps(nextProps);
  }

  shouldComponentUpdate(nextProps, nextState) {
    const {
      name, selectedKeys, checkedKeys, sFieldName, sKeyName, treeData, expandedKeys, disabled, disabledCheckedKeys, searchVisible, searchValue, searchData,
    } = this.props;

    const bUpdate = disabled !== nextState.disabled || name !== nextState.name || sFieldName !== nextState.sFieldName || sKeyName !== nextState.sKeyName ||
      JSON.stringify(disabledCheckedKeys) !== JSON.stringify(nextState.disabledCheckedKeys) ||
      (commonUtils.isNotEmptyObject(searchValue) ? searchValue : '') !== (commonUtils.isNotEmptyObject(nextState.searchValue) ? nextState.searchValue : '') ||
      searchVisible !== nextState.searchVisible ||
      JSON.stringify(treeData) !== JSON.stringify(nextState.treeData) ||
      JSON.stringify(checkedKeys) !== JSON.stringify(nextState.checkedKeys) ||
      JSON.stringify(expandedKeys) !== JSON.stringify(nextState.expandedKeys) ||
      JSON.stringify(selectedKeys) !== JSON.stringify(nextState.selectedKeys) ||
      JSON.stringify(searchData) !== JSON.stringify(nextState.searchData);
    return bUpdate;
  }

  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
    if (this.props.onExpandTree) {
      this.props.onExpandTree(expandedKeys.map(item => item.split('-')[0]), expandedKeys);
      this.props.onSaveState({
        expandedKeys
      })
    }
  };

  onSelect = (selectedKeys, e) => {
    if (this.props.onSelect !== undefined) {
      this.props.onSelect(this.props.name, selectedKeys, e);
    }
  }

  /**   获取tree 对象的props   */
  getTreeProps = () => {
    const {
      checkable, disabled, checkedKeys, isSearch, showLine, selectedKeys, disabledCheckedKeys, expandedKeys, autoExpandParent, draggable, treeHeight,
    } = this.state;
    return {
      autoExpandParent,
      checkable,
      disabled,
      showLine,
      className: 'hide-file-icon',
      checkedKeys,
      selectedKeys,
      isSearch,
      disabledCheckedKeys,
      expandedKeys,
      draggable,
      onCheck: this.checkBoxCheck,
      onExpand: this.onExpand,
      onSelect: this.onSelect,
      onDrop: this.props.onDrop,
      multiple: this.props.multiple,
      // switcherIcon: <img src={file} alt="svg" />,
      showIcon: true,
      height: treeHeight,
    };
  };

  /**   获取tree 对象的props   */
  getTableProps = (name, props) => {
    const returnTypes = {
      name,
      app: props.app,
      formId: props.sModelsId,
      getSqlDropDownData: props.getSqlDropDownData,
      getSqlCondition: props.getSqlCondition,
      handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
      getFloatNum: props.getFloatNum,
      getDateFormat: props.getDateFormat,
      onDataChange: props.onDataChange,
      onUploadChange: props.onUploadChange,
      onModalCancel: props.onModalCancel,
      onLookRow: props.onDataRowLook,
      onAddRow: props.onDataRowAdd,
      onDelRow: props.onDataRowDel,
      onSelectRowChange: this.handleSelectRowChange,
      onDoubleClick: this.handleDoubleClick,
      selectedRowKeys: this.state.selectedRowKeys,
      headerColumn: props[`${name}Column`],
      config: props[`${name}Config`],
      data: props[`${name}Data`],
      enabled: false,
      rowSelectionType: 'radio', // 表格选择是单选还是多选择
      tableProps: {
        rowSelection: null,
        rowKey: props.sFieldName,
        AutoTableHeight: 450,
      }, // 表格属性
      previewImage: props.previewImage, /* 预览图片地址 */
      previewVisible: props.previewVisible, /* 图片预览弹窗 */
    };
    return returnTypes;
  };

  /**   处理选择行发生改变   */
  handleSelectRowChange = (name, selectedRowKeys) => {
    /*   外置处理业务   */
    this.setState({ selectedRowKeys });
  };

  assignmentWillProps = (props) => {
    const addState = {
      name: props.name,
      checkable: props.checkable,
      disabled: props.disabled,
      checkedKeys: props.checkedKeys,
      selectedKeys: props.selectedKeys,
      treeData: props.treeData,
      allCheckKeys: props.allCheckKeys,
      sFieldName: props.sFieldName,
      sKeyName: props.sKeyName,
      showLine: props.showLine,
      isSearch: props.isSearch,
      searchData: props.searchData,
      draggable: props.draggable,
    };
    if (props.expandedKeys !== undefined) {
      addState.expandedKeys = props.expandedKeys;
    }
    this.setState({ ...addState });
  };

  handleButtonClick = (e, child) => {
    const { allCheckKeys } = this.state;
    const stateValue = {};
    if (child === 'expandAll') {
      stateValue.expandedKeys = allCheckKeys;
    } else if (child === 'unExpand') {
      stateValue.expandedKeys = [];
    } else if (child === 'checkedAll') {
      stateValue.checkedKeys = allCheckKeys;
    } else if (child === 'unChecked') {
      stateValue.checkedKeys = [];
    }
    this.props.onSetTreeOptionKeys('Checked', stateValue.checkedKeys);
    this.setState(stateValue);
  }

  handleExpandClick = (e, child) => {
    const { allCheckKeys } = this.state;
    const stateValue = {};
    if (child === 'expandAll') {
      this.tableCollapsed = false;
      this.expRef.classList.remove('ant-table-row-expand-icon-collapsed');
      stateValue.expandedKeys = allCheckKeys;
    } else if (child === 'unExpand') {
      this.tableCollapsed = true;
      this.expRef.classList.add('ant-table-row-expand-icon-collapsed');
      stateValue.expandedKeys = [];
    }
    this.setState(stateValue);
  }

  checkBoxCheck = (checked, e) => {
    this.props.onCheck(checked, e);
  }

  handleSearch = (value) => {
    if (value !== '') {
      this.props.onSearch(value);
      this.setState({
        searchVisible: true,
      });
    }
  }

  handleChange = (event) => {
    this.setState({
      searchValue: event.target.value,
    });
  }

  hideModal = () => {
    this.setState({
      searchVisible: false,
    });
  }

  handleDoubleClick = (record) => {
    if (!commonUtils.isEmpty(record.sAllId)) {
      const expandedKeys = [];
      let expandedKey = '';
      const selectedKeys = [];
      record.sAllId.split('-').forEach((item) => {
        if (!commonUtils.isEmpty(item)) {
          expandedKey += `-${item}`;
          expandedKeys.push(expandedKey);
        }
      });
      if (commonUtils.isNotEmptyArr(this.state.expandedKeys)) {
        this.state.expandedKeys.forEach((item) => {
          expandedKeys.push(item);
        });
      }
      const e = { node: { props: { treeNode: record } } };
      this.props.onSelect(this.props.name, [record.sAllId], e);
      selectedKeys.push(record.sAllId);
      this.setState({ expandedKeys, searchVisible: false, selectedKeys });
    }
  };

  treeNodesProps = (item) => {
    const { checkedKeys, disabledCheckedKeys } = this.props;
    const showType = {};
    for (const ckey of checkedKeys) {
      if (ckey === item.key) {
        showType.checked = true;
        break;
      }
    }
    for (const dkey of disabledCheckedKeys) {
      if (dkey === item.key) {
        showType.disabled = true;
        break;
      }
    }
    return showType;
  };

  renderTreeNodesType = (item) => {
    const { checkedKeys, disabledCheckedKeys } = this.props;
    const iIndex = checkedKeys.findIndex(itemCheck => itemCheck === item.key);
    if (iIndex > -1) {
      checkedKeys[iIndex].checked = true;
    }

    const subscript = disabledCheckedKeys.findIndex(itemCheck => itemCheck === item.key);
    if (subscript > -1) {
      disabledCheckedKeys[subscript].checked = true;
    }
  }

  renderTreeNodes = (data) => {
    const { sFieldName, sKeyName } = this.props;
    return data.map((item) => {
      if (item.children && item.children.length > 0) {
        return (
          <TreeNode
            title={item[sFieldName]}
            key={item[sKeyName]}
            treeNode={item}
            {... this.treeNodesProps(item)}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (<TreeNode
        title={item[sFieldName]}
        key={item[sKeyName]}
        treeNode={item}
        {... this.treeNodesProps(item)}
        switcherIcon={item.sIconType === '12' || item.sIconType === '02' ?  <img src={material} alt="svg" /> :(item.sIconType === '13' || item.sIconType === '03' ? <img src={process} alt="svg" /> : <img src={file_single} width={13} alt="svg" /> ) }
      />);
    });
  };
  render() {
    const treeProps = this.getTreeProps();
    const PermissionContent = commonFunc.showLocalMessage(this.props, 'PermissionContent', '权限内容');
    const pleaseInputKeyWord = commonFunc.showLocalMessage(this.props, "pleaseInputKeyWord", "请输入你想要搜索的关键字");
    return (
      <FormItem className={styles.subForm}>
        <div className={styles.tableOption}>
          <div id="staticEditTree" ref={ref => { this.treeRef = ref; }}>
            {this.props.isSearch ?
              <SearchModule
                placeholder={pleaseInputKeyWord}
                disabled={false}
                onChange={this.handleChange}
                onSearch={this.handleSearch}
                value={this.state.searchValue}
                className={styles.search}
              /> : ''}
            {/*<div className={styles.advCol} >*/}
            {/*  {!this.props.checkedAll ? '' : <Button htmlType="button" disabled={treeProps.disabled} onClick={e => this.handleButtonClick(e, 'checkedAll')}>全选</Button>}*/}
            {/*  {!this.props.unChecked ? '' : <Button htmlType="button" disabled={treeProps.disabled} onClick={e => this.handleButtonClick(e, 'unChecked')}>全部不选</Button>}*/}
            {/*</div>*/}
            {
              this.props.isSearch ?
                <div className={styles.advColTitle} >
                  <div className={styles.advColCt}> <Checkbox style={{ marginRight:'5px' }} onChange={e => this.handleButtonClick(e,e.target.checked ? 'checkedAll' : 'unChecked')} /> {PermissionContent}</div>
                  <div className={styles.advColExpand}>
                    <button
                      className={`table-expAllIcon ant-table-row-expand-icon ${this.tableCollapsed ? 'ant-table-row-expand-icon-collapsed' : ''}`}
                      ref={(ref) => {
                        this.expRef = ref
                      }}
                      onClick={e => this.handleExpandClick(e, this.tableCollapsed ? 'expandAll' : 'unExpand')}
                    ></button>
                  </div>
                </div> : ''

            }
            <Tree {...treeProps}>
              {this.renderTreeNodes(this.props.treeData)}
            </Tree>
          </div>
          {/*<div className={styles.advCol} >*/}
          {/*  {!this.props.checkedAll ? '' : <Button htmlType="button" disabled={treeProps.disabled} onClick={e => this.handleButtonClick(e, 'checkedAll')}>全选</Button>}*/}
          {/*  {!this.props.unChecked ? '' : <Button htmlType="button" disabled={treeProps.disabled} onClick={e => this.handleButtonClick(e, 'unChecked')}>全部不选</Button>}*/}
          {/*</div>*/}
          {
            this.state.searchVisible ?
              <AntdDraggableModal
                width={1200}
                title="查询结果"
                visible={this.state.searchVisible}
                onOk={this.hideModal}
                onCancel={this.hideModal}
                footer={null}
              >
                <StaticEditTable {...this.getTableProps('search', this.props)} />
              </AntdDraggableModal>
            : ''
          }
        </div>
      </FormItem>
    );
  }
}

export default TreeComponent;
