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

    <!-- 组件选择框 -->
    <a-select
      style="width:280px;"
      v-model:value="selectedComponentId"
      :placeholder="'请选择组件'"
      :disabled="!selectedPlatform"
    >
      <a-select-option
        v-for="item in selectedPlatformComponents"
        :key="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 } from '../types';
import { findAllPlatformWithComponents } from './api';

export default defineComponent({
  props: {
    placeholder: {
      type: String,
      default: '',
    },
    payload: {
      type: [Object,null] as PropType<PlatformComponentPayload | null>,
      required: false,
      default: ({
        platform: null,
        component: null,
      }),
    },
  },
  emits: [
    'change',
  ],
  setup(props, { emit }) {
    const platforms = ref<PlatformWithComponents[]>([]);
    const platformMapping = ref<Map<number, PlatformWithComponents>>(new Map());
    const componentsMapping = ref<Map<number, PlatformComponent>>(new Map());

    const selectedPlatformComponents = ref<PlatformComponent[]>([])

    const selectedPlatform = ref<PlatformWithComponents|null>(null);
    const selectedPlatformId = ref<number|null>(null);

    const selectedComponent = ref<PlatformComponent|null>(null);
    const selectedComponentId = ref<number|null>(null);

    const load = () => {
      platforms.value = [];
      platformMapping.value.clear();
      componentsMapping.value.clear();

      findAllPlatformWithComponents().then(re => {
        platforms.value = re.data ?? [];
        platforms.value.forEach(platform => {
          platformMapping.value.set(platform.id, platform);
          if(platform.components){
            platform.components.forEach(comp=> {
              componentsMapping.value.set(comp.id, comp)
            })
          }
        });
      }).catch(err => {
        console.error('加载平台组件数据失败：', err);
      });
    };

    const triggerChange = ()=> {
      emit('change', {
        platform: selectedPlatform.value ? {
          id: selectedPlatform.value?.id,
          name: selectedPlatform.value?.name,
          description: selectedPlatform.value?.description,
        } : null,
        component: selectedComponent.value ? {
          id: selectedComponent.value.id,
          name: selectedComponent.value.name,
          description: selectedComponent.value.description,
          num: selectedComponent.value.num,
          platformId: selectedComponent.value.platformId,
          type: selectedComponent.value.type,
        } : null,
      })
    }

    watch(()=> props.payload, (n: PlatformComponentPayload | null | undefined)=> {
      if(n && n.platform){
        selectedPlatform.value = platformMapping.value.get(n.platform?.id) ?? null;
        selectedPlatformId.value = selectedPlatform.value?.id ?? null;
        selectedPlatformComponents.value = selectedPlatform.value?.components ?? []
      } else {
        selectedPlatform.value = null;
        selectedPlatformId.value = null;
        selectedPlatformComponents.value = []
      }

      if(n && n.component){
        selectedComponent.value = n.component;
        selectedComponentId.value = selectedComponent.value?.id ?? null;
      } else {
        selectedComponent.value = null;
        selectedComponentId.value = null;
      }

      console.error('watch',n)
    }, {deep: true, immediate: true})


    watch(()=> selectedPlatformId.value,(n: null | number)=> {
      if(n && platformMapping.value.get(n)){
        selectedPlatform.value = platformMapping.value.get(n) ?? null;
        selectedPlatformComponents.value = selectedPlatform.value?.components ?? []
      } else {
        selectedPlatform.value = null;
        selectedPlatformComponents.value = []
      }
      selectedComponentId.value = null;

      triggerChange();
    })

    watch(()=> selectedComponentId.value,(n: null | number)=> {
      if(n && componentsMapping.value.get(n)){
        selectedComponent.value = componentsMapping.value.get(n) ?? null;
      } else {
        selectedComponent.value = null;
      }

      triggerChange();
    })

    onMounted(() => load());

    return {
      platforms,
      selectedPlatformComponents,
      selectedPlatform,
      selectedPlatformId,
      selectedComponent,
      selectedComponentId,
    };
  },
});
</script>