<script setup lang="ts">
import type { NdmServerResultVO, Station } from '@/apis';
import { DeviceRawCard, ServerCurrentDiag, ServerHistoryDiag, ServerUpdate } from '@/components';
import { usePermission } from '@/composables';
import { PERMISSION_TYPE_LITERALS } from '@/enums';
import { useSettingStore } from '@/stores';
import { NCard, NPageHeader, NScrollbar, NTab, NTabs } from 'naive-ui';
import { storeToRefs } from 'pinia';
import { computed, ref, toRefs, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const props = defineProps<{
  ndmDevice: NdmServerResultVO;
  station: Station;
}>();

const route = useRoute();
const router = useRouter();

const settingStore = useSettingStore();
const { showDeviceRawData } = storeToRefs(settingStore);

const { hasPermission } = usePermission();

const { ndmDevice, station } = toRefs(props);

const showPageHeader = computed(() => {
  return !!route.query['fromPage'];
});
const onBack = () => {
  router.push({ path: `${route.query['fromPage']}` });
};

const activeTabName = ref('当前诊断');
const onTabChange = (name: string) => {
  activeTabName.value = name;
};
watch([ndmDevice, showDeviceRawData], ([newDevice, showRaw], [oldDevice]) => {
  if (newDevice.id !== oldDevice.id || (!showRaw && activeTabName.value === '原始数据')) {
    activeTabName.value = '当前诊断';
  }
});
</script>

<template>
  <NCard hoverable style="height: 100%" :header-style="{ padding: '12px' }" :content-style="{ height: '100%', padding: '0', overflow: 'hidden' }">
    <template #header>
      <NPageHeader v-if="showPageHeader" @back="onBack" />
      <NTabs :value="activeTabName" @update:value="onTabChange">
        <NTab name="当前诊断">当前诊断</NTab>
        <NTab name="历史诊断">历史诊断</NTab>
        <NTab v-if="hasPermission(station.code, PERMISSION_TYPE_LITERALS.OPERATION)" name="修改设备">修改设备</NTab>
        <NTab v-if="showDeviceRawData" name="原始数据">原始数据</NTab>
      </NTabs>
    </template>
    <template #default>
      <NScrollbar x-scrollable :content-style="{ padding: '0 12px 12px 12px' }">
        <template v-if="activeTabName === '当前诊断'">
          <ServerCurrentDiag :ndm-device="ndmDevice" :station="station" />
        </template>
        <template v-if="activeTabName === '历史诊断'">
          <ServerHistoryDiag :ndm-device="ndmDevice" :station="station" />
        </template>
        <template v-if="activeTabName === '修改设备'">
          <ServerUpdate :ndm-device="ndmDevice" :station="station" />
        </template>
        <template v-if="activeTabName === '原始数据'">
          <DeviceRawCard :ndm-device="ndmDevice" />
        </template>
      </NScrollbar>
    </template>
  </NCard>
</template>

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