<script setup lang="ts">
import { reqPath } from '@/api/reqPath';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import TableExtendData from '@/pages/System/Info/components/TableExtendData/TableExtendData.vue';
import { loading } from '@/utils/composition';
import { deepClone } from '@/utils/utils';
import type { PropType } from 'vue';
import { nextTick, ref, toRefs, computed, reactive, onMounted, onUnmounted } from 'vue';
import useStore from '@/stores';
import { useI18n } from 'vue-i18n';
import {
  IOtherTab,
  IUBCard,
  IPortData,
  ITranPortData,
  ITranUBCard
} from '../../product.datatype';
import { getBoard } from '../../service/system.service';
import { isOtherEmptyProperty } from '../../utils/system.util';
import { traduction } from '@/utils/language';
const store = useStore();
const i18n = useI18n();
const errorMsg = traduction('COMMON_FAILED');
const props = defineProps({
  data: {
    type: Object as PropType<IOtherTab>,
    required: true,
    default: () => {
      return {};
    },
  },
});
const { data } = toRefs(props);
const boardData: IOtherTab = data?.value;
const boardTableData = ref([] as any);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(boardTableData.value.length);
const tableData = ref([]);
const tableRef = ref();
const linkStatusList = {
  LinkUp: 'LinkUp',
  NoLink: 'NoLink',
  LinkDown: 'LinkDown',
  'N/A': '--',
  Connected: traduction('NET_CONNECT'),
  Disconnected: traduction('NET_DISCONNECT'),
  Down: traduction('NET_DISCONNECT'),
  Up: traduction('NET_CONNECT'),
};

function getUBData() {
  boardTableData.value = [];
  getBoard(boardData.detailLink)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        res.data.forEach((borad: IUBCard) => {
          const d = parseData(borad);
          if (d) {
            boardTableData.value.push(d);
          }
        });
      }
      total.value = boardTableData.value.length;
      getData();
    })
    .finally(() => {
      loading(false);
    });
}

function parseData(board: IUBCard): ITranUBCard {
  let extendAttr = initExtendData(board);
  return {
    name: isOtherEmptyProperty(board.Name) || ' ',
    position: isOtherEmptyProperty(board.Position) || ' ',
    uid: isOtherEmptyProperty(board.UID) || ' ',
    description: isOtherEmptyProperty(board.Description) || ' ',
    manufacturer: isOtherEmptyProperty(board.Manufacturer) || ' ',
    partNumber: isOtherEmptyProperty(board.PartNumber) || ' ',
    pcbVersion: isOtherEmptyProperty(board.PCBVersion) || ' ',
    serialNumber: isOtherEmptyProperty(board.SerialNumber) || ' ',
    srVersion: isOtherEmptyProperty(board.SRVersion) || ' ',
    extendAttr,
  };
}

// 表头数组
const columns = [
  {
    title: 'COMMON_NAME',
    width: '10%',
    show: true,
    content: 'name',
  },
  {
    title: 'OTHER_BOARD_DESCRIPTION',
    width: '10%',
    show: true,
    content: 'description',
  },
  {
    title: 'COMMON_COMPONENT_UID',
    width: '15%',
    show: true,
    content: 'uid',
  },
  {
    title: 'COMMON_MANUFACTURER',
    width: '10%',
    show: true,
    content: 'manufacturer',
  },
  {
    title: 'OTHER_POSITION',
    width: '10%',
    show: true,
    content: 'position',
  },
  {
    title: 'OTHER_PART_NUMBER',
    width: '10%',
    show: true,
    content: 'partNumber',
  },
  {
    title: 'COMMON_ALARM_PCB_VERSION',
    width: '10%',
    show: true,
    content: 'pcbVersion',
  },
  {
    title: 'OTHER_HAESWARD_DESCRIPTION_VERSION',
    width: '20%',
    show: true,
    content: 'srVersion',
  },
];

function handleSizeChange(val: number) {
  pageSize.value = val;
  currentPage.value = 1;
  getData();
}

function handleCurrentChange(val: number) {
  getData();
}

function getData() {
  tableData.value = boardTableData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value,
  );
}

