import { Typography } from "antd";
import classnames from "classnames";
import React, { memo, useCallback, useEffect, useRef, useState } from "react";
import { PresentationAgenda } from "../../spheres";
import { ListContain } from "./styled";
import { getFlexibleTime } from "@tingwujs/common";

const { Paragraph } = Typography;

// 地址不存在时展示
const errorImg =
  "https://img.alicdn.com/imgextra/i2/O1CN01nLzZgS1hZKMxsmcEG_!!6000000004291-0-tps-1009-567.jpg";

export interface IPptSlideListProps {
  chooseId?: string; // 当前选中的是哪个ppt，需要在从原文区打开时传入，以及快捷键时传入
  smallImgChoose?: (chooseId: string) => void; // 列表点击之后，抛出ppt的id
  keyDire?: string; // 上下左右按键
  agendas?: PresentationAgenda[]; // 议程数据
  pptsMap?: any; // ppt图片数据
  isFirstShow?: boolean; // 是否第一次打开，第一次打开，不需要滚动效果
  deleteId?: number; // 被删除的第几张图片
}

// interface StorySetGuideType {
//   // @ts-ignore
//   readonly [key: boolean]: number;
// }

// eslint-disable-next-line max-lines-per-function
export const PPTSlide: React.FC<IPptSlideListProps> = memo(props => {
  const { smallImgChoose, chooseId, agendas = [], pptsMap = {}, isFirstShow, keyDire } = props;
  const [chooseNumState, setChooseNumState] = useState(chooseId);
  const interObs = useRef<any>(null);
  const resUse: any = useRef(null);
  const firstShow: any = useRef(true);
  const slidecKeyDire: any = useRef("");
  firstShow.current = isFirstShow;
  slidecKeyDire.current = keyDire;
  useEffect(() => {
    let ele: any; // IntersectionObserver 目前观察元素
    ele = document.querySelector(".ppt-active");
    // const configInter: StorySetGuideType = {
    //   false: {
    //     behav: 'smooth',
    //     dire: 'end',
    //   },
    //   true: {
    //     behav: 'auto',
    //     dire: 'nearest',
    //   },
    // };
    interObs.current = new IntersectionObserver(
      entries => {
        // const flag = entries[0].isIntersecting;
        const entry = entries[0];
        if (entry.intersectionRatio < 1) {
          try {
            ele.scrollIntoView({
              behavior: firstShow.current ? "auto" : "smooth",
              block: slidecKeyDire.current,
              inline: slidecKeyDire.current,
            });
          } catch (error) {
            // Error handling for scroll behavior
          }
        }
      },
      {
        threshold: [0],
      }
    );
    const observe = new MutationObserver(mutations => {
      ele && interObs.current.unobserve(ele);
      for (let ii = 0; ii < mutations.length; ii++) {
        const tar: any = mutations[ii].target;
        const cls = tar.className;
        if (cls && cls.includes("ppt-active")) {
          ele = tar;
          interObs.current.observe(tar);
        }
      }
    });
    observe.observe(resUse.current, {
      characterData: true,
      subtree: true,
      attributes: true,
      childList: true,
    });

    setTimeout(() => {
      const in_ele = document.querySelector(".ppt-active");
      const getCLi = in_ele && in_ele.getClientRects();
      if (!getCLi) return;
      const dataEle = getCLi[0];
      resUse.current.scrollTop = dataEle.top - document.body.clientHeight + dataEle.height;
    }, 100);

    return () => {
      observe.disconnect();
    };
  }, []);

  useEffect(() => {
    setChooseNumState(chooseId);
  }, [chooseId]);

  // useEffect(() => {
  //   // TODO
  // }, [chooseNumState, isFirstShow]);

  // 渲染PPT
  const renderPPT = useCallback(
    (item: any) => {
      return (
        <div
          className={classnames(
            "PPTSlide__PPT",
            `pptImgContent${item.id}`,
            chooseNumState === item.id && "ppt-active"
          )}
          id={`pptImgContent${item.id}`}
          onClick={() => {
            smallImgChoose && smallImgChoose(item.id);
          }}
          style={{
            backgroundImage: `url(${item.photoThumbnail || errorImg})`,
          }}
        />
      );
    },
    [chooseNumState, smallImgChoose]
  );

  // 渲染章节标题
  const renderAgendaTitle = useCallback((title: string, time: number) => {
    return (
      <Paragraph
        className="PPTSlide__AgendaTitle"
        ellipsis={{
          rows: 2,
          tooltip: {
            // @ts-ignore - Antd tooltip placement type mismatch
            placement: "right",
            title,
            getTooltipContainer: (node: any) => node,
          },
        }}
      >
        {getFlexibleTime(time)}&nbsp;&nbsp;{title}
      </Paragraph>
    );
  }, []);

  // 渲染章节
  const renderAgenda = useCallback(
    (agenda: any) => {
      const ppts = pptsMap[agenda.id]?.ppts || [];
      return (
        <div className="PPTSlide__Agenda" key={`Agenda_${agenda.id}`}>
          {renderAgendaTitle(agenda.agendaHeading, agenda.beginTime)}
          {ppts.length > 0 && <>{ppts.map(renderPPT)}</>}
        </div>
      );
    },
    [pptsMap, renderAgendaTitle, renderPPT]
  );

  return (
    <ListContain className="ppt-slide" ref={resUse}>
      {agendas.map(renderAgenda)}
    </ListContain>
  );
});
