import React, { useState, useEffect } from 'react';
import { Spin, Checkbox, Button, Empty } from 'antd';
import _ from 'lodash';
import ListCardItem from './ItemCard';
import styles from './ItemCard.less';

const tip = 'loading...';

export const getId = item => item.userID || item.roleID || item.stationID || item.id;
export const checkIsGroup = node =>
  ['widgetGroup'].includes(node?.type || node) && node.children?.length > 0;

// 递归遍历节点的方法
export const checkChildrenByCondition = (item, fn, withGroup = true, method = 'every') => {
  if (!checkIsGroup(item)) {
    return fn(item);
  }
  const childrenResults = item.children[method](t =>
    checkChildrenByCondition(t, fn, withGroup, method),
  );
  return withGroup ? [fn(item), ...childrenResults] : [...childrenResults];
};

const ListCard = props => {
  console.log(props, 'props');
  const {
    ouid,
    searchWord,
    onCommit = () => {},
    dataList,
    onChange,
    checkList,
    btnLoading = false,
    loading,
  } = props;
  const [valueList, setValueList] = useState([]);
  const [changedItem, setChangedItem] = useState({ item: {} });

  useEffect(() => {
    setValueList(checkList);
  }, [dataList, loading, checkList]);

  const updateValueList = (checkedKeys, childrenKeys, sourceItem) => {
    // eslint-disable-next-line no-console
    // console.time('updateValueList:');
    const removekeys = _.difference(childrenKeys, checkedKeys);
    let result = _.uniq(_.union(checkedKeys, valueList));
    _.remove(result, v => removekeys.includes(v));
    setValueList(result);
    if (sourceItem) setChangedItem(sourceItem);
    // eslint-disable-next-line no-unused-expressions
    onChange && onChange(result);
    // eslint-disable-next-line no-console
    // console.timeEnd('updateValueList:');
  };

  const checkAll = e => {
    if (e.target.checked) {
      const result = dataList.map(item => getAllID(item)).flat(Infinity);
      setValueList(result);
      // eslint-disable-next-line no-unused-expressions
      onChange && onChange(result);
    } else {
      setValueList([]);
      // eslint-disable-next-line no-unused-expressions
      onChange && onChange([]);
    }
  };

  const getAllID = item => {
    let result = [];
    const haveChildren = Array.isArray(item.children) && item.children.length > 0;
    // 统一使用 getId
    result.push(getId(item));
    if (haveChildren) {
      // 每次递归result被置空，所以要另外保存
      result = [...item.children.map(i => getAllID(i)), ...result];
    }
    return result;
  };

  return (
    <div>
      {loading ? (
        <Spin
          size="large"
          spinning={loading}
          tip={tip}
          style={{
            position: 'absolute',
            top: '30%',
            left: '0',
            right: '0',
            bottom: '0',
          }}
        />
      ) : (
        <>
          <Checkbox onChange={checkAll}>全选/全不选</Checkbox>
          {dataList && dataList.length > 0 ? (
            dataList
              .filter(d => d.type === 'widgetGroup' || 'widget')
              .map((item, index) => (
                <ListCardItem
                  item={item}
                  ouid={ouid}
                  changedItem={changedItem}
                  updateValueList={updateValueList}
                  valueList={valueList}
                  key={`item${index}key`}
                  searchWord={searchWord}
                  {...props}
                />
              ))
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </>
      )}
      {true && !loading && dataList && dataList.length > 0 && (
        <div className={styles.btnBox}>
          <Button
            type="primary"
            onClick={() => onCommit(valueList.filter(Boolean))}
            loading={btnLoading}
          >
            提交
          </Button>
        </div>
      )}
    </div>
  );
};

export default ListCard;
