<script setup lang="ts">
import type { NdmDeviceResultVO, Station } from '@/apis';
import { DeviceRenderer, DeviceTree, type DeviceTreeProps } from '@/components';
import type { UseDeviceSelectionReturn } from '@/composables';
import { SELECT_DEVICE_FN_INJECTION_KEY } from '@/constants';
import { useStationStore } from '@/stores';
import { NLayout, NLayoutContent, NLayoutSider } from 'naive-ui';
import { storeToRefs } from 'pinia';
import { provide, ref } from 'vue';

const stationStore = useStationStore();
const { stations } = storeToRefs(stationStore);

const selectedStation = ref<Station>();
const selectedDevice = ref<NdmDeviceResultVO>();

// 获取设备树暴露出来的 `selectDevice` 函数，并将其提供给子组件
const selectDeviceFn = ref<UseDeviceSelectionReturn['selectDevice']>();
const onExposeSelectDeviceFn: DeviceTreeProps['onExposeSelectDeviceFn'] = (fn) => {
  selectDeviceFn.value = fn;
};
provide(SELECT_DEVICE_FN_INJECTION_KEY, selectDeviceFn);

const onAfterSelectDevice: DeviceTreeProps['onAfterSelectDevice'] = (device, stationCode) => {
  selectedDevice.value = device;
  selectedStation.value = stations.value.find((station) => station.code === stationCode);
};
</script>

<template>
  <NLayout has-sider style="height: 100%">
    <NLayoutSider bordered :width="600" :collapsed-width="0" show-trigger="bar">
      <DeviceTree :events="['select', 'manage']" :sync-route="true" :device-prefix-label="'查看'" @expose-select-device-fn="onExposeSelectDeviceFn" @after-select-device="onAfterSelectDevice" />
    </NLayoutSider>
    <NLayoutContent :content-style="{ padding: '8px 8px 8px 24px' }">
      <template v-if="selectedStation && selectedDevice">
        <DeviceRenderer :station="selectedStation" :ndm-device="selectedDevice" />
      </template>
    </NLayoutContent>
  </NLayout>
</template>

<style scoped lang="scss"></style>
