<script setup lang="ts">
import { IMemory, IMemoryList, IAEPInfo } from '../../product.datatype';
import { DEFAULT_DATA } from '@/model/base-enum';
import { getMemory, getOneMemory } from '../../service/system.service';
import { ref, reactive } from 'vue';
import { loading } from '@/utils/composition';
import { getStoreData } from '@/utils/composition';
import { isOtherEmptyProperty } from '../../utils/system.util';
import SystemInfoTable from '@/pages/System/Info/components/SystemInfoTable/SystemInfoTable.vue';
import { UI_REST_SYSTEM_MEMORY } from '@/api/api';
import { IUpdateBody } from '../product.datatype';

loading(true);
const memoryData = reactive({ data: {} as IMemoryList });
const memoryShow = ref(false);
const showExtend = ref(false);
const tableId = 'memoryTable';
const platform = getStoreData('loct', 'platform');
const columns = [
  {
    title: 'COMMON_NAME',
    width: '15%',
    content: 'deviceLocator',
    show: true,
  },
  {
    title: 'COMMON_MANUFACTURER',
    width: '15%',
    content: 'manufacturer',
    show: true,
  },
  {
    title: 'COMMON_CAPACITY',
    content: 'capacityMiB',
    width: '15%',
    show: true,
  },
  {
    title: 'MEMORY_CONFIGURED_SPEED_MTS',
    content: 'operatingSpeedMHz',
    width: '15%',
  },
  {
    title: 'MEMORY_MAX_SPEED_MTS',
    content: 'allowedSpeedsMHz',
    width: '15%',
    show: true,
  },
  {
    title: 'COMMON_TYPE',
    content: 'deviceType',
    width: '10%',
    show: true,
  },
  {
    title: 'MEMORY_POSITION',
    content: 'position',
    width: '15%',
    show: true,
  },
];

const extendArray = [
  {
    label: 'COMMON_NAME',
    content: 'deviceLocator',
    hide: true,
  },
  {
    label: 'MEMORY_POSITION',
    content: 'position',
    hide: true,
  },
  {
    label: 'COMMON_MANUFACTURER',
    content: 'manufacturer',
    hide: true,
  },
  {
    label: 'COMMON_CAPACITY',
    content: 'capacityMiB',
    hide: true,
  },
  {
    label: 'MEMORY_CONFIGURED_SPEED_MTS',
    content: 'operatingSpeedMHz',
    hide: true,
  },
  {
    label: 'MEMORY_MAX_SPEED_MTS',
    content: 'allowedSpeedsMHz',
    hide: true,
  },
  {
    label: 'COMMON_TYPE',
    content: 'deviceType',
    hide: true,
  },
  {
    label: 'MEMORY_MIN_VOLTAGE_MILLIVOLT',
    content: 'minVoltageMillivolt',
    hide: true,
  },
  {
    label: 'MEMORY_TECHNOLOGY',
    content: 'typeDetail',
    hide: true,
  },
  {
    label: 'MEMORY_DATAWIDTH_BITS',
    content: 'dataWidthBits',
    hide: true,
  },
  {
    label: 'OTHER_PART_NUMBER',
    content: 'partNumber',
    hide: true,
  },
  {
    label: 'MEMORY_PANK',
    content: 'rankCount',
    hide: true,
  },
  {
    label: 'MEMORY_BOM_NUMBER',
    content: 'bomNumber',
    hide: true,
  },
  {
    label: 'COMMON_SERIALNUMBER',
    content: 'serialNumber',
    hide: true,
  },
];

