<script setup lang="ts">
import { MapAreaType } from '@api/map';
import { saveSceneByGroupId, saveSceneById } from '@api/scene';
import type { EditorService } from '@core/editor.service';
import { isEmpty } from 'lodash-es';
import { computed } from 'vue';
import { inject, type InjectionKey, ref, type ShallowRef, watch } from 'vue';

type Props = {
  token: InjectionKey<ShallowRef<EditorService>>;
  editable?: boolean;
  sid?: string;
  id: string;
};
const props = defineProps<Props>();
const editor = inject(props.token)!;

//#region 接口
const updateScene = async () => {
  const json = editor.value.save();
  if (!json) return;
  if (props.sid) {
    await saveSceneByGroupId(props.id, props.sid, json);
  } else {
    const png = editor.value.toPng(8, undefined, true);
    await saveSceneById(props.id, json, png);
  }
};
//#endregion

const mode = ref<MapAreaType>();
watch(editor.value.mouseBrush, (v) => {
  if (!mode.value) return;
  const [p1, p2] = v ?? [];
  if (isEmpty(p1) || isEmpty(p2)) return;
  editor.value.addArea(p1, p2, mode.value);
  mode.value = undefined;
});

const canDelete = computed<boolean>(() => editor.value.current.value?.name === 'area');
</script>

<template>
  <a-space class="toolbar" :size="0">
    <a-button
      class="icon-btn tool-btn"
      :class="{ active: mode === MapAreaType.库区 }"
      size="large"
      :title="$t('添加库区')"
      @click="mode = MapAreaType.库区"
    >
      <i class="icon" :class="mode === MapAreaType.库区 ? 'area1-active' : 'area1'" />
    </a-button>
    <a-button
      class="icon-btn tool-btn ml-12"
      :class="{ active: mode === MapAreaType.互斥区 }"
      size="large"
      :title="$t('添加互斥区')"
      @click="mode = MapAreaType.互斥区"
    >
      <i class="icon" :class="mode === MapAreaType.互斥区 ? 'area11-active' : 'area11'" />
    </a-button>
    <a-button
      class="icon-btn tool-btn ml-12"
      :class="{ active: mode === MapAreaType.非互斥区 }"
      size="large"
      :title="$t('添加非互斥区')"
      @click="mode = MapAreaType.非互斥区"
    >
      <i class="icon" :class="mode === MapAreaType.非互斥区 ? 'area12-active' : 'area12'" />
    </a-button>

    <a-divider class="size-24 mh-8" type="vertical" />

    <a-button class="icon-btn tool-btn" size="large" :title="$t('保存')" @click="updateScene">
      <i class="mask save" />
    </a-button>
    <a-button class="icon-btn tool-btn ml-12" size="large" :title="$t('撤销')" @click="editor.undo()">
      <i class="mask undo" />
    </a-button>
    <a-button class="icon-btn tool-btn ml-12" size="large" :title="$t('重做')" @click="editor.redo()">
      <i class="mask redo" />
    </a-button>
    <a-button
      class="icon-btn tool-btn ml-12"
      size="large"
      :title="$t('删除区域')"
      @click="editor.deleteById(editor.current.value?.id)"
      :disabled="!canDelete"
    >
      <i class="mask trash" />
    </a-button>
  </a-space>
</template>
