import { defineStore } from "pinia";
import { useProjectStore } from "@/store/modules/project";

import { ReferLine } from "#/project";

interface StageState {
  // 缩放比例
  scale: number;
  // 大屏宽度
  width: number;
  // 大屏高度
  height: number;
  // x坐标原点位置
  originX: number;
  // y坐标原点位置
  originY: number;
  // 视口宽度
  viewportWidth: number;
  // 视口高度
  viewportHeight: number;
  // 屏幕中心原点x
  centerX: number;
  // 屏幕中心原点y
  centerY: number;
  // x坐标滚动
  scrollX: number;
  // y坐标滚动
  scrollY: number;
  // 容器宽度
  wrapperWidth: number;
  // 容器高度
  wrapperHeight: number;
  // 显示图层面板
  showLayer: boolean;
}

export const useStageStore = defineStore({
  id: 'stage',
  state: (): StageState => ({
    scale: 1,
    width: 1280,
    height: 720,
    originX: 0,
    originY: 0,
    viewportWidth: 0,
    viewportHeight: 0,
    centerX: 0,
    centerY: 0,
    scrollX: 0,
    scrollY: 0,
    wrapperWidth: 0,
    wrapperHeight: 0,
    showLayer: false
  }),
  getters: {
    // 根据滚动和缩放，重新计算辅助线位置
    getReferLines(state): ReferLine[] {
      const { scale, scrollX, scrollY, originX, originY } = state;
      const projectStore = useProjectStore();
      return projectStore.referLines
      .map((line) => {
        
        let x = line.x || 0;
        let y = line.y || 0;
        if(line.type === 'horizontal') {
          x = originX + line.value * scale - scrollX + 20;
        } else {
          y = originY + line.value * scale - scrollY + 20;
        }

        return {
          ...line,
          x,
          y
        }
      })
      .filter((line) => {
        // 过滤掉不在视口内的辅助线
        if(line.type === 'horizontal') {
          return line.x > 20 && line.x < state.viewportWidth;
        } else {
          return line.y > 20 && line.y < state.viewportHeight;
        }
      })
    }
  },
  actions: {
    setSize(width: number, height: number) {
      this.width = width;
      this.height = height;
    },
    setStageWaraaperSize(width: number, height: number) {
      this.wrapperWidth = width;
      this.wrapperHeight = height;
    },
    setViewportSize(width: number, height: number) {
      this.viewportWidth = width;
      this.viewportHeight = height;
    },
    setOriginPoint(originX: number, originY: number) {
      this.originX = originX;
      this.originY = originY;
    },
    setScale(scale: number) {
      this.scale = scale;
    },
    setCenterPoint(x: number, y: number) {
      this.centerX = x;
      this.centerY = y;
    },
    setScroll(x: number, y: number) {
      this.scrollX = x;
      this.scrollY = y;
    },
    toggleShowLayer() {
      this.showLayer = !this.showLayer;
    }
  }
})