import { FC, useEffect, useRef, useState } from "react";
import { Button, Empty } from "antd";
import { useNavigate } from "react-router-dom";
import {
  DageLoading,
  DageTreeActionData,
  DageTreeActions,
} from "@dage/pc-components";
import { PlusOutlined } from "@ant-design/icons";
import { deleteAssIndexApi, getAssIndexTreeApi } from "@/api";
import { AssIndexTreeItemType, ASS_INDEX_TYPE, YES_OR_NO } from "@/types";
import style from "../../index.module.scss";

export interface SidebarProps {
  /**
   * 勾选模式
   */
  checkable?: boolean;
  type: ASS_INDEX_TYPE;
  currentId: null | number;
  treeApi?: () => Promise<AssIndexTreeItemType[]>;
  setCurrentId: (id: number | null) => void;
}

export const Sidebar: FC<SidebarProps> = ({
  checkable,
  type,
  currentId,
  treeApi,
  setCurrentId,
}) => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [treeData, setTreeData] = useState<AssIndexTreeItemType[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<number[]>([]);
  const lastCheckedItem = useRef<any>(null);
  const isFixed = type === ASS_INDEX_TYPE.FIXED;

  const transformTreeData = (data: AssIndexTreeItemType[]) => {
    return data.map((item) => {
      // @ts-ignore
      item.hideAddBtn = item.isPoint === YES_OR_NO.YES;
      // @ts-ignore
      item.hideDeleteBtn = Boolean(item.children?.length);

      if (item.children && item.children.length > 0) {
        item.children = transformTreeData(item.children);
      }

      return item;
    });
  };

  const getAssIndexTree = async () => {
    try {
      setLoading(true);
      const data = treeApi ? await treeApi() : await getAssIndexTreeApi(type);
      if (data.length) {
        // 防止再次选择
        data[0].disabled = true;
        setCurrentId(data[0].id);
        setCheckedKeys([data[0].id]);
        lastCheckedItem.current = data[0];

        setTreeData(transformTreeData(data));
      } else {
        setCurrentId(null);
        setCheckedKeys([]);
        setTreeData([]);
        lastCheckedItem.current = null;
      }
    } finally {
      setLoading(false);
    }
  };

  const handleAddNode = (item: DageTreeActionData) => {
    navigate(`/assessment/index/create/${type}?parentId=${item.id}`);
  };

  const handleEditNode = (item: DageTreeActionData) => {
    navigate(`/assessment/index/edit/${type}/${item.id}`);
  };

  const handleDeleteNode = async (item: DageTreeActionData) => {
    await deleteAssIndexApi(item.id);
    getAssIndexTree();
  };

  useEffect(() => {
    setTreeData([]);
    getAssIndexTree();
  }, [type]);

  return (
    <div className={style.sidebar}>
      <div className={style.sidebarHeader}>
        <h4>指标列表</h4>

        {!checkable && (
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate("/assessment/index/create/" + type)}
          >
            新增指标
          </Button>
        )}
      </div>

      {currentId && treeData.length ? (
        <DageTreeActions
          defaultExpandAll
          maxLevel={isFixed ? 5 : 2}
          treeData={treeData}
          selectedKeys={checkedKeys}
          onAdd={checkable ? undefined : handleAddNode}
          onEdit={checkable ? undefined : handleEditNode}
          onDelete={checkable ? undefined : handleDeleteNode}
          onSelect={(keys, { selectedNodes }) => {
            const checkedId = keys[keys.length - 1] as number;

            lastCheckedItem.current.disabled = false;
            selectedNodes[0].disabled = true;
            setCurrentId(checkedId);
            setCheckedKeys([checkedId]);
            lastCheckedItem.current = selectedNodes[0];
          }}
        />
      ) : (
        <Empty />
      )}

      {loading && <DageLoading />}
    </div>
  );
};
