import { getComponentAll } from '@/services/pipeline/index.js';
import { PipelineNodeModel } from '@/types';
import { to } from '@/utils/promise';
import { Collapse } from 'antd';
import { useEffect, useState } from 'react';
import Styles from './index.less';

type ModelMenuData = {
  key: string;
  name: string;
  value: PipelineNodeModel[];
};

type ModelMenuProps = {
  onComponentDragEnd: (
    data: PipelineNodeModel & { x: number; y: number; label: string; img: string },
  ) => void;
};
const ModelMenu = ({ onComponentDragEnd }: ModelMenuProps) => {
  const [modelMenusList, setModelMenusList] = useState<ModelMenuData[]>([]);

  useEffect(() => {
    // 获取所有组件
    const getAllComponents = async () => {
      const [res] = await to(getComponentAll());
      if (res && res.data) {
        const menus = res.data as ModelMenuData[];
        setModelMenusList(menus);
      }
    };

    getAllComponents();
  }, []);

  const dragEnd = (e: React.DragEvent<HTMLDivElement>, data: PipelineNodeModel) => {
    onComponentDragEnd({
      ...data,
      x: e.clientX,
      y: e.clientY,
      label: data.component_label,
      img: `/assets/images/${data.icon_path}.png`,
    });
  };

  const defaultActiveKey = modelMenusList.map((item) => item.key + '');
  const items = modelMenusList.map((item) => {
    return {
      key: item.key,
      label: item.name,
      children: item.value.map((ele) => {
        return (
          <div
            key={ele.id}
            draggable="true"
            onDragEnd={(e) => {
              dragEnd(e, ele);
            }}
            className={Styles.collapseItem}
          >
            {ele.icon_path && (
              <img
                style={{ height: '16px', marginRight: '15px' }}
                src={`/assets/images/${ele.icon_path}.png`}
                draggable={false}
                alt=""
              />
            )}
            {ele.component_label}
          </div>
        );
      }),
    };
  });

  return (
    <div className={Styles.collapse}>
      <div className={Styles.modelMenusTitle}>组件库</div>
      {/* 这样 defaultActiveKey 才能生效 */}
      {modelMenusList.length > 0 ? (
        <Collapse
          collapsible="header"
          expandIconPosition="end"
          defaultActiveKey={defaultActiveKey}
          items={items}
        ></Collapse>
      ) : null}
    </div>
  );
};

export default ModelMenu;
