<script setup lang="ts">
import { ref, reactive, computed, onMounted, shallowRef } from 'vue';
import ProductComponent from './component/product/Product.vue';
import ResourceComponent from './component/resource/Resource.vue';
import PictureComponent from './component/picture/Picture.vue';
import MonitorComponent from './component/monitor/Monitor.vue';
import VirtualComponent from './component/virtual/Virtual.vue';
import QuickAccessComponent from './component/quickAccess/QuickAccess.vue';
import LoginInfoComponent from './component/loginInfo/LoginInfo.vue';
import { IMonitorInfo } from './home.datatype';
import { getOverView, getThermalOverView } from './services/home.service';
import { factoryMonitorInfo } from './utils/monitor.util';
import { useHome, WebStyleType, IPVersionType } from './hooks/useHome';
import StyleDefault from './component/skeleton/StyleDefault.vue';
import StyleBeautiful from './component/skeleton/StyleBeautiful.vue';
import StyleIBMA from './component/skeleton/StyleIBMA.vue';
import StyleSimple from './component/skeleton/StyleSimple.vue';
import StyleStandard from './component/skeleton/StyleStandard.vue';
import HomeDefault from './component/template/HomeDefault.vue';
import HomeBeautiful from './component/template/HomeBeautiful.vue';
import HomeIBMA from './component/template/HomeIBMA.vue';
import HomeSimple from './component/template/HomeSimple.vue';
import HomeStandard from './component/template/HomeStandard.vue';
import useStore from '@/stores';
import { NavTheme } from '@/model/base-enum';
import { traduction } from '@/utils/language';
import { setStoreData } from '@/utils/composition';
import { summaryData } from './summaryMockData';

const store = useStore();
const picInfo = reactive({
  ProductImage: '',
  ProductAlias: '',
  ProductName: '',
});
const ipAddress = reactive({
  addressIPv4: '',
  addressIPv6: '',
  ipVersion: '',
});
const deviceInfo = reactive({ data: null });
const resourceInfo = reactive({ data: null });
const isShow = ref(false);
const fusionPartition = ref('');
const monitorInfo = reactive({ data: {} as IMonitorInfo });
// 组件初始化时定义key
const uploadKey = ref(new Date().getTime());
let leftNavTheme = computed(() => {
  return useStore().state.loct.navStyle;
});

const overviewInfo = computed(() => {
  return useStore()?.state.glob?.overviewData;
});
const kvmClientUrl = ref('');
const { getWebStyle } = useHome();
const webStyle = getWebStyle();
let webStyleComponent = shallowRef();
let skeletonComponent = shallowRef();
onMounted(() => {
  webStyleComponent.value = getWebStyleComponent();
  skeletonComponent.value = getSkeletonComponent();
  initInfo();
});

// 临时假数据
const summary = summaryData;
const customerType = ref('');

function getWebStyleComponent(): string {
  const decision = {
    [WebStyleType.DEFAULT]: HomeDefault,
    [WebStyleType.IBMA]: HomeIBMA,
    [WebStyleType.SIMPLE]: HomeSimple,
    [WebStyleType.STANDARD]: HomeStandard,
    [WebStyleType.BEAUTIFUL]: HomeBeautiful,
  };
  return decision[getWebStyle()] || HomeDefault;
}

function getSkeletonComponent(): string {
  const decision = {
    [WebStyleType.DEFAULT]: StyleDefault,
    [WebStyleType.IBMA]: StyleIBMA,
    [WebStyleType.SIMPLE]: StyleSimple,
    [WebStyleType.STANDARD]: StyleStandard,
    [WebStyleType.BEAUTIFUL]: StyleBeautiful,
  };
  return decision[getWebStyle()] || StyleDefault;
}

function initInfo() {
  if (overviewInfo?.value) {
    const overviewData = overviewInfo.value;
    setHomeData(overviewData);
    getOverView().then((res: any) => {
      const oData = { ...res.data, ...{ Summary: summary } };
      store.state.glob.setGlobState({ type: 'overviewData', value: oData });
      setHomeData(oData);
      uploadKey.value = new Date().getTime();
      getThermalSummary(oData);
    });
  } else {
    getOverView().then((res: any) => {
      const overviewData = { ...res.data, ...{ Summary: summary } };
      setStoreData('glob', 'overviewData', overviewData);
      setHomeData(overviewData);
      uploadKey.value = new Date().getTime();
      getThermalSummary(overviewData);
    });
  }
}

function getThermalSummary(overviewData: any) {
  getThermalOverView().then((res: any) => {
    overviewData.Summary = { ...overviewData.Summary, ...res.data };
    store.state.glob.setGlobState({ type: 'overviewData', value: overviewData });
    setHomeData(overviewData);
    uploadKey.value = new Date().getTime();
  });
}

