index.js 8.72 KB
Newer Older
李纪文's avatar
李纪文 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
import PropTypes from 'prop-types';

import { Input, Layout, Spin, Tree, ConfigProvider } from 'antd';
// import { SearchOutlined } from '@ant-design/icons';
import React, { useCallback, useEffect, useMemo, useRef, useState, useContext } from 'react';
import PandaEmpty from '@wisdom-components/empty';
import classNames from 'classnames';
import _ from 'lodash';
import { getEquipmentInfo } from './apis';
import './index.less';
import classnames from 'classnames';

// 生成树的数据格式
const treeDataGenerator = (origin, currentType, ref) => {
  if (!origin || !Array.isArray(origin)) return [];
  return origin.map((item) => {
    const { shortName, deviceName, code, deviceType, children: originChildren } = item;
    const title = shortName || deviceName;
    const children = treeDataGenerator(originChildren, currentType);
    const _width = (ref?.current?.getBoundingClientRect().width || 180) - 24 - 8 - 28; // 24为tree的左侧空白,8为右侧滚动条位置,28是左侧复选框和边距等
    return {
      ...item,
      title: (
        <div
          title={title}
          style={{
            width: _width,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
          }}
        >
          {title}
        </div>
      ),
      key: code,
      children,
      disabled: currentType ? !(currentType === deviceType) : false,
    };
  });
};

// 树结构展开平铺
const flattenTreeData = (treeData) => {
  if (!treeData || !Array.isArray(treeData)) return {};
  const result = {};
  const deep = (treeData, target) => {
    treeData &&
      treeData.forEach((item) => {
        target[item.key] = item;
        if (item.children && item.children.length > 0) {
          deep(item.children, target);
        }
      });
  };
  deep(treeData, result);
  return result;
};

// 图层树处理
const convertToTree = (data, name) => {
  let obj = {};
  let newData = [];
  data.forEach((item, index) => {
    const state = item[name] || '未知';
    if (obj[state]) {
      obj[state] = [...obj[state], item];
    } else {
      obj[state] = [item];
    }
  });
  for (let k in obj) {
    newData.push({
      title: k,
      children: [...obj[k]],
      key: k,
      selectable: false,
      disableCheckbox: true,
      checkable: false,
    });
    expandedKeys.push(k);
  }
  return newData;
};

let dataList = [];
let expandedKeys = [];

