import { css } from "@linaria/core";

import { defineComponent, onMounted, reactive, ref } from "vue";

import { object } from "vue-types";

import { LoadingOutlined } from "@ant-design/icons-vue";
import { Spin } from "ant-design-vue";

import { useList } from "@/modules/list";
import { useQueditor } from "@queenjs-modules/queditor";

function getQuery() {
  const search = location.href.split("?")[1];
  const ret: { [name: string]: string } = {};
  if (search) {
    const aParams = search.split("&");
    const len = aParams.length;
    for (let i = 0; i < len; i++) {
      const aParam = aParams[i].split("=");
      const sParamName = decodeURIComponent(aParam[0]);
      const sParamValue = decodeURIComponent(aParam[1]);
      ret[sParamName] = sParamValue;
    }
  }
  return ret;
}
const Canvas3d = defineComponent({
  props: {
    pack: object<any>(),
  },
  emits: ["init"],
  setup(props, { emit }) {
    const state = reactive({ loaded: false });
    const { actions, components, controls, store } = useQueditor();
    store.showLoading = false;
    const initQueen = async () => {
      actions.initPack(props.pack.source);
      actions.on("initQueen3dScene:success", () => {
        const queen3d = controls.queen3dCtrl.queen3d;
        const app = controls.queen3dCtrl.queen3d.getAppInstance();

        app.setNoPan(true);

        queen3d.setTransparntBg();

        queen3d.setControllerZoom(0.5, 6);

        if (queen3d.picker) {
          queen3d.picker.enable = false;
        }

        queen3d.redraw();
        state.loaded = true;
        emit("init", true);
      });
    };
    initQueen();

    return () => (
      <components.Viewport.Canvas
        class={`${CanvasStyle} ${state.loaded ? "loaded" : null}`}
      />
    );
  },
});

export default defineComponent({
  setup(props) {
    const query = getQuery();
    const meshId = query.id;
    const dialogId = query.dialogid;
    const packRef = ref();
    const state = reactive({ loaded: false, loading: true });
    const { actions } = useList();
    onMounted(async () => {
      const res = await actions.loadPack3d({ meshId: meshId } as any);
      packRef.value = res?.data;
      state.loaded = true;
      document.addEventListener("mousedown", () => {
        window.parent.postMessage(JSON.stringify({ type: "start", dialogId }));
      });
      document.addEventListener("touchstart", () => {
        window.parent.postMessage(JSON.stringify({ type: "start", dialogId }));
      });
      document.addEventListener("mouseup", () => {
        window.parent.postMessage(JSON.stringify({ type: "end", dialogId }));
      });
      document.addEventListener("touchend", () => {
        window.parent.postMessage(JSON.stringify({ type: "end", dialogId }));
      });
    });

    return () => {
      return (
        <>
          {state.loaded && (
            <Canvas3d
              pack={packRef.value}
              onInit={(v) => {
                state.loading = false;
              }}
            />
          )}

          {state.loading && (
            <Spin
              class={loadingStyle}
              indicator={
                <LoadingOutlined style={{ fontSize: "40px", color: "#fff" }} />
              }
            />
          )}
        </>
      );
    };
  },
});

// const rootStyle = css`
//   padding: 30px;
//   background-color: red;
// `;

const loadingStyle = css`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
`;
const CanvasStyle = css`
  width: 100%;
  height: 100%;
  visibility: hidden;
  &.loaded {
    visibility: inherit;
  }
`;
