<template>
  <RightPano
    v-if="
      custom.currentModel &&
      active &&
      (custom.showMode === 'fuse' || !getSceneModel(custom.currentModel)?.supportPano())
    "
    class="merge-layout"
  >
    <div class="actions-group">
      <Actions :items="actionItems" v-model:current="currentItem" />
      <Actions
        class="merge-action"
        v-model:current="currentAction"
        :items="othActions"
        single
      />
    </div>
    <ui-group>
      <ui-group-option label="等比缩放">
        <template #icon>
          <ui-icon
            class="set-prop"
            ctrl
            :class="{ disabled: isOld || currentItem }"
            @click="router.push({ 
              name: RoutesName.proportion, 
              params: { id: custom.currentModel!.id, save: '1' },
            })"
            type="ratio"
            tip="设置比例"
          />
        </template>
        <ui-input
          type="number"
          class="scale-input"
          v-model="custom.currentModel.scale"
          v-bind="modelRange.scaleRange"
          :ctrl="false"
          width="100%"
        >
          <template #preIcon><ui-icon type="a-1b1" /></template>
          <template #icon>%</template>
        </ui-input>
      </ui-group-option>
      <ui-group-option label="不透明度">
        <ui-input
          type="range"
          v-model="custom.currentModel.opacity"
          v-bind="modelRange.opacityRange"
          :ctrl="false"
          width="100%"
        >
          <template #icon>%</template>
        </ui-input>
      </ui-group-option>
    </ui-group>
  </RightPano>
</template>

<script lang="ts" setup>
import { RoutesName, router } from "@/router";
import { RightPano } from "@/layout";
import { autoSaveFuseModels, defaultFuseModelAttrs, isOld } from "@/store";
import { asyncTimeout, togetherCallback } from "@/utils";
import { sdk, getSceneModel, modelRange, getFuseModel, getSupportPano } from "@/sdk";
import { useViewStack, useActive } from "@/hook";
import {
  showLeftPanoStack,
  custom,
  modelsChangeStoreStack,
  showRightPanoStack,
} from "@/env";
import { ref, nextTick, watchEffect, computed, watch, reactive } from "vue";
import { Dialog } from "bill/expose-common";

import Actions from "@/components/actions-merge/index.vue";

import type { ActionsProps, ActionsItem } from "@/components/actions/index.vue";
import { listener } from "@/components/drawing/hook";
import { clickListener, getOffset } from "@/utils/event";
import { useRMenus } from "@/components/right-menu";
import { actionItems, currentItem } from ".";

const active = useActive();

const othActions = reactive([
  {
    icon: "rectification",
    text: "配准",
    single: true,
    disabled: computed(() => isOld.value || !!currentItem.value),
    action: () => {
      router.push({
        name: RoutesName.registration,
        params: { id: custom.currentModel!.id, save: "1" },
      });
    },
  },
  {
    icon: "reset",
    text: "恢复默认",
    single: true,
    action: () => {
      reset();
    },
  },
]);
const currentAction = ref<any>();

watchEffect(() => {
  if (!custom.currentModel) {
    currentItem.value = null;
  }
});

watch(
  () => custom.currentModel,
  () => {
    let old = currentItem.value;
    currentItem.value = null;
    console.error("currentItem", currentItem.value, old);
    asyncTimeout(16).then(() => {
      currentItem.value = old;
      console.log("change", currentItem.value);
    });
  },
  { flush: "post" }
);

const reset = async () => {
  if (custom.currentModel && (await Dialog.confirm("确定恢复默认？此操作无法撤销"))) {
    const rotation = getSceneModel(custom.currentModel)!.getDefaultRotation();
    Object.assign(custom.currentModel, {
      ...defaultFuseModelAttrs,
      rotation: {
        x: rotation.x,
        y: rotation.y,
        z: rotation.z,
      },
    });
    await nextTick();
    custom.currentModel && (custom.currentModel.bottom = 0);
  }
};

let unMount: (() => void) | null = null;
useViewStack(() =>
  togetherCallback([
    showLeftPanoStack.push(ref(true)),
    showRightPanoStack.push(computed(() => !!custom.currentModel)),
    modelsChangeStoreStack.push(ref(true)),
    clickListener(
      document.querySelector("#layout-app") as HTMLDivElement,
      (pixel) => {
        const pos = sdk.getPositionByScreen(pixel);
        if (!custom.currentModel) return;
        unMount && unMount();
        setTimeout(() => {
          unMount = useRMenus(pixel, [
            {
              label: "移动到这里",
              icon: "move",
              handler() {
                getSceneModel(custom.currentModel!)?.moveModelTo(pixel, pos?.worldPos);
              },
            },
          ]);
        });
      },
      2
    ),
    () => (currentItem.value = null),
  ])
);

watchEffect(() => console.error(currentItem.value), { flush: "sync" });
useViewStack(autoSaveFuseModels);
useViewStack(() => {
  const stopWatch = watchEffect(() => {
    if (custom.showMode === "pano") {
      sdk.hideGrid();
    } else {
      sdk.showGrid();
    }
  });
  return () => {
    sdk.hideGrid();
    stopWatch();
  };
});
</script>

<style lang="scss" scoped>
.actions-group {
  position: absolute;
  bottom: 100%;
  left: 0;
  width: 100%;
  margin-bottom: 10px;
  gap: 10px;
  display: flex;
}
.model-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;

  p {
    font-size: 14px;
    color: #fff;
  }
}

.model-desc {
  color: rgba(255, 255, 255, 0.6);
  line-height: 18px;
  font-size: 12px;
}

.model-action {
  display: flex;
  align-items: center;
  > * {
    margin-left: 20px;
  }
}
</style>

<style lang="scss">
.merge-layout {
  position: relative;
  overflow: initial !important;
  top: calc(var(--editor-head-height) + var(--header-top) + 70px) !important;

  .ui-input .text.suffix input {
    padding-left: 5px;
    padding-right: 15px;
  }
  .ui-input .text.suffix .retouch {
    right: 5px;
  }
}

.set-prop {
  cursor: pointer;
}

.scale-input input {
  text-align: right;
  padding-right: 20px !important;
}
</style>
