<script setup lang="ts">
import { syncGroupRobotsById } from '@api/robot';
import { getSceneByGroupId, type GroupSceneDetail } from '@api/scene';
import { EditorService } from '@core/editor.service';
import { decodeTextFile, downloadFile, selectFile, textToBlob } from '@core/utils';
import { Modal } from 'ant-design-vue';
import { computed, onMounted, provide, ref, shallowRef, watch } from 'vue';
import { useI18n } from 'vue-i18n';

const EDITOR_KEY = Symbol('editor-key');

type Props = {
  sid: string;
  id: string;
};
const props = defineProps<Props>();

const { t } = useI18n();

//#region 接口
const readScene = async () => {
  const res = await getSceneByGroupId(props.id, props.sid);
  detail.value = res ?? undefined;
  title.value = res?.label ?? '';
  editor.value?.load(res?.json, editable.value, detail.value ?? {});
};

const syncGroup = async () => {
  await syncGroupRobotsById(props.id, props.sid);
};
//#endregion

const detail = ref<GroupSceneDetail>();
const title = ref<string>('');
watch(
  () => props.id,
  () => readScene(),
  { immediate: true, flush: 'post' },
);

const container = shallowRef<HTMLDivElement>();
const editor = shallowRef<EditorService>();
provide(EDITOR_KEY, editor);
onMounted(() => {
  editor.value = new EditorService(container.value!);
});

const editable = ref<boolean>(false);
watch(editable, (v) => editor.value?.setState(v));

const toSync = () =>
  Modal.confirm({
    class: 'confirm',
    title: t('您确定要同步组文件至机器人吗？'),
    content: t('请确保当前场景已经保存，否则可能导致同步的文件版本不正确。'),
    centered: true,
    cancelText: t('返回'),
    okText: t('同步'),
    onOk: () => syncGroup(),
  });

const importScene = async () => {
  const file = await selectFile('.scene');
  if (!file?.size) return;
  const json = await decodeTextFile(file);
  editor.value?.load(json, editable.value, detail.value ?? {});
};
const exportScene = () => {
  const json = editor.value?.save();
  if (!json) return;
  const blob = textToBlob(json);
  if (!blob?.size) return;
  const url = URL.createObjectURL(blob);
  downloadFile(url, `${title.value || 'unknown'}.scene`);
  URL.revokeObjectURL(url);
};

const show = ref<boolean>(true);
const current = ref<{ type: 'robot' | 'point' | 'line' | 'area'; id: string }>();
watch(
  () => editor.value?.selected.value[0],
  (v) => {
    const pen = editor.value?.getPenById(v);
    if (pen?.id) {
      current.value = { type: <'point' | 'line' | 'area'>pen.name, id: pen.id };
      return;
    }
    if (current.value?.type === 'robot') return;
    current.value = undefined;
  },
);
const isRobot = computed(() => current.value?.type === 'robot');
const isPoint = computed(() => current.value?.type === 'point');
const isRoute = computed(() => current.value?.type === 'line');
const isArea = computed(() => current.value?.type === 'area');

const selectRobot = (id: string) => {
  current.value = { type: 'robot', id };
  editor.value?.inactive();
};
</script>

<template>
  <a-layout class="full">
    <a-layout-header class="p-16" style="height: 64px">
      <a-flex justify="space-between" align="center">
        <a-typography-text class="title">{{ title }}</a-typography-text>
        <a-space align="center">
          <a-button v-if="editable" class="warning" @click="editable = false">
            <i class="icon exit size-18 mr-8" />
            <span>{{ $t('退出编辑器') }}</span>
          </a-button>
          <a-button v-else type="primary" @click="editable = true">
            <i class="icon edit size-18 mr-8" />
            <span>{{ $t('启用编辑器') }}</span>
          </a-button>
          <a-button @click="toSync">{{ $t('同步') }}</a-button>
          <a-button @click="importScene">{{ $t('导入') }}</a-button>
          <a-button @click="exportScene">{{ $t('导出') }}</a-button>
        </a-space>
      </a-flex>
    </a-layout-header>

    <a-layout class="p-16">
      <a-layout-sider :width="320">
        <a-tabs type="card">
          <a-tab-pane key="1" :tab="$t('机器人')">
            <RobotGroup
              v-if="editor"
              :token="EDITOR_KEY"
              :editable="editable"
              :current="current?.id"
              @change="selectRobot"
            />
          </a-tab-pane>
          <a-tab-pane key="2" :tab="$t('库区')">
            <PenGroups v-if="editor" :token="EDITOR_KEY" :current="current?.id" only-area1 />
          </a-tab-pane>
          <a-tab-pane key="3" :tab="$t('高级组')">
            <PenGroups v-if="editor" :token="EDITOR_KEY" :current="current?.id" />
          </a-tab-pane>
        </a-tabs>
      </a-layout-sider>
      <a-layout-content>
        <div ref="container" class="editor-container full"></div>
      </a-layout-content>
    </a-layout>
  </a-layout>

  <div v-if="editable" class="toolbar-container">
    <EditorToolbar v-if="editor" :token="EDITOR_KEY" :id="id" />
  </div>

  <template v-if="current?.id">
    <a-float-button style="top: 80px; right: 16px" shape="square" @click="show = !show">
      <template #icon><i class="icon detail" /></template>
    </a-float-button>
    <div v-if="show" class="card-container">
      <RobotDetailCard v-if="isRobot" :token="EDITOR_KEY" :current="current.id" />

      <template v-if="isPoint">
        <PointEditCard v-if="editable" :token="EDITOR_KEY" :id="current.id" />
        <PointDetailCard v-else :token="EDITOR_KEY" :current="current.id" />
      </template>
      <template v-if="isRoute">
        <RouteEditCard v-if="editable" :token="EDITOR_KEY" :id="current.id" />
        <RouteDetailCard v-else :token="EDITOR_KEY" :current="current.id" />
      </template>
      <template v-if="isArea">
        <AreaEditCard v-if="editable" :token="EDITOR_KEY" :id="current.id" />
        <AreaDetailCard v-else :token="EDITOR_KEY" :current="current.id" />
      </template>
    </div>
  </template>
</template>

<style scoped lang="scss">
.editor-container {
  background-color: transparent !important;
}

.toolbar-container {
  position: fixed;
  bottom: 40px;
  left: 50%;
  z-index: 100;
  transform: translateX(-50%);
}

.card-container {
  position: fixed;
  top: 80px;
  right: 64px;
  z-index: 100;
  width: 320px;
  height: calc(100% - 96px);
  overflow: visible;
  pointer-events: none;

  & > * {
    pointer-events: all;
  }
}
</style>
