<script setup lang="ts">
import { ref, watch, reactive } from 'vue';
import type { PropType } from 'vue';
import { UnitsCard, IOtherTab } from '../../product.datatype';
import { getBoard } from '../../service/system.service';
import { isOtherEmptyProperty } from '../../utils/system.util';
import { useI18n } from 'vue-i18n';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import TableExtendData from '../TableExtendData/TableExtendData.vue';
import { loading } from '@/utils/composition';
import { traduction } from '@/utils/language';

const i18n = useI18n();
const props = defineProps({
  data: {
    type: Object as PropType<IOtherTab>,
    required: true,
    default: () => {
      return {};
    },
  },
});
const tableId = 'unitsTable';
let boardData: any = {};
const boardTableData = reactive([] as any);
const isBasicComputingUnit = ref(false);
const isExtensionUnit = ref(false);
const isStorageExtensionUnit = ref(false);

// 不同卡对应的初始数据函数数组
const parseDataMap = new Map<string, Function>([['Basic Card', initBasicCard]]);
watch(
  () => props.data,
  () => {
    getCurrentData();
  },
  { deep: true },
);

function getCurrentData(): any {
  const { data } = props;
  Object.assign(boardData, data);
  boardTableData.splice(0);
  // 基础计算组件存在显示差异
  isBasicComputingUnit.value = boardData.type === 'BasicComputingUnit';
  isExtensionUnit.value = boardData.type === 'ExtensionUnit';
  isStorageExtensionUnit.value = boardData.type === 'StorageExtensionUnit';

  if (data.currentNumber && data.currentNumber > 0) {
    loading(true);
    getBoard(boardData.detailLink)
      .then((res: any) => {
        if (res.data && res.data.length > 0) {
          res.data.forEach((borad: any) => {
            const showData = parseData(borad);
            if (showData) {
              boardTableData.push(showData);
            }
          });
        }
      })
      .finally(() => {
        loading(false);
      });
  }
}
getCurrentData();

function parseData(board: any): any {
  const type = board.FunctionType;
  let extendAttr = {};
  if (parseDataMap.has(type)) {
    extendAttr = parseDataMap.get(type)?.call(parseDataMap.get(type), board);
  } else {
    extendAttr = initBasicCard(board);
  }
  return {
    name: isOtherEmptyProperty(board.Name) || ' ',
    position: isOtherEmptyProperty(board.Position) || ' ',
    manufacturer: isOtherEmptyProperty(board.Manufacturer) || ' ',
    slot_position: isOtherEmptyProperty(board.Id) || ' ',
    description: isOtherEmptyProperty(board.Description) || ' ',
    component_uid: isOtherEmptyProperty(board.ComponentUniqueID) || ' ',
    extendAttr,
  };
}

// 表头数组
const columns = [
  {
    title: 'COMMON_NAME',
    width: '20%',
    content: 'name',
    show: true,
  },
  {
    title: 'OTHER_POSITION',
    width: '20%',
    content: 'position',
    show: true,
  },
  {
    title: 'COMMON_MANUFACTURER',
    width: '15%',
    content: 'manufacturer',
    show: true,
  },
  {
    title: 'OTHER_SLOT_POSITION',
    width: '15%',
    content: 'slot_position',
    show: true,
  },
  {
    title: 'COMMON_DESCRIPTION',
    width: '20%',
    content: 'description',
    show: true,
  },
  {
    title: 'OTHER_COMPONENT_UID',
    width: '30%',
    content: 'component_uid',
    show: true,
  },
];

