/* eslint-disable no-unused-expressions */
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';
import { GetMapSetByGroupID } from '@/services/userManage/api';

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 => {
  const {
    ouid,
    searchWord,
    onCommit = () => {},
    dataList,
    onChange,
    checkList,
    btnLoading = false,
    loading,
    roleID,
  } = props;
  const [valueList, setValueList] = useState([]); // 选中值
  const [changedItem, setChangedItem] = useState({ item: {} }); // 改变的项
  const [indeterminate, setIndeterminate] = useState(false);
  const [keepAA, setKeepAA] = useState('');
  const [checkValue, setCheckValue] = useState(false);
  const [flag, setFlag] = useState(0);

  // 首次进入处理数据后续不触发
  useEffect(() => {
    console.log(checkList);
    let aa = dataList
      .map(l => checkChildrenByCondition(l, it => [getId(it)], true, 'map').flat(Infinity))
      .flat(Infinity)
      .filter(Boolean).length;
    setKeepAA(aa);
    setValueList(checkList);
    if (checkList.length === 0) {
      setIndeterminate(false);
      setCheckValue(false);
    } else if (checkList.length < aa) {
      setIndeterminate(true);
      setCheckValue(false);
    } else {
      setIndeterminate(false);
      setCheckValue(true);
    }
  }, [dataList, loading, checkList]);

  // 处理选中的值
  const updateValueList = (checkedKeys, childrenKeys, sourceItem) => {
    const removekeys = _.difference(childrenKeys, checkedKeys);
    let result = _.uniq(_.union(checkedKeys, valueList));
    _.remove(result, v => removekeys.includes(v));
    setValueList(result);
    setChangedItem(sourceItem);
    onChange && onChange(result);
    if (result.length === 0) {
      setIndeterminate(false);
      setCheckValue(false);
    } else if (result.length < keepAA) {
      setIndeterminate(true);
      setCheckValue(false);
    } else {
      setIndeterminate(false);
      setCheckValue(true);
    }
  };

  // 全选
  const checkAll = e => {
    setFlag(flag + 1);
    if (e.target.checked) {
      const arr = JSON.parse(JSON.stringify(dataList));
      const result = arr.map(item => getAllID(item)).flat(Infinity);
      setValueList(result);
      setCheckValue(true);
      setIndeterminate(false);
      // eslint-disable-next-line no-unused-expressions
      onChange && onChange(result);
    } else {
      setValueList([]);
      setCheckValue(false);
      setIndeterminate(false);
      // eslint-disable-next-line no-unused-expressions
      onChange && onChange([]);
    }
  };

  // 获取所有ID
  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',
          }}
        />
      ) : (
        <div className={styles.divBox}>
          <span
            style={{
              display: 'block',
              marginTop: '-14px',
              width: '120px',
              backgroundColor: 'white',
            }}
          >
            <Checkbox onChange={checkAll} indeterminate={indeterminate} checked={checkValue}>
              <span style={{ fontSize: '16px', fontWeight: 'bold' }}>全选/全不选</span>
            </Checkbox>
          </span>
          {dataList && dataList.length > 0 ? (
            dataList
              .filter(d => d.type === 'widgetGroup' || 'widget')
              .map((item, index) => (
                <ListCardItem
                  item={item}
                  ouid={ouid}
                  flag={flag}
                  roleID={roleID}
                  changedItem={changedItem}
                  updateValueList={updateValueList}
                  valueList={valueList}
                  key={`item${index}key`}
                  searchWord={searchWord}
                  {...props}
                />
              ))
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </div>
      )}
      {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;
