import React, { memo, useCallback, useEffect, useState, useRef } from "react";
import { Wrapper, RightCont } from "./styled";
import { TopNav } from "./miniComponents/topNav";
import { PPTSlide } from "../pptSlide/pptSlide";
// import { BottomText } from './miniComponents/bottomText';
import { ImgBoxArea } from "./miniComponents/imgBoxArea";
import { useHotkeys } from "react-hotkeys-hook";
import { TYIcon, message } from "@tingwu/design";
import { KEY_ARROWUP, KEY_ARROWDOWN, KEY_ARROWLEFT, KEY_ARROWRIGHT } from "@tingwu/util";

import { PresentationAgenda } from "../../spheres";
import { middleStatus } from "./untils/middleData";

export interface IExtractPpt {
  onChange?: (value: string) => void;
  agendas: PresentationAgenda[];
  pptsMap: any;
  list?: any;
  chooseId: string;
  closePpt: React.MouseEventHandler<HTMLSpanElement> | undefined;
  onReviewHandler: Function;
  onExport: Function | undefined;
  onDelete: Function | undefined;
  pController: any;
  onCopySuccess?: any;
  agendasLoading?: boolean;
  pptsummaryLoading?: boolean;
  pptDownloadLoading?: boolean;
}

const initShow = {
  index: 0,
  total: 0,
  beginTime: 0,
  photo: "",
  id: "",
  content: "",
  photoThumbnail: "",
};
export const ExtractPpt: React.FC<IExtractPpt> = memo(props => {
  const {
    agendas,
    pptsMap = {},
    closePpt,
    chooseId,
    onReviewHandler,
    onExport,
    onDelete,
    pController,
    onCopySuccess,
    agendasLoading,
    pptsummaryLoading,
    pptDownloadLoading,
  } = props;

  const [chooseNumState, setChooseNumState] = useState(chooseId);
  const [useAgendas, setUuseAgendas] = useState<PresentationAgenda[]>([]);
  const [usePptsMap, setUusePptsMap] = useState({});
  const [isFirstShow, setIsFirstShow] = useState(true);
  const [keyDire, setKeyDire] = useState("");
  const [innerDownloadLoading, setInnerDownloadLoading] = useState(pptDownloadLoading);
  const [showData, setShowData] = useState(initShow);
  const [canDelete, setCanDelete] = useState(true);
  const flatPpt = useRef<any>([]);
  const deleteData = useRef(false);
  useEffect(() => {
    flatPpt.current = [];
    middleStatus.noData = false;
    Object.values(pptsMap).forEach((item: any) => {
      flatPpt.current.push(item.ppts);
    });
    flatPpt.current = flatPpt.current.flat(1);
    if (!showData.id) {
      setUuseAgendas(agendas);
      setUusePptsMap(pptsMap);
    }

    if (!agendasLoading && !pptsummaryLoading) {
      // 数据都是ok状态
      setCanDelete(true);
      middleStatus.noData = !flatPpt.current.length; // ppt数据被删除完 或者无ppt数据
      setUuseAgendas(agendas);
      setUusePptsMap(pptsMap);
      if (showData.id && deleteData.current) {
        // 首次进入且未点击删除按钮 不执行. 删除时候走这里
        deleteData.current = false;
        let in_index: any = showData.index - 1;
        if (in_index === -1) {
          in_index += 1;
        }
        setChooseNumState(flatPpt.current[in_index]?.id || "");
      }
    } else {
      setCanDelete(false);
    }
  }, [pptsMap]);

  useEffect(() => {
    setInnerDownloadLoading(pptDownloadLoading);
  }, [pptDownloadLoading]);

  useEffect(() => {
    !agendasLoading && setUuseAgendas(agendas);
    !pptsummaryLoading && setUusePptsMap(pptsMap);

    if (!agendasLoading && !pptsummaryLoading) {
      setCanDelete(true);
    }
    // console.log(flatPpt.current, '!agendasLoading && !pptsummaryLoading----');
    // console.log(pptsMap, 'agendas11111', agendas);
    // middleStatus.noData = !flatPpt.current.length; // ppt数据被删除完 或者无ppt数据
    // if(!agendasLoading && !pptsummaryLoading) {
    //   for(let i=0; i< middleStatus.deleteArr.length; i++) {
    //     onDelete && onDelete(middleStatus.deleteArr[i]);
    //   };
    //   middleStatus.deleteArr = [];
    // }
    setChooseNumState(chooseId);
    setShowData(v => {
      return {
        ...v,
        ...flatPpt.current[showData.index],
      };
    });
  }, [agendasLoading, pptsummaryLoading]);

  useEffect(() => {
    showData.id && setIsFirstShow(false); // 非首次进入

    const index = flatPpt.current.findIndex((item: any) => {
      return item.id === chooseNumState;
    });
    const in_data: any = flatPpt.current[index];
    const len = flatPpt.current.length;
    setShowData({
      ...in_data,
      index,
      total: len,
    });
  }, [chooseNumState]);
  const nowChooseId = useCallback(
    (param: string) => {
      let nowIdIndex = 0;
      flatPpt.current.forEach((_item: any, index: number) => {
        if (_item.id === chooseNumState) {
          if (param === "pre") {
            nowIdIndex = index - 1;
          } else {
            nowIdIndex = index + 1;
          }
        }
      });
      if (nowIdIndex > -1 && nowIdIndex < flatPpt.current.length) {
        return flatPpt.current[nowIdIndex].id;
      } else if (nowIdIndex < 0) {
        message.warning({
          content: "已经是第一张啦",
          key: "1",
        });
        return flatPpt.current[0].id;
      } else {
        message.warning({
          content: "已经是最后一张啦",
          key: "1",
        });
        return flatPpt.current[flatPpt.current.length - 1].id;
      }
    },
    [chooseNumState]
  );
  const doScroll = () => {
    const ele: any = document.querySelector(".ppt-slide");
    if (!ele) return;
    ele.style.overflow = "hidden";
    setTimeout(() => {
      ele.style.overflow = "scroll";
    }, 100);
  };
  useHotkeys(KEY_ARROWUP, () => {
    doScroll();
    setKeyDire("start");
    console.log("上键");
    setChooseNumState(nowChooseId("pre"));
  });
  useHotkeys(KEY_ARROWLEFT, () => {
    console.log("左键");
    setKeyDire("start");
    doScroll();
    setChooseNumState(nowChooseId("pre"));
  });
  useHotkeys(KEY_ARROWDOWN, () => {
    doScroll();
    console.log("下键");
    setKeyDire("end");
    setChooseNumState(nowChooseId("next"));
  });
  useHotkeys(KEY_ARROWRIGHT, () => {
    doScroll();
    console.log("右键");
    setKeyDire("end");
    setChooseNumState(nowChooseId("next"));
  });
  const onDeletePpt = async (id: string) => {
    if (!onDelete || !canDelete) return;
    deleteData.current = true;
    // const res: any = true;
    const res: any = await onDelete(id);
    if (res) {
      // 删除成功
      pController.removePPTById(showData.id);

      // setUuseAgendas(agendas);
      // setUusePptsMap(pptsMap);
      // if (showData.id) { // 首次进入 不执行. 删除时候走这里
      //   let in_index: any = showData.index - 1;
      //   if (in_index === -1) {
      //     in_index += 1;
      //   }
      //   setChooseNumState(flatPpt.current[in_index]?.id || '');
      // }
    }
  };

  return (
    <Wrapper className={"contentOper"}>
      <div>
        <PPTSlide
          agendas={useAgendas}
          pptsMap={usePptsMap}
          chooseId={chooseNumState}
          keyDire={keyDire}
          isFirstShow={isFirstShow}
          smallImgChoose={(id: string) => {
            setChooseNumState(id);
          }}
        />
      </div>
      <RightCont>
        {chooseNumState ? (
          <TopNav
            showData={showData}
            onReviewHandler={onReviewHandler}
            onExport={onExport}
            onDelete={onDelete ? onDeletePpt : undefined}
            onCopySuccess={onCopySuccess}
            pptDownloadLoading={innerDownloadLoading}
            canDelete={canDelete}
          />
        ) : null}

        <span className={"close-icon"} onClick={closePpt}>
          <TYIcon type={"tongyi-false-line"} style={{ fontSize: 22, color: "var(--Text_White)" }} />
        </span>
        <ImgBoxArea key={showData.id} showData={showData} />
        {/* <ImgBoxArea key={showData.id} showData={showData} /> */}
        {/* <BottomText text={showData.content} /> */}
      </RightCont>
    </Wrapper>
  );
});
