import boardFactory, { BoardShape, MetaShapeType, bgImage } from "./";
import { getCaseInfo } from "@/store/case";
import { BoardData, getCaseFileImageInfo, getuserFileInfo } from "@/store/caseFile";
import { Board } from "./";
import { Ref, ref, watch, watchEffect } from "vue";
import { BoardType } from "@/store/caseFile";
import { BoardTypeDesc } from "@/constant/caseFile";
import { RouteName, router } from "@/router";
import { ElMessage } from "element-plus";

const defaultStore = {
  id: -1,
  version: "v4.0",
  floors: [
    {
      points: {},
      walls: {},
      tags: {},
      rectangles: {},
      circles: {},
      arrows: {},
      icons: {},
      signs: {},
      title: {
        len: null,
        value: "某某案发现场",
        height: 50,
        floor: 0,
        geoType: "Title",
        vectorId: "Title6",
      },
      image: {
        len: null,
        image: null,
        floor: 0,
        geoType: "BgImage",
        vectorId: "BgImage8",
      },
      compass: {
        len: null,
        angle: 0,
        floor: 0,
        center: {
          x: 800,
          y: 70,
        },
        radius: 52,
        geoType: "Compass",
        vectorId: "Compass7",
      },
    },
  ],
  currentId: 20,
  shapes: [],
};

const getStore = async (caseId: number, fileId: number, type: BoardType) => {
  let data: BoardData;
  const route = router.currentRoute.value;
  if (fileId === -1 && route.name != 'drawShareFile') {
    const info = await getCaseInfo(caseId);
    if (info) {
      defaultStore.floors[0].title.value =
        info.caseTitle + "案发" + BoardTypeDesc[type];
      data = { ...defaultStore };
    } else {
      router.replace({ name: RouteName.vrmodel });
      throw "案件不存在";
    }
  } else {
    try {
      const getFunction = route.name == 'drawShareFile'?getuserFileInfo:getCaseFileImageInfo
      const fileInfo = await getFunction(fileId);
      console.log('fileInfo', fileInfo);
      if (fileInfo) {
      data = {
        ...fileInfo.content,
        ognFilesUrl: fileInfo.ognFilesUrl,
        id: fileInfo.filesId,
      };
      console.log('fileInfo', fileInfo, data);
    } else {
      router.replace({ name: RouteName.caseFile, params: { caseId } });
      throw "该图不存在！";
    }
    } catch (error) {
      console.error(error);
      throw "接口异常";
    }
  }
  return data;
};

export type BoardProps = {
  caseId: number;
  fileId: number;
  type: BoardType;
  dom: HTMLCanvasElement;
};
export type BoardState = {
  backDisabled: boolean;
  exixtsBgImage: boolean
  forwardDisabled: boolean;
  selectShape: BoardShape | null;
  addShape: MetaShapeType | null;
  addData: any;
};
export const useBoard = (props: Ref<BoardProps | null>) => {
  const board = ref<Board>();
  const state = ref<BoardState>({
    backDisabled: true,
    exixtsBgImage: false,
    forwardDisabled: true,
    selectShape: null,
    addShape: null,
    addData: null,
  });

  watchEffect(async (onCleanup) => {
    if (!props.value) {
      board.value = undefined;
      return;
    }

    const store = await getStore(
      props.value.caseId,
      props.value.fileId,
      props.value.type
    );
    console.log('store', store);
    const boardRaw = (board.value = await boardFactory(store, props.value.dom));
    console.log('boardRaw', boardRaw);
    state.value.exixtsBgImage = !!(store as any).floors[0].bgImage
    onCleanup(() => {
      boardRaw && boardRaw.destroy();
    });
  });

  watchEffect(
    () => {
      if (!props.value || !board.value) {
        return;
      }
      if (props.value.fileId === -1) {
        board.value
          .calcTableShape([
            ["案发时间", ""],
            ["案发地点", ""],
            ["绘图单位", ""],
            ["绘图人", ""],
            ["绘图时间", ""],
          ])
          .then((data) => {
            board.value!.setDefaultTable(data.content, null);
            board.value!.initHistory();
          });
      } else {
        board.value.initHistory();
      }
    },
    { flush: "post" }
  );

  watchEffect((onCleanup) => {
    if (!board.value) {
      return;
    }
    const boardRaw = board.value;

    console.log("开启监听");
    boardRaw.bus.on('exixtsBgImage', b => {
      console.error("a?", b)
      state.value.exixtsBgImage = b
    })
    boardRaw.bus.on("backDisabled", (dis) => (state.value.backDisabled = dis));
    boardRaw.bus.on(
      "forwardDisabled",
      (dis) => (state.value.forwardDisabled = dis)
    );
    boardRaw.bus.on("selectShape", (val) => {
      if (!val) {
        state.value.selectShape = null;
        return;
      }
      state.value.selectShape = val;
    });

    onCleanup(() => {
      boardRaw.bus.off("*" as any);
    });
  });

  watchEffect((onCleanup) => {
    if (board.value && state.value.addShape) {
      const cleaup = board.value.readyAddShape(
        state.value.addShape,
        state.value.addData || null,
        () => {
          state.value.addShape = null;
          state.value.addData = null;
        }
      );
      const keyupHandler = (ev: KeyboardEvent) => {
        if (ev.key === "Escape") {
          state.value.addShape = null;
          state.value.addData = null;
          cleaup();
        }
      };
      document.documentElement.addEventListener("keyup", keyupHandler);
      onCleanup(() => {
        document.documentElement.removeEventListener("keyup", keyupHandler);
      });
    }
  });

  return {
    board,
    state,
  };
};

export * from "./";
