<template>
  <a-space>
    <!-- 平台选择框 -->
    <a-select
      style="width:280px"
      v-model:value="innerPlatformId"
      placeholder="请选择平台"
      :disabled="loading"
    >
      <a-select-option
        v-for="item in platforms"
        :key="`platform-${item.id}`"
        :value="item.id"
      >
        {{ item.description || item.name || '未命名平台' }}
      </a-select-option>
    </a-select>

    <!-- 组件选择框 -->
    <a-select
      style="width:280px;"
      v-model:value="innerComponentId"
      placeholder="请选择组件"
      :disabled="!innerPlatformId || loading"
    >
      <a-select-option
        v-for="item in selectedPlatformComponents"
        :key="`component-${item.id}`"
        :value="item.id"
      >
        {{ item.description || item.name || '未命名组件' }}
      </a-select-option>
    </a-select>
  </a-space>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, type PropType, ref, watch } from 'vue';
import type { Platform, PlatformComponent, PlatformComponentPayload, PlatformWithComponents, PlatformWithComponentsResponse } from '../types';
import { findAllPlatformWithComponents } from './api';

export default defineComponent({
  name: 'PlatformSelect',
  props: {
    platformId: {
      type: [Number, null] as PropType<number | null>,
      required: false,
      default: null,
    },
    componentId: {
      type: [Number, null] as PropType<number | null>,
      required: false,
      default: null,
    },
  },
  emits: {
    change: (payload: PlatformComponentPayload) => true,
  },
  setup(props, { emit }) {
    const loading = ref<boolean>(true);
    const platforms = ref<PlatformWithComponents[]>([]);
    const platformMap = ref<Map<number, Platform>>(new Map());
    const componentMap = ref<Map<number, PlatformComponent>>(new Map());

    const innerPlatformId = ref<number | null>(null);
    const innerComponentId = ref<number | null>(null);

    const selectedPlatformComponents = computed(() => {
      const platform = platforms.value.find(p => p.id === innerPlatformId.value);
      return platform?.components || [];
    });

    const loadData = async () => {
      try {
        loading.value = true;
        const res: PlatformWithComponentsResponse = await findAllPlatformWithComponents();
        const data = res.data || [];

        platforms.value = data;
        platformMap.value.clear();
        componentMap.value.clear();

        data.forEach(platform => {
          platformMap.value.set(platform.id, platform);
          platform.components?.forEach(component => {
            componentMap.value.set(component.id, component);
          });
        });

        innerPlatformId.value = props.platformId;
        innerComponentId.value = props.componentId;
      } catch (err) {
        console.error('加载平台组件失败:', err);
      } finally {
        loading.value = false;
      }
    };

    const emitChange = () => {
      // 根据ID获取完整对象
      const platform = platformMap.value.get(innerPlatformId.value || -1) || null;
      const component = componentMap.value.get(innerComponentId.value || -1) || null;

      const validComponent = component && component.platformId === innerPlatformId.value
        ? component
        : null;

      emit('change', {
        platform: platform ? {
          id: platform.id,
          name: platform.name,
          description: platform.description,
          scenarioId: platform.scenarioId,
        } : null,
        component: validComponent,
      } as PlatformComponentPayload);
    };

    watch([() => props.platformId, () => props.componentId],
      ([newPlatformId, newComponentId]) => {
        if (!loading.value) {
          innerPlatformId.value = newPlatformId;
          innerComponentId.value = newComponentId;
        }
      },
      { immediate: true, deep: false },
    );

    watch(innerPlatformId, (newVal) => {
      if (newVal !== innerPlatformId.value) {
        innerComponentId.value = null;
      }
      emitChange();
    });

    watch(innerComponentId, emitChange);

    onMounted(() => {
      loadData();
    });

    return {
      loading,
      platforms,
      selectedPlatformComponents,
      innerPlatformId,
      innerComponentId,
    };
  }
});
</script>