// Units卡扩展数据
const unitsCardExtendArr = [
  {
    label: 'COMMON_SERIALNUMBER',
    content: 'serialNumber',
    hide: true,
  },
  {
    label: 'COMMON_NPU_NAME',
    content: 'npuName',
    hide: true,
  },
  {
    label: 'COMMON_ALARM_PCB_VERSION',
    content: 'pcbVersion',
    hide: true,
  },
  {
    label: 'OTHER_HAESWARD_DESCRIPTION_VERSION',
    content: 'hwsrVersion',
    hide: true,
  },
  {
    label: 'OTHER_BIOS1_VERSION',
    content: 'bios1Version',
    hide: true,
  },
  {
    label: 'OTHER_PART_NUMBER',
    content: 'partNumber',
    hide: true,
  },
  {
    label: 'OTHER_BIOS2_VERSION',
    content: 'bios2Version',
    hide: true,
  },
  {
    label: 'OTHER_BOARD_ID',
    content: 'boardId',
    hide: true,
  },
  {
    label: 'OTHER_MCU_VERSION',
    content: 'mcuVersion',
    hide: true,
  },
  {
    label: 'OTHER_POWER',
    content: 'powerWatts',
    hide: true,
  },
];

// 过滤出返回信息中CPLD[number]Version的字段名和数字
function getCPLDVersionKeys(extendInfo: any): string[][] {
  const keys = Object.keys(extendInfo || {}).filter(key => {
    return /^CPLD[\d]*Version$/.test(key);
  });
  const data = keys.map(key => {
    const index = key.replace(/[^\d]/g, '');
    return [key, index];
  }).sort((a, b) => (a[0] || '').localeCompare(b[0] || ''));
  return data;
}

function getUnitsCardExtendArr(extendInfo: any): any[] {
  const keys = getCPLDVersionKeys(extendInfo);
  let isBasicComputeColumns = keys.map(key => {
    return {
      label: traduction('COMMIN_CPLD_VERSION_CUSTOM', [key[1]]),
      content: key[0],
      hide: true,
    };
  });
  if (isExtensionUnit.value) {
    isBasicComputeColumns = isBasicComputeColumns.concat([{
      label: 'COMMIN_FPGA_VERSION',
      content: 'fPGAVersion',
      hide: true,
    }]);
  }
  let otherColumns = [
    {
      label: 'COMMIN_CPLD_VERSION',
      content: 'cpldVersion',
      hide: true,
    },
  ];
  if (isStorageExtensionUnit.value) {
    otherColumns = otherColumns.concat([{
      label: 'COMMIN_DRIVE_COUNT',
      content: 'driveNumber',
      hide: true,
    }]);
  }
  return [
    ...unitsCardExtendArr,
    ...((isBasicComputingUnit.value || isExtensionUnit.value) ? isBasicComputeColumns : otherColumns),
  ];
}
function getExtendData(bodyData: any) {
  const serialNumber = isOtherEmptyProperty(bodyData?.ExtendInfo?.SerialNumber) || ' ';
  const npuName = isOtherEmptyProperty(bodyData?.ExtendInfo?.NpuName) || ' ';
  const pcbVersion = isOtherEmptyProperty(bodyData?.ExtendInfo?.PCBVersion) || ' ';
  const hwsrVersion = isOtherEmptyProperty(bodyData?.ExtendInfo?.HWSRVersion) || ' ';
  const bios1Version = isOtherEmptyProperty(bodyData?.ExtendInfo?.Bios1Version) || ' ';
  const partNumber = isOtherEmptyProperty(bodyData?.ExtendInfo?.PartNumber) || ' ';
  const bios2Version = isOtherEmptyProperty(bodyData?.ExtendInfo?.Bios2Version) || ' ';
  const boardId = isOtherEmptyProperty(bodyData?.ExtendInfo?.BoardId) || ' ';
  const mcuVersion = isOtherEmptyProperty(bodyData?.ExtendInfo?.McuVersion) || ' ';
  const powerWatts = isOtherEmptyProperty(bodyData?.PowerWatts) === 0 ?
    '--' : isOtherEmptyProperty(bodyData?.PowerWatts) || ' ';
  const fPGAVersion = isOtherEmptyProperty(bodyData?.ExtendInfo?.FPGAVersion) || ' ';
  const driveNumber = isOtherEmptyProperty(bodyData?.DriveNumber) || ' ';
  return {
    serialNumber,
    npuName,
    pcbVersion,
    hwsrVersion,
    bios1Version,
    partNumber,
    bios2Version,
    boardId,
    mcuVersion,
    powerWatts,
    fPGAVersion,
    driveNumber,
    extendTitleArr: JSON.parse(JSON.stringify(getUnitsCardExtendArr(bodyData?.ExtendInfo))),
  };
}
function initBasicCard(bodyData: any): UnitsCard {
  const extendData: any = getExtendData(bodyData);
  if (isBasicComputingUnit.value || isExtensionUnit.value) {
    const cpldKeys = getCPLDVersionKeys(bodyData?.ExtendInfo);
    cpldKeys.forEach(key => {
      const value = isOtherEmptyProperty(bodyData?.ExtendInfo?.[key[0]]) || ' ';
      extendData[key[0]] = value;
    });
  } else {
    const cpldVersion = isOtherEmptyProperty(bodyData?.ExtendInfo?.CPLDVersion) || ' ';
    extendData.cpldVersion = cpldVersion;
  }
  extendData.extendTitleArr.forEach((element: any) => {
    element.hide = extendData[element.content] === '--';
    if (element.content === 'mcuVersion' && Object.prototype.hasOwnProperty.call(bodyData?.ExtendInfo, 'McuVersion')) {
      element.hide = false;
    }
  });
  if (extendData.powerWatts === 65535) {
    extendData.powerWatts = '--';
  }
  return extendData;
}
</script>