const aepInfoArray = [
  {
    label: 'MEMORY_RESIDUAL_LIFE',
    content: 'aepInfo.remainPercent',
    hide: false,
  },
  {
    label: 'MEMORY_MEDIUM_TEMPERATURE',
    content: 'aepInfo.mediumTemp',
    hide: false,
  },
  {
    label: 'MEMORY_FIRMWARE_VERSION',
    content: 'aepInfo.revision',
    hide: false,
  },
  {
    label: 'MEMORY_VOLATILE_CAPACITY',
    content: 'aepInfo.volatileMib',
    hide: false,
  },
  {
    label: 'MEMORY_CONTROLLER_TEMPERATURE',
    content: 'aepInfo.controlTemp',
    hide: false,
  },
  {
    label: 'MEMORY_NON_VOLATILE_CAPACITY',
    content: 'aepInfo.persistMib',
    hide: false,
  },
];

getMemory().then((res: any) => {
  memoryData.data = factoryMemoryInfo(res.data, 'arm');
  memoryShow.value = true;
  loading(false);
});

function factoryMemoryInfo(data: any, platForm: any): IMemoryList {
  const maxNum = data.MaxNumber;
  const lists = data.List;

  const responseData: IMemoryList = {
    memory: [],
    totalMemorylength: 0,
  };

  responseData.totalMemorylength = maxNum;
  if (lists && lists.length) {
    lists.forEach((list: any) => {
      const memData = parseMemoryData(list);
      if (memData) {
        responseData.memory.push(memData);
      }
    });
  }

  return responseData;
}

function parseMemoryData(data: any): IMemory {
  const memory: IMemory = parseMemoryInfoInit(data);
  memory.extendTitleArr = [];
  showExtend.value = true;
  memory.extendTitleArr.push(getExtendInfo(memory));
  if (data.DCPMM) {
    memory.aepInfo = parseAepInfo(data);
    memory.extendTitleArr.push(getAepInfo(memory.aepInfo));
  }
  return memory;
}
function initMemory(data: any, unit: string) {
  if (data !== null && data !== undefined) {
    return `${data} ${unit}`;
  } else {
    return DEFAULT_DATA.noDataStr;
  }
}

function parseMemoryInfoInit(data: any): IMemory {
  const capacityMiB = initMemory(data.General.CapacityMiB, 'MB');
  const operatingSpeedMHz = initMemory(data.General.OperatingSpeedMHz, 'MT/s');
  const allowedSpeedsMHz = initMemory(data.General.AllowedSpeedsMHz, 'MT/s');
  const minVoltageMillivolt = initMemory(data.General.MinVoltageMillivolt, 'mV');
  const dataWidthBits = initMemory(data.General.DataWidthBits, 'bit');
  const rankCount = initMemory(data.General.RankCount, 'rank');
  const deviceType = data.General.DeviceType || DEFAULT_DATA.noDataStr;
  const manufacturer = data.General.Manufacturer || DEFAULT_DATA.noDataStr;
  const position = data.General.Position || DEFAULT_DATA.noDataStr;
  const partNumber =
    data.General.PartNumber !== '' && data.General.PartNumber !== null && data.General.PartNumber !== undefined
      ? data.General.PartNumber
      : DEFAULT_DATA.noDataStr;
  const serialNumber =
    data.General.SerialNumber !== '' &&data.General.SerialNumber !== null && data.General.SerialNumber !== undefined
      ? data.General.SerialNumber
      : DEFAULT_DATA.noDataStr;
  const typeDetail = data.General.TypeDetail || DEFAULT_DATA.noDataStr;
  const url = `${UI_REST_SYSTEM_MEMORY}/${data.General.Position}${data.General.DeviceLocator}`;
  const expandFlag = `${data.General.Position}${data.General.DeviceLocator}`;
  const expandShow = false;
  return {
    allowedSpeedsMHz,
    bomNumber: data.General.BomNumber,
    capacityMiB,
    dataWidthBits,
    deviceLocator: data.General.DeviceLocator,
    deviceType,
    manufacturer,
    minVoltageMillivolt,
    operatingSpeedMHz,
    partNumber,
    position,
    rankCount,
    serialNumber,
    typeDetail,
    url,
    expandFlag,
    expandShow,
  };
}