const UBCardExtendArr = [
  {
    label: 'OTHER_LINK_STATUS',
    content: 'portLinkStatus',
    hide: true,
  },
  {
    label: 'OTHER_CABLE_STATUS',
    content: 'portCableConnectionStatus',
    hide: true,
  },
];
function initExtendData(bodyData: IUBCard): object {
  const extendCard = bodyData?.UBPorts || [];
  let extendData = {
    extendCards: [] as ITranPortData[],
  };
  if (extendCard && extendCard instanceof Array && extendCard.length > 0) {
    extendData.extendCards = [];
    extendCard.forEach((extendCardInfo: IPortData) => {
      if (extendCardInfo !== null && extendCardInfo !== []) {
        extendData.extendCards?.push(getExtendCard(extendCardInfo));
      }
    });
  }
  return extendData;
}

function getExtendCard(extendCardInfo: IPortData): ITranPortData {
  const title = `Port${extendCardInfo?.PortId || 0}`;
  let linkStatus = isOtherEmptyProperty(extendCardInfo.LinkStatus) || ' ';
  let cableConnectionStatus = isOtherEmptyProperty(extendCardInfo.CableConnection) ?? ' ';
  if (linkStatus !== '--') {
    linkStatus = linkStatusList[linkStatus] ?? '--';
  }
  
  if (cableConnectionStatus !== '--') {
    cableConnectionStatus = cableConnectionStatus === 0 ? 'ALARM_EVENT_NORMAL' : 'OTHER_FAULTY';
  }
  const ubExtendCard: ITranPortData = {
    title,
    portLinkStatus: linkStatus,
    portCableConnectionStatus: cableConnectionStatus,
  };
  const titleArr = deepClone(UBCardExtendArr);
  ubExtendCard.extendCardTitleArr = titleArr;
  titleArr.forEach((element: any) => {
    element.hide = ubExtendCard[element.content] === '--';
  });
  return ubExtendCard;
}

function getRowKey(rowInfo: any) {
  return 'UB' + rowInfo.rowIndex;
}

function getCellClass(cellInfo: any) {
  if (cellInfo.columnIndex === 0) {
    return 'expand_cell';
  }
  return columns[cellInfo.columnIndex - 1]?.content;
}

onMounted(() => {
  if (boardData.currentNumber && boardData.currentNumber > 0) {
    loading(true);
    getUBData();
  }
});
</script>

<template>
  <div id="UBCardPage" 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">{{ total }}</span>
    </div>
    <el-table
      ref="tableRef"
      v-addId.table="'UBCardTable'"
      :data="tableData"
      :row-class-name="getRowKey"
      :cell-class-name="getCellClass"
    >
      <el-table-column class="expand" type="expand">
        <template #default="scope">
          <div>
            <span v-t="'OTHER_PORT_ATTR'" class="module-title" />
            <div v-for="card in scope.row.extendAttr.extendCards" :key="card.title" class="module">
              <span v-if="card.title" v-t="card.title" class="module-title" />
              <TableExtendData :data-list="card.extendCardTitleArr" :fields="card"/>
            </div>
          </div>
        </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"
        show-overflow-tooltip
      >
        <template #default="attr">
          <span v-if="col.content !== 'operate'" :class="col?.content">
            {{ attr.row[col?.content] }}
          </span>
        </template>
      </el-table-column>
      <template #empty>
        <TableNoData />
      </template>
    </el-table>
    <el-pagination
      v-if="tableData.length != 0"
      v-model:currentPage="currentPage"
      v-addId.pagination="'UBCardPagination'"
      :page-sizes="[10, 15, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

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

  .collect-box {
    display: flex;
    align-items: center;
    .collecting-text {
      font-size: 12px;
      color: var(--o-text-color-secondary);
      line-height: 16px;
    }
  }

  .el-button {
    background: none;
    margin: 0;
    min-width: 0;
  }

  #proCollect {
    width: 200px;
    margin-left: 8px;
    :deep(.el-progress__text) {
      margin-left: 8px;
      min-width: 30px;
    }
  }

  .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;
  }

  .no-data {
    text-align: center;
    margin-top: 128px;
  }
  .no-data-text {
    font-size: 12px;
    color: var(--o-text-color-tertiary);
    text-align: center;
    line-height: 16px;
  }
  :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;
      }
    }
  }
  :deep(.el-table__expanded-cell) {
    .cell {
      width: 100% !important;
    }

    .el-scrollbar__thumb,
    .el-scrollbar__bar {
      background-color: transparent !important;
    }
    .port-icon {
      top: 4px;
    }
  }
}
.small-item {
  margin-bottom: 0px !important;
}
</style>
