// @ts-ignore
import React, { useEffect, useState } from 'react';
import PandaDeviceTree from '../index';
import request from 'umi-request';

const Demo = () => {
  const [treeData, setTreeData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState(null);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const fetchData = (params = {}) => {
    // eslint-disable-next-line no-use-before-define
    request(`${baseUrl}/Publish/GCK/Device/DeviceTree`, {
      method: 'post',
      data: {
        pageIndex: 1,
        pageSize: 500,
        deviceTypes: '二供泵房,二供机组',
        getChild: true,
        userID: 1,
        queryInfo: params.queryInfo || '',
        sortFields: '',
        direction: '',
        isTop: true,
      },
    }).then(function (response) {
      // eslint-disable-next-line no-nested-ternary
      const data = response.data
        ? response.data.list && response.data.list.length > 0
          ? response.data.list[0].deviceList
          : []
        : [];
      // eslint-disable-next-line no-use-before-define
      setTreeData(handleData(data));
    });
  };

  const handleData = (data) => {
    // eslint-disable-next-line array-callback-return
    data.map((item) => {
      // eslint-disable-next-line no-param-reassign
      item.title = item.deviceName;
      // eslint-disable-next-line no-param-reassign
      item.key = item.stationID;
      // eslint-disable-next-line no-param-reassign
      item.children = handleData(item.children);
    });
    return data;
  };

  useEffect(() => {
    fetchData();
  }, []);

  const onExpand = (expandedKeysValue) => {
    console.log('onExpand', expandedKeysValue);
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue, info) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  const onSearch = (e) => {
    if (e.type == 'keydown') {
      fetchData({ queryInfo: e.target.value });
    }
    console.log(e.type, 'e.type');
    console.log(e.target.value, 'e.target.value');
  };

  return (
    <div style={{ width: '200px', height: '400px', border: '1px solid #eee' }}>
      <PandaDeviceTree
        onSearch={onSearch}
        checkable
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        onSelect={onSelect}
        selectedKeys={selectedKeys}
        treeData={treeData}
      />
    </div>
  );
};

export default Demo;

const baseUrl = 'https://www.fastmock.site/mock/162c15dca15c4dba9ba51e0a0b76929b/api';