<script setup lang="ts">
import type { RobotRealtimeInfo } from '@api/robot';
import { getSceneByGroupId, getSceneById, monitorRealSceneById, monitorSceneById } from '@api/scene';
import { EditorService } from '@core/editor.service';
import { useViewState } from '@core/useViewState';
import { message } from 'ant-design-vue';
import { isNil } from 'lodash-es';
import { computed, onMounted, onUnmounted, provide, ref, shallowRef, watch } from 'vue';
import { useRoute } from 'vue-router';

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

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

// 获取路由信息以判断当前模式
const route = useRoute();
const isMonitorMode = computed(() => route.path.includes('/monitor'));

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

const monitorScene = async () => {
  client.value?.close();
  // 根据路由路径是否是真实场景监控决定使用哪个监控接口
  const ws = isMonitorMode.value ? await monitorRealSceneById(props.sid) : await monitorSceneById(props.sid);
  if (isNil(ws)) return;
  ws.onmessage = (e) => {
    const { id, x, y, active, angle, path, ...rest } = <RobotRealtimeInfo>JSON.parse(e.data || '{}');
    if (!editor.value?.checkRobotById(id)) return;
    editor.value?.updateRobot(id, rest);
    if (isNil(x) || isNil(y)) {
      editor.value.updatePen(id, { visible: false });
    } else {
      editor.value.refreshRobot(id, { x, y, active, angle, path });
    }
  };
  client.value = ws;
};
//#endregion

const title = ref<string>('');

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

const client = shallowRef<WebSocket>();
onMounted(async () => {
  await readScene();
  await editor.value?.initRobots();
  await monitorScene();
  // 自动保存和恢复视图状态
  await handleAutoSaveAndRestoreViewState();
});
onUnmounted(() => {
  client.value?.close();
});

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();
};

// 视图状态管理
const { saveViewState, autoSaveAndRestoreViewState, isSaving } = useViewState();

// 保存当前视图状态
const handleSaveViewState = async () => {
  if (!editor.value) return;

  try {
    await saveViewState(editor.value, props.sid, props.id);
    message.success('视图状态保存成功');
  } catch {
    message.error('视图状态保存失败');
  }
};

// 自动保存和恢复视图状态
const handleAutoSaveAndRestoreViewState = async () => {
  if (!editor.value) return;

  await autoSaveAndRestoreViewState(editor.value, props.sid, props.id);
};
</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 }}--{{ isMonitorMode ? '场景监控' : '场景仿真' }}</a-typography-text>
        <a-button type="primary" :loading="isSaving" @click="handleSaveViewState"> 保存比例 </a-button>
      </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('机器人')">
            <RobotGroups v-if="editor" :token="EDITOR_KEY" :sid="sid" :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>

  <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" />
      <PointDetailCard v-if="isPoint" :token="EDITOR_KEY" :current="current.id" />
      <RouteDetailCard v-if="isRoute" :token="EDITOR_KEY" :current="current.id" />
      <AreaDetailCard v-if="isArea" :token="EDITOR_KEY" :current="current.id" />
    </div>
  </template>
</template>

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

.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>