<template>
  <div id="unitPage" class="system-info-table">
    <div v-if="boardData.maxNumber && boardData.maxNumber > 0" class="summary">
      <span id="totalLabel" v-t="'HOME_HEALTH_TOTALNUM'" class="label" />
      <span id="totalNum" class="label-content">{{ boardData.maxNumber }}</span>
      <span id="currentLabel" v-t="'HOME_HEALTH_CURRENTNUM'" class="label" />
      <span id="currentNum" class="label-content">{{ boardTableData?.length }}</span>
    </div>
    <el-table :id="tableId" :data="boardTableData" resizable border>
      <el-table-column class="expand" type="expand">
        <template #default="scope">
          <span v-t="'OTHER_EXTEND_INFO'" class="module-title" />
          <TableExtendData
            :data-list="scope.row.extendAttr.extendTitleArr"
            :fields="scope.row.extendAttr"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-for="col in columns"
        :key="col?.content"
        :label="$t(col?.title)"
        :prop="col?.content"
        :min-width="col?.width"
      />
      <template #empty>
        <TableNoData />
      </template>
    </el-table>
  </div>
</template>

<style lang="scss" scoped>
.system-info-table {
  background: var(--o-bg-color-base);
  border-radius: 4px;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;

  :deep(.el-table--border) {
    .el-table__cell:first-child .cell {
      margin-left: 8px;
      width: 16px;
      padding-left: 0;
      display: inline-block;
    }

    tr,
    colgroup {
      th:nth-child(1),
      col:nth-child(1),
      td:nth-child(1) {
        width: 40px;
        max-width: 40px;
      }
    }
  }

  .el-tabs__content {
    margin-top: 0;
  }

  .summary {
    padding: 16px 0;
  }
  .label-content {
    background: var(--o-border-color-light);
    border-radius: 8px;
    width: 28px;
    height: 16px;
    display: inline-block;
    text-align: center;
    margin: 0 16px 0 8px;
    font-size: 12px;
    font-weight: 900;
  }

  .label {
    font-size: 12px;
    color: $APP-COLOR-TEXT;
    letter-spacing: 0;
    line-height: 16px;
  }
  .detail {
    width: 50%;
    float: left;
    display: flex;
    margin-top: 8px;
  }

  .module-title {
    font-weight: 700;
    margin: 16px 0;
    display: block;
  }
}
</style>
<style lang="scss">
#unitPage {
  .el-scrollbar{
    .el-table__expanded-cell {
      padding-left: 40px !important;
      padding-top: 0;
      background: var(--o-bg-color-light);
    }
  }
  

  .el-table tr th {
    font-weight: 600 !important;
  }

  .expanded {
    background: var(--o-bg-color-light);
    box-shadow: inset 0 -1px 0 0 var(--o-border-color-light);
  }

  .el-table__header {
    width: 100% !important;
  }

  .el-table__body {
    width: 100% !important;
  }
}
</style>