function getAepInfo(aepInfo: any) {
  aepInfoArray.forEach(element => {
    element.hide = aepInfo[element.content.split('.')[1]] === undefined;
  });
  return {
    title: 'MEMORY_AEP_INFO',
    data: aepInfoArray,
  };
}

function getExtendInfo(memory: any) {
  extendArray.forEach(element => {
    if (element.content === 'bomNumber') {
      element.hide = memory[element.content] === undefined || platform === 'Arm';
      memory[element.content] = isOtherEmptyProperty(memory.bomNumber);
    } else {
      element.hide = memory[element.content] === undefined;
    }
  });
  return {
    title: 'FDM_INFO',
    data: extendArray,
  };
}

function parseAepInfo(data: any): IAEPInfo {
  const remainPercent =
    data.RemainingServiceLifePercent === null || data.RemainingServiceLifePercent === undefined
      ? DEFAULT_DATA.noDataStr
      : `${data.RemainingServiceLifePercent} %`;
  const mediumTemp =
    data.MediumTemperatureCelsius === null || data.MediumTemperatureCelsius === undefined
      ? DEFAULT_DATA.noDataStr
      : `${data.MediumTemperatureCelsius} ℃`;
  const revision =
    data.FirmwareRevision === null || data.FirmwareRevision === undefined
      ? DEFAULT_DATA.noDataStr
      : data.FirmwareRevision;
  const volatileMib =
    data.VolatileRegionSizeLimitMiB === null || data.VolatileRegionSizeLimitMiB === undefined
      ? DEFAULT_DATA.noDataStr
      : `${data.VolatileRegionSizeLimitMiB} MB`;
  const controlTemp =
    data.ControllerTemperatureCelsius === null || data.ControllerTemperatureCelsius === undefined
      ? DEFAULT_DATA.noDataStr
      : `${data.ControllerTemperatureCelsius} ℃`;
  const persistMib =
    data.PersistentRegionSizeLimitMiB === null || data.PersistentRegionSizeLimitMiB === undefined
      ? DEFAULT_DATA.noDataStr
      : `${data.PersistentRegionSizeLimitMiB} MB`;

  return {
    remainPercent,
    mediumTemp,
    revision,
    volatileMib,
    controlTemp,
    persistMib,
  };
}

function expandChange(row: any, callback: any): void {
  if (row.expandShow) {
    memoryData.data.memory.forEach((item: any, index: number) => {
      if (item.expandFlag === row.expandFlag) {
        memoryData.data.memory[index].expandShow = false;
      }
    });
    callback();
    return;
  } else {
    loading(true);
    getOneMemory(row.url || '')
      .then((res: any) => {
        const memory: IMemory = parseMemoryInfoInit(res.data);
        memory.expandShow = true;
        memory.extendTitleArr = [];
        memory.extendTitleArr.push(getExtendInfo(memory));
        memoryData.data.memory.forEach((item: any, index: number) => {
          if (item.expandFlag === row.expandFlag) {
            memoryData.data.memory[index] = memory;
          }
        });
        callback();
        loading(false);
      })
      .catch((err: any) => {
        memoryData.data.memory.forEach((item: any, index: number) => {
          if (item.expandFlag === row.expandFlag) {
            memoryData.data.memory[index].expandShow = true;
          }
        });
        callback();
        loading(false);
      });
  }
}

function currentChange(callback: any) {
  memoryData.data.memory.forEach((item: any) => {
    item.expandShow = false;
  });
  callback();
}

</script>

<template>
  <SystemInfoTable
    v-if="memoryShow"
    :id="tableId"
    :data="memoryData.data.memory"
    :columns="columns"
    :showextend="showExtend"
    :num="memoryData.data.totalMemorylength"
    :needChange="true"
    rowKey="expandFlag"
    @expand-change="expandChange"
    @current-change="currentChange"
  />
</template>

<style lang="scss" scoped>
.system-info-table {
  margin-right: 24px;
  padding: 0 16px;
}
</style>
