import React, { useContext, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Spin, Input, Tree, Divider, message, Pagination, ConfigProvider } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import Empty from '@wisdom-components/empty';
import './index.less';

const DeviceTree = (props) => {
  const {
    prefix,
    placeholder,
    deviceTreeService,
    serviceParams,
    onTreeCheck,
    onTreeSelect,
    pagination,
  } = props;

  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('ec-device-tree');

  const [treeData, setTreeData] = useState([]);
  const [params, setParams] = useState({});
  const [totalCount, setTotalCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);

  useEffect(() => {
    setParams(serviceParams);
  }, []);

  useEffect(() => {
    setParams(serviceParams);
  }, [serviceParams]);

  const handleData = (data) => {
    data.map((item) => {
      item.title = item.deviceName;
      item.key = item.stationID;
      item.children = handleData(item.children);
    });
    return data;
  };

  const fetchData = (param = {}) => {
    setLoading(true);
    deviceTreeService(param).then((response) => {
      if (response.code === 0) {
        const data = response.data
          ? response.data.list && response.data.list.length > 0
            ? response.data.list[0].deviceList
            : []
          : [];
        const newData = handleData(data);
        const keys = newData.length > 0 ? [newData[0].key] : [];
        setLoading(false);
        setTreeData(newData);
        setTotalCount(response.data.totalCount);
        onTreeCheck(newData.length > 0 ? [newData[0]] : []);
        onTreeSelect(newData.length > 0 ? [newData[0]] : []);
        setCheckedKeys(keys);
        setExpandedKeys(keys);
        setSelectedKeys(keys);
      } else {
        message.error(response.msg);
      }
    });
  };

  useEffect(() => {
    if (JSON.stringify(params) !== '{}') {
      fetchData(params);
    }
  }, [params]);

  const onSearch = (e) => {
    if (e.type === 'keydown' || e.target.value === '') {
      const param = { ...params, queryInfo: e.target.value };
      setParams(param);
    }
  };

  // 选中复选框
  const onCheck = (checkedKeysValue) => {
    const { checked } = checkedKeysValue;
    const checkedTree = [];
    treeData.forEach((item) => {
      if (checked.includes(item.key)) {
        checkedTree.push(item);
      }
      if (item.children.length > 0) {
        item.children.forEach((child) => {
          if (checked.includes(child.key)) {
            checkedTree.push(child);
          }
        });
      }
    });
    setCheckedKeys(checked);
    onTreeCheck(checkedTree);
  };

  const onSelect = (selectedKeysValue, info) => {
    setSelectedKeys(selectedKeysValue);
    onTreeSelect(info.selectedNodes);
  };

  const onExpand = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
  };

  const onPaginationChange = (page) => {
    setParams({ ...params, pageIndex: page });
  };

  return (
    <div className={classNames(prefixCls)}>
      <Input
        prefix={prefix}
        placeholder={placeholder}
        bordered={false}
        onChange={onSearch}
        onPressEnter={onSearch}
      />
      <Divider className={classNames(`${prefixCls}-divider`)} />
      <div className={classNames(`${prefixCls}-content`)}>
        <Spin delay={1000} spinning={loading}>
          {!!treeData.length && (
            <Tree
              checkedKeys={checkedKeys}
              expandedKeys={expandedKeys}
              selectedKeys={selectedKeys}
              treeData={treeData}
              onExpand={onExpand}
              onCheck={onCheck}
              onSelect={onSelect}
              checkStrictly
              {...props}
            />
          )}
          {!treeData.length && !loading && <Empty />}
        </Spin>
      </div>
      {pagination && (
        <div className={classNames(`${prefixCls}-pagination`)}>
          <Pagination
            simple
            hideOnSinglePage
            current={params.pageIndex || 1}
            pageSize={params.pageSize || 20}
            total={totalCount}
            onChange={onPaginationChange}
          />
        </div>
      )}
      {!pagination && (
        <Divider plain className={classNames(`${prefixCls}-total`)}>
          共 {totalCount}条 记录
        </Divider>
      )}
    </div>
  );
};

DeviceTree.defaultProps = {
  prefix: <SearchOutlined />,
  placeholder: '搜索设备名称',
  pagination: true,
  serviceParams: {},
  onTreeCheck: () => {},
  onTreeSelect: () => {},
};

DeviceTree.propTypes = {
  prefix: PropTypes.node,
  placeholder: PropTypes.string,
  pagination: PropTypes.bool,
  serviceParams: PropTypes.object,
  onTreeCheck: PropTypes.func,
  onTreeSelect: PropTypes.func,
  deviceTreeService: PropTypes.any,
};

export default DeviceTree;
