import mitt from "mitt";
import { text, table, compass, title, bgImage, customImage } from "./shape";
import Layer from "./editCAD/Layer";
import { history } from "./editCAD/History/History.js";
import { uploadFile } from "@/store/system";
import { uploadNewFile, uploadFiles } from "@/store/case";

// const toStore = (refs) => {
//   return {
//     bgImage: refs.baseMap?.data || null,
//     shapes: refs.shapes.map(shape => shape.data)
//   }
// }

export const create = async (store, canvas) => {
  const refs = {
    ctx: canvas.getContext("2d"),
    bus: mitt(),
    shapes: [],
    baseMap: null,
  };

  console.log('ssssss', store)
  setTimeout(() => {
    console.log(!!store.floors[0].bgImage)
    refs.bus.emit('exixtsBgImage', !!store.floors[0].bgImage)
  }, 100)
  
  const layer = new Layer();
  await layer.start(canvas, store);
  const defaultData = {
    color: "rgba(0,0,0,1)",
    text: "",
    fontSize: 12,
    scale: 1,
    rotate: 0,
    content: [
      { width: 160, height: 60, value: "", colIndex: 0, rowIndex: 0 },
      { width: 160, height: 60, value: "", colIndex: 1, rowIndex: 0 },
    ],
  };

  layer.uiControl.bus.on("showAttribute", ({ type, value: data }) => {
    data =
      data && typeof data === "object"
        ? Object.assign({ ...defaultData }, data)
        : { ...defaultData };

    const method = Object.fromEntries(
      Object.keys(data).map((key) => [
        `set${key.slice(0, 1).toUpperCase() + key.slice(1)}`,
        (value, save = true) => {
          update({ [key]: value, save });
        },
      ])
    );

    const shape = {
      data: { type, ...data },
      ...method,
      delete: () => {
        layer.uiControl.clearUI();
        layer.uiControl.setAttributes(type, "delete");
        if (type === bgImage) {
          refs.bus.emit('exixtsBgImage', false)
        }
      },
    };
    const update = (newData) => {
      layer.uiControl.setAttributes(type, "update", { ...newData, version: 2 });
    };
    refs.bus.emit("selectShape", shape);
  });
  layer.uiControl.bus.on("hideAttribute", () => {
    refs.bus.emit("selectShape", null);
  });
  history.bus.on("undoAvailable", (availabe) => {
    refs.bus.emit("backDisabled", !availabe);
  });
  history.bus.on("redoAvailable", (availabe) =>
    refs.bus.emit("forwardDisabled", !availabe)
  );

  setTimeout(() => {
    // layer.uiControl.bus.emit('showAttribute', { type: compass, data: 0 })
    // history.bus.emit('undoAvailable', true)
    // history.bus.emit('redoAvailable', true)
  }, 100);

  let run = false;
  const board = {
    bus: refs.bus,
    el: canvas,
    async getStore() {
      const data = layer.uiControl.exportJSON();
      const floor = data.floors[0];
      const shapes = [];

      if (floor) {
        const bgImage = floor.bgImage?.url;
        if (bgImage && bgImage.includes("blob:")) {
          const url = await fetch(bgImage)
            .then((res) => res.blob())
            .then((blob) =>
              uploadFile(new File([blob], (store.id || "image") + ".png"))
            );

          floor.bgImage.url = url;
          console.log(url);
        }
        shapes.push({ type: title, text: floor.title.value });
      }
      return {
        id: store.id,
        shapes,
        ognFilesUrl: store.ognFilesUrl,
        ...layer.uiControl.exportJSON(),
      };
    },
    viewInit() {
      layer.uiControl.menu_flex();
    },
    unSelectShape() {
      layer.uiControl.clearUI();
    },
    setDefaultTable(rbTable, rtTable) {
      if (rbTable) {
        layer.uiControl.initDownTable(rbTable);
      }
      if (rtTable) {
        layer.uiControl.initTopTable(rtTable);
      }
    },
    initHistory() {
      history.init();
    },
    readyAddShape(shapeType, data, onFine) {
      layer.uiControl.selectUI = shapeType;
      if (customImage === shapeType) {
        layer.uiControl.setAttributes(shapeType, "upload", {
          url: data,
          version: 2,
        });
        onFine();
      } else {
        layer.uiControl.updateEventNameForSelectUI();
        const finePack = () => {
          layer.uiControl.bus.off("hideUI", finePack);
          onFine();
        };
        layer.uiControl.bus.on("hideUI", finePack);
      }
    },
    back() {
      if (run) return;
      run = true;
      console.log("撤销");
      history.handleUndo().then(() => {
        console.log("撤销完成");
        run = false;
      });
    },
    forward() {
      if (run) return;
      run = true;
      console.log("回复");
      history.handleRedo().then(() => {
        console.log("回复完成");
        run = false;
      });
    },
    setImage(url) {
      refs.bus.emit('exixtsBgImage', true)
      layer.uiControl.setAttributes(bgImage, "upload", { url, scale: 1 });
    },
    clear() {
      history.clear()
    },
    export() {
      return new Promise((resolve) => {
        layer.uiControl.exportImg(canvas, "cover.jpg", (blob) => {
              // const file = new File([blob], `asdasd.jpg`)
              // window.open(URL.createObjectURL(file))
              // console.log(blob)
              resolve(blob)
        });
      });
      const $canvas = document.createElement("canvas");
      $canvas.width = canvas.width;
      $canvas.height = canvas.height;

      const cctx = $canvas.getContext("2d");
      cctx.rect(0, 0, $canvas.width, $canvas.height);
      cctx.fillStyle = "rgba(255,255,255,1)";
      cctx.fill();
      cctx.drawImage(
        canvas,
        0,
        0,
        $canvas.width,
        $canvas.height,
        0,
        0,
        canvas.width,
        canvas.height
      );

      return new Promise((resolve) => {
        // resolve(layer.uiControl.menu_screenShot())
        $canvas.toBlob(resolve, "image/jpeg", 1);
      });
    },
    calcTableShape(data) {
      return new Promise((resolve) => {
        const tableData = {
          data: {
            type: table,
            content: data
              .map((cols, index) => [
                {
                  rowIndex: index,
                  colIndex: 0,
                  width: 0,
                  height: 0,
                  value: cols[0],
                },
                {
                  rowIndex: index,
                  colIndex: 1,
                  width: 0,
                  height: 0,
                  value: cols[1],
                },
              ])
              .flat(),
          },
          setContent(newData) {
            board.bus.emit("selectShape", null);
            resolve({ type: table, content: newData });
          },
          autoSet: true,
        };
        board.bus.emit("selectShape", tableData);
      });
    },
    destroy() {},
  };

  return board;
};

export * from "./shape";

export default create;

export { shapes } from "./shapes";