function setHomeData(overviewData: any): void {
  overviewData.Summary = { ...overviewData.Summary };
  picInfo.ProductImage = overviewData.ProductImage;
  picInfo.ProductName = overviewData.DeviceInfo.ProductName;
  picInfo.ProductAlias = overviewData.DeviceInfo.ProductAlias;
  sessionStorage.setItem('productName', overviewData.DeviceInfo.ProductName);
  localStorage.setItem('productName', overviewData.DeviceInfo.ProductName);
  localStorage.setItem('productSN', overviewData.DeviceInfo.ProductSN);
  kvmClientUrl.value = overviewData.KVMClientUrl;
  deviceInfo.data = { ...picInfo, ...overviewData.DeviceInfo };
  resourceInfo.data = overviewData.Summary;
  monitorInfo.data = factoryMonitorInfo(overviewData);
  fusionPartition.value = overviewData.FusionPartition;
  isShow.value = true;
  customerType.value = overviewData.Customer ?? '';
  if (customerType.value === 'ByteDance') {
    setStoreData('loct', 'customerType', 'ByteDance');
  }
  ipAddress.ipVersion = overviewData.DeviceInfo.DefaultIPAddress.IpVersion;
  const accessInfo = {
    modeV4: overviewData?.DeviceInfo?.DefaultIPAddress?.Mode, 
    addressV4: overviewData?.DeviceInfo?.DefaultIPAddress?.Address,
    modeV6: overviewData?.DeviceInfo?.DefaultIPAddress?.Ipv6Mode,  
    addressV6: overviewData?.DeviceInfo?.DefaultIPAddress?.Ipv6Address,
    version: ipAddress.ipVersion,
  };
  setAddress(accessInfo);
}

function setAddress(accessInfo: any) {
  // 恢复默认地址
  let replaceStr = '--';
  try {
    switch (accessInfo.version) {
      case IPVersionType.IPV4_AND_IPV6:
        ipAddress.addressIPv4 = replaceIpAddressStr(accessInfo.modeV4, true, accessInfo.addressV4);
        ipAddress.addressIPv6 = replaceIpAddressStr(accessInfo.modeV6, false, accessInfo.addressV6);
        break;
      case IPVersionType.IPV4_ONLY:
        ipAddress.addressIPv4 = replaceIpAddressStr(accessInfo.modeV4, true, accessInfo.addressV4);
        break;
      case IPVersionType.IPV6_ONLY:
        ipAddress.addressIPv6 = replaceIpAddressStr(accessInfo.modeV6, false, accessInfo.addressV6);
        break;
      default:
        throw new Error();
    }
  } catch (e) {
    ipAddress.addressIPv4 = traduction('HOME_IPDEFAULVALUE').replace('N/A', replaceStr);
    ipAddress.addressIPv6 = traduction('HOME_IPDEFAULVALUE').replace('N/A', replaceStr);
  }
}
function replaceIpAddressStr(mode: string, isIpv4: boolean, address: string) {
  const isDhcp = mode.includes('DHCP');
  if(isDhcp) {
    return traduction(isIpv4 ? 'HOME_IPV4DEFAULDHCP' : 'HOME_IPV6DEFAULDHCP');
  } else {
    return traduction(isIpv4 ? 'HOME_IPV4DEFAULVALUE' : 'HOME_IPV6DEFAULVALUE').replace('N/A', address || '--');
  }
}
</script>

<template>
  <div id="homeIbmc" :class="{ 'is-left-nav': leftNavTheme === NavTheme.Left }">
    <template v-if="webStyle">
      <component :is="skeletonComponent" v-if="!isShow" />
      <component :is="webStyleComponent" v-if="isShow">
        <!-- 首页概览模块  -->
        <template #PictureComponent>
          <PictureComponent :data="picInfo"></PictureComponent>
        </template>

        <!-- 产品信息  -->
        <template #ProductComponent>
          <ProductComponent
            id="homeDetailInfor"
            :key="'product' + uploadKey"
            :data="deviceInfo"
          ></ProductComponent>
        </template>

        <!-- 产品资源  -->
        <template #ResourceComponent>
          <ResourceComponent :key="'resource' + uploadKey" :data="resourceInfo"></ResourceComponent>
        </template>

        <!-- 系统监控 -->
        <template #MonitorComponent>
          <MonitorComponent
            id="homeSystemMonitor"
            :key="'monitor' + uploadKey"
            :data="monitorInfo.data"
          ></MonitorComponent>
        </template>

        <!-- 虚拟控制台 -->
        <template #VirtualComponent>
          <VirtualComponent id="homeSystemVirtual" :key="'virtual' + uploadKey" :data="kvmClientUrl"></VirtualComponent>
        </template>

        <!-- 快捷访问 -->
        <template #QuickAccessComponent>
          <QuickAccessComponent
            v-if="isShow"
            :fusion-partition="fusionPartition"
            :ip-adress="ipAddress"
            :customer-type="customerType"
          ></QuickAccessComponent>
        </template>
      </component>
    </template>
  </div>
  <LoginInfoComponent></LoginInfoComponent>
</template>

<style lang="scss" scoped>
#homeIbmc {
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  &.is-left-nav {
    width: calc(100% - 256px);
  }
}

#homeSystemMonitor {
  width: 100%;
  float: left;
  height: 100%;
}
</style>
