import React, { useCallback, useEffect, useState, useContext } from 'react';
import styles from './index.less';
import { Collapse } from '@easyv/react-gui';
import { FileSearchOutlined, BulbOutlined } from '@easyv/react-icons';
import EasyvTooltip from 'components/EasyvTooltip';
import { CustomizeEventCheck ,CustomizeEventViewDisplay } from '@/utils/eventTracking/nodes.type';
import classnames from 'classnames';
import { NodesContext } from '../../Context/index';
import { isEfficient } from './index';
import { CustomEventState } from 'models/queue.type';
import message from 'components/message';
import { EventList, Type } from '@/utils/nodes.types';
import { eventTracking } from '@/models/event-tracking';
import { useDispatch } from 'react-redux';

function CardEventList({
  eventList,
  screenId,
  screenName,
}: {
  screenId: number;
  screenName: string;
  eventList: EventList;
}) {
  const dispatch = useDispatch();
  const config = [
    {
      name: '作为上游节点',
      id: Type.UP,
    },
    {
      name: '作为下游节点',
      id: Type.DOWN,
    },
  ];
  const { setEventNode, setCustomEvents, onRoutingSwitch, changeLayerStatus } =
    useContext(NodesContext);
  const [collapsed, setCollapsed] = useState<Type[]>(config.map((d) => d.id));
  const [actives, setActive] = useState<string[]>([]);

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

  useEffect(() => {
    const { downStream = [], upStream = [] } = eventList;
    let nodeIds = downStream?.concat(upStream).reduce((all, cur) => {
      return all.concat(
        cur.list.reduce((complete: string[], item): any => {
          if (actives.includes(item.id)) {
            return complete.concat(item.nodeId);
          }
          return complete;
        }, []),
      );
    }, []);
    nodeIds = Array.from(new Set(nodeIds));
    setEventNode(nodeIds);
  }, [actives, eventList]);

  const handleClick = (data) => {
    if (data && data.id) {
      setActive(data.id);
      // setActive(actives.includes(data.id) ? actives.filter((d) => d !== data.id) : actives.concat(data.id));
    }
  };
  const isCollapseUp = useCallback((id) => {
    return id === Type.UP;
  }, []);

  const getTypeList = useCallback(
    (id) => {
      return isCollapseUp(id) ? eventList.upStream : eventList.downStream;
    },
    [eventList],
  );

  const getNodeStr = useCallback((value) => {
    const event = value?.eventName;
    const switchState = value?.text;
    const targetNode = value?.name;
    const _isCollapseUp = isCollapseUp(value?.collapseType);
    const str = _isCollapseUp
      ? `${switchState} ${targetNode} ${event}`
      : `${targetNode} ${event} ${switchState}`;

    return (
      <EasyvTooltip title={str} placement="top">
        {str}
      </EasyvTooltip>
    );
  }, []);

  //   state = view（查看） | show（查看并独显）
  const linkView = async (data, state: CustomEventState = CustomEventState.VIEW) => {
    const { targetNodeId, actionId, eventId } = data;
    const hide = message.loading('处理中，请稍等', 0);
    if (targetNodeId) {
      await onRoutingSwitch(targetNodeId);
      await setCustomEvents([
        {
          targetNodeId,
          actionId,
          eventId,
          state,
        },
      ]);
      state === CustomEventState.VIEW_AND_SHOW && changeLayerStatus('focus'); // 独显
    } else {
      message.warning('定位失败，目标组件不存在');
    }
    hide();
  };

  return (
    <div>
      {config
        .filter((d) =>
          isCollapseUp(d.id)
            ? isEfficient(eventList?.upStream)
            : isEfficient(eventList?.downStream),
        )
        .map((d) => (
          <Collapse
            key={d.id}
            collapsed={collapsed ? !collapsed.includes(d.id) : true}
            bordered={false}
            className={classnames({
              [styles.collapse]: collapsed?.includes(d.id),
            })}
            header={d.name}
            onChange={() => {
              const _collapsed = Array.from(
                new Set(
                  collapsed?.includes(d.id)
                    ? collapsed.filter((id) => d.id !== id)
                    : [...collapsed, d.id],
                ),
              );
              setCollapsed(_collapsed);
            }}>
            <ul className={classnames(styles.cards)}>
              {getTypeList(d.id)?.map((item) => {
                return item.list.map((value) => {
                  return (
                    <li
                      className={classnames(styles.card, {
                        [styles.cardActive]: actives.includes(value.id),
                      })}
                      key={value.id}
                      onClick={() => {
                        handleClick(value);
                      }}>
                      <div className={styles.left}>
                        {getNodeStr({ ...value, ...item.config, collapseType: d.id })}
                      </div>
                      <div className={styles.right}>
                        <span
                          className={styles.icon}
                          onClick={(e) => {
                            e.stopPropagation();
                            dispatch(
                              eventTracking<CustomizeEventCheck>({
                                id: `${screenId}-customizeEventCheck`,
                                type: 'customizeEventCheck',
                                screenId,
                                screenName,
                                num: 1,
                              }));
                            linkView({ ...value, ...item.config }, CustomEventState.VIEW);
                          }}>
                          <EasyvTooltip placement="top" title="查看">
                            <FileSearchOutlined />
                          </EasyvTooltip>
                        </span>
                        <span
                          className={styles.icon}
                          onClick={(e) => {
                            e.stopPropagation();
                            dispatch(
                              eventTracking<CustomizeEventViewDisplay>({
                                  id: `${screenId}-customizeEventViewDisplay`,
                                  type: 'customizeEventViewDisplay',
                                  screenId,
                                  screenName,
                                  num: 1,
                              }),
                            );
                            linkView({ ...value, ...item.config }, CustomEventState.VIEW_AND_SHOW);
                          }}>
                          <EasyvTooltip placement="top" title="查看并独显">
                            <BulbOutlined />
                          </EasyvTooltip>
                        </span>
                      </div>
                    </li>
                  );
                });
              })}
            </ul>
          </Collapse>
        ))}
    </div>
  );
}

export default CardEventList;