const DeviceTree = (props) => {
  const {
    deviceTypes = '二供泵房,二供机组',
    userAccessor = false,
    getChild = true,
    sortFields = '',
    direction = '',
    classField = '',
    customerName = '',
  } = props;

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

  const cusProps = _.pick(props, ['onSelect', 'onCheck', 'selectable', 'checkable']);
  const { onSelect, onCheck, keepChecked, singleType = false, selectable, checkable } = props;

  const [data, setData] = useState([]);
  const [{ pageIndex, pageSize }, setPagination] = useState({
    pageIndex: 1,
    pageSize: 100,
  });
  const [searchs, setSearchs] = useState('');
  const [loading, setLoading] = useState(true);
  const [hasMore, setHasMore] = useState(true);
  const ref = useRef();

  const dataRef = useRef({
    currentType: '',
    preCheckedData: [],
    preCheckedKeys: [],
    preSelectedData: [],
    flatData: {},
  });
  const { currentType, flatData } = dataRef.current;
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [first, setFirst] = useState(true);

  const requestQuery = useMemo(() => {
    return {
      deviceTypes,
      pageIndex,
      pageSize,
      queryInfo: searchs,
      getChild,
      userID: userAccessor ? window?.globalConfig?.userInfo?.OID : void 0,
      sortFields,
      classField,
      direction,
      customerName,
    };
  }, [
    customerName,
    deviceTypes,
    direction,
    getChild,
    pageIndex,
    pageSize,
    searchs,
    sortFields,
    classField,
  ]);

  useEffect(() => {
    setLoading(true);
    getEquipmentInfo(requestQuery)
      .then((res) => {
        setLoading(false);
        const { list, pageIndex, totalCount } = res.data || {};
        const newData = pageIndex === 1 ? list : [...dataList, ...list]; // 非第一页时合并

        // 是否需要默认选中
        if (pageIndex === 1 && (!keepChecked || (keepChecked && !checkedKeys.length))) {
          setCheckedKeys(newData.length > 0 ? [newData[0].code] : []);
          onCheck?.(newData.length > 0 ? [newData[0]] : []);

          // 仅单选时使用select相关数据
          !checkable && onSelect?.(newData.length > 0 ? [newData[0]] : []);
          !checkable && setSelectedKeys(newData.length > 0 ? [newData[0].code] : []);

          singleType && (dataRef.current.currentType = newData[0].deviceType);
        }
        setData(() => {
          dataList = [...newData];
          return newData;
        });
        props.setDeviceList(newData);
        props.setSearchStr(searchs);
        setHasMore(newData.length < totalCount);
      })
      .catch((err) => {
        setLoading(false);
      });
  }, [requestQuery]);

  const onScroll = useCallback(() => {
    if (loading || !hasMore) return;
    const { clientHeight, scrollHeight, scrollTop } = ref.current;
    if (clientHeight + scrollTop + 10 >= scrollHeight) {
      // 加载更多
      setPagination({
        pageSize,
        pageIndex: pageIndex + 1,
      });
    }
  }, [loading, pageIndex, pageSize, hasMore]);

  const onSearch = useCallback(
    (value) => {
      setSearchs(value);
      setPagination({
        pageIndex: 1,
        pageSize,
      });
    },
    [pageSize],
  );

  useEffect(() => {
    ref.current?.addEventListener('scroll', onScroll, true);
    return () => {
      // eslint-disable-next-line react-hooks/exhaustive-deps
      ref.current?.removeEventListener('scroll', onScroll, true);
    };
  }, [onScroll]);

  const treeData = useMemo(() => {
    const treeData = treeDataGenerator(data, singleType && currentType, ref);
    const flatData = flattenTreeData(treeData);
    dataRef.current.flatData = Object.assign(dataRef.current.flatData || {}, flatData);
    return convertToTree(treeData, requestQuery.classField ? 'deviceClass' : 'deviceType');
  }, [data, singleType, currentType]);

  const handleCheck = (keys, info) => {
    // keys中会保留多余的key
    const { checked } = keys;
    setCheckedKeys(checked);
    const data = checked.map((key) => flatData[key]);
    onCheck?.(data);
    singleType && data.length === 0 && (dataRef.current.currentType = '');
    singleType && data.length === 1 && (dataRef.current.currentType = data[0].deviceType);
  };

  const handleSelect = (keys, info) => {
    if (checkable) {
      setCheckedKeys(keys);
      const data = keys.map((key) => flatData[key]);
      onCheck?.(data);
      singleType && data.length === 0 && (dataRef.current.currentType = '');
      singleType && data.length === 1 && (dataRef.current.currentType = data[0].deviceType);
    } else {
      setSelectedKeys(keys);
      const data = keys.map((key) => flatData[key]);
      onSelect?.(data);
    }
  };

  return (
    <div className={classNames(prefixCls, 'wkt-scroll-light')}>
      <Input.Search placeholder="搜索设备名称" onSearch={onSearch} allowClear />
      <div className={classnames(`${prefixCls}-tree-wrap`, 'wkt-scroll-light-plus')} ref={ref}>
        <Spin spinning={loading}>
          {data && data.length ? (
            <Tree
              checkStrictly
              checkedKeys={checkedKeys}
              selectedKeys={selectedKeys}
              autoExpandParent
              treeData={treeData}
              defaultExpandParent
              defaultExpandedKeys={expandedKeys}
              {...cusProps}
              onCheck={handleCheck}
              onSelect={handleSelect}
            />
          ) : (
            <PandaEmpty />
          )}
        </Spin>
      </div>
    </div>
  );
};

DeviceTree.defaultProps = {
  deviceTypes: '二供泵房',
  userAccessor: false,
  getChild: false,
  sortFields: '',
  direction: '',
  customerName: '',
  classField: '',
  selectable: false,
  checkable: false,
  keepChecked: false,
  onSelect: () => {},
  onCheck: () => {},
  setDeviceList: () => {},
  setSearchStr: () => {},
};

DeviceTree.propTypes = {
  deviceTypes: PropTypes.string,
  userAccessor: PropTypes.bool,
  getChild: PropTypes.bool,
  sortFields: PropTypes.string,
  direction: PropTypes.string,
  customerName: PropTypes.string,
  classField: PropTypes.string,
  selectable: PropTypes.bool,
  checkable: PropTypes.bool,
  keepChecked: PropTypes.bool,
  onSelect: PropTypes.func,
  onCheck: PropTypes.func,
  setDeviceList: PropTypes.func,
  setSearchStr: PropTypes.func,
};

export default DeviceTree;