<script setup lang="ts">
import { ref, reactive, shallowRef, nextTick, onUnmounted, Ref } from 'vue';
import Team from './NetPages/Team/Team.vue';
import { traduction } from '@/utils/language';
import { deepClone, showElMessage } from '@/utils/utils';
import { ElNotification as elNotification } from 'element-plus';
import Bridge from './NetPages/Bridge/Bridge.vue';
import Dialog from '@/components/Dialog/Dialog.vue';
import FCCard from './NetPages/FCCard/FCCard.vue';
import NetCard from './NetPages/NetCard/NetCard.vue';
import GlobalStoreService from '@/services/gloabal-store-service';
import { INetData, IPerCartData } from '@/model/System/net-interface';
import { getNetData, getNetDataDetail, getNetworkSettings, networkAdapter } from './net.server';
import { initNetworkData } from '@/pages/Manager/Network/networkFunctions/networkDataFactory';
import UploadingIcon from '@/components/UploadingIcon/UploadingIcon.vue';
import { cancelRequests } from '@/utils/http-service';

import './net-card-style/index.scss';

const globalStoreService = new GlobalStoreService();
const errorMsg = traduction('COMMON_FAILED');
const netCadText = traduction('NET_NIC');

const defaultExpandedKeys: string[] = reactive([]);
const currentNodeKey = ref('');
const currentNode = ref<any>({});
const currentNodeId = ref('');

const treeProps = {
  children: 'children',
  label: 'name',
};

const dialog = ref();
const dialogConfig = reactive({
  title: '',
  content: '',
});

const rootKeys = ['NetCard', 'FCCard', 'Team', 'Bridge', 'IBCard'];
const treeData: Ref<Array<INetData>> = ref([]);

let showComponent = shallowRef();
let showData: any = reactive({});
let showRef: any = ref();
const treeRef = ref(null);
let timer: any = null;
let netCardData: any[] = [];
let currentHotplugCardId: string = '';
let firstEntry = true;

// 确认热插拔操作 或者 点击弹窗的取消按钮
function sureSetting(value: boolean) {
  if (value) {
    let param = {};
    if (showData.OrderlyHotplugCtrlStatus === 'Removable') {
      param = {
        AdapterId: showData.AdapterId,
      };
    }
    cancelTimer();
    networkAdapter(showData.AdapterId, param)
      .then(() => {
        currentHotplugCardId = showData.AdapterId;
        elNotification.closeAll();
        elNotification({
          title: traduction('NET_UNINSTALLED_NOTICE_SWAP_TITLE', {
            netCard: getNetCardName(showData.AdapterId),
          }),
          message: traduction('NET_UNINSTALLED_NOTICE_SWAP_CONTENT'),
          icon: UploadingIcon as any,
          position: 'bottom-right',
          duration: 0,
          offset: 10,
        });
        changeDialogShow(false);
        initTimer();
      })
      .catch((err: any) => {
        globalStoreService.setValue('isLoading', false);
        showElMessage('error', errorMsg);
      });
  } else {
    changeDialogShow(false);
  }
}

// 修改弹窗显示状态
function changeDialogShow(val: boolean) {
  if (val) {
    getNetworkSettings()
      .then((data: any) => {
        const type = initNetworkData(data).networkPort.networkPortType.Type;
        let ocpPort = false;
        if (type.indexOf('OCP') !== -1) {
          ocpPort = true;
        }

        if (showData.OrderlyHotplugCtrlStatus === 'Removable') {
          dialogConfig.title = traduction('COMMON_CONFIRM');
        } else {
          dialogConfig.title = traduction('INSERT_TITLE');
        }

        if (showData.OrderlyHotplugCtrlStatus === 'Insertable') {
          dialogConfig.content = traduction('INSERT_CONTENT');
        } else if (ocpPort) {
          dialogConfig.content = traduction('UNPLUGS_ONOCP_CONTENT');
        } else {
          dialogConfig.content = traduction('UNPLUGS_CONTENT');
        }
        dialog.value.show();
      })
      .catch((err: any) => {
        globalStoreService.setValue('isLoading', false);
        showElMessage('error', errorMsg);
      });
  } else {
    dialog.value.hide();
  }
}

// 点击左边导航数据项
function handleNodeClick(item: INetData | IPerCartData) {
  cancelRequests();
  if (rootKeys.includes(item.id) ) {
    return;
  }
  if (currentNodeKey.value !== item.id) {
    (treeRef.value as any)?.setCheckedKeys([], false);
  }
  currentNodeKey.value = item.id;
  currentNode.value = item;
  currentNodeId.value = item.adapterId;
  getNetDetail(item.adapterId, item);
}

// 修改展示组件 - 和设置展示数据
function changeShowComponent(item?: undefined | INetData | IPerCartData, treeNode?: any) {
  let key = '';
  let resShowData: any = {};
  if (treeNode) {
    key = treeNode.key;
    resShowData = item;
  } else if (treeData.value[0]?.children[0]) {
    key = treeData.value[0].key;
    const findItem =
      treeData.value[0].children.find(e => e.id === currentNodeKey.value) ||
      treeData.value[0].children[0];
    resShowData = item;
    currentNodeKey.value = findItem.id;
    (treeRef.value as any)?.setCheckedKeys([currentNodeKey.value], false);
  }
  switch (key) {
    case 'Bridge': {
      showComponent.value = Bridge;
      break;
    }
    case 'FCCard': {
      showComponent.value = FCCard;
      break;
    }
    case 'NetCard': {
      showComponent.value = NetCard;
      break;
    }
    case 'Team': {
      showComponent.value = Team;
      break;
    }
    default: {
      showComponent.value = NetCard;
      break;
    }
  }
  nextTick(() => {
    updateShowData(showData, resShowData);
  });
}

function updateShowData(sData: object, resShowData: object): void {
  if (JSON.stringify(sData) === JSON.stringify(resShowData)) {
    return;
  }
  for (const key in sData) {
    if ({}.hasOwnProperty.call(sData, key)) {
      delete sData[key];
    }
  }
  Object.assign(sData, deepClone(resShowData));
}

// 根据rootKeys顺序排序展示数据
function changeSort(arr: any) {
  const temp: any[] = [];
  rootKeys.forEach((key: string) => {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].key === key) {
        temp.push(arr[i]);
        break;
      }
    }
  });
  treeData.value = temp;
}

function getNetCardData(data: any[], key: string) {
  return data[key].map((item: any, index: number) => {
    return {
      type: 'leaf',
      key: 'NetCard',
      name: item.CardName,
      adapterId: item.AdapterId,
      orderlyHotplugCtrlStatus: item.OrderlyHotplugCtrlStatus,
      id: `${key}_${index}`,
    };
  });
}

// 加工数据
function initData(data: any) {
  const arr: any = [];
  netCardData = [];
  for (const key in data) {
    if (key === 'NetCard' && data[key].length > 0 && rootKeys.includes(key)) {
      // 因为卡的名称可能存在重复的，可能导致多个卡同时处于选择状态，所以这里使用唯一的id属性，而不是name来作为currentNodeKey
      const ibCardData = data.NetCard.filter((card: any) => card.NetDevFuncCapabilities === 32);
      data.NetCard = data.NetCard.filter((card: any) => !ibCardData.includes(card));
      arr.push({
        type: 'root',
        key: 'NetCard',
        name: netCadText,
        id: key,
        children: getNetCardData(data, key),
      });
      netCardData = getNetCardData(data, key);
      if (ibCardData.length > 0) {
        arr.push({
          type: 'root',
          key: 'IBCard',
          name: 'IBCard',
          id: 'IBCard',
          children: ibCardData.map((item: any, index: number) => {
            return {
              type: 'leaf',
              key: 'IBCard',
              name: item.CardName || item.Name,
              adapterId: item.AdapterId,
              id: `IBCard_${index}`,
            };
          }),
        });
      }
    } else if (rootKeys.includes(key) && data[key]?.length > 0) {
      arr.push({
        type: 'root',
        key: key,
        name: key,
        id: key,
        children: data[key].map((item: any, index: number) => {
          return {
            type: 'leaf',
            key: key,
            name: item.CardName || item.Name,
            adapterId: item.AdapterId,
            id: `${key}_${index}`,
          };
        }),
      });
    } else {}
  }
  if (arr[0]) {
    changeSort(arr);
  }
  checkFirstEnterHotPlugin();
}

function setTreeCurrentNodeKey(children: any[], cNodeKey: Ref<string>): void {
  if (cNodeKey.value && children.find(e => e.id === cNodeKey.value)) {
    return;
  }
  cNodeKey.value = children[0].id;
}

// 获取数据
function getData() {
  treeData.value = [];
  defaultExpandedKeys.splice(0);
  globalStoreService.setValue('isLoading', true);
  getNetData()
    .then((data: any) => {
      if (data) {
        initData(data);
        if (treeData?.value?.[0]?.children?.[0] ) {
          setTreeCurrentNodeKey(treeData.value[0].children, currentNodeKey);
        }
        if (data.NetCard.length) {
          currentNode.value = data.NetCard[0];
          currentNodeId.value = data.NetCard[0].AdapterId;
          getNetDetail(data.NetCard[0].AdapterId);
        } else {
          globalStoreService.setValue('isLoading', false);
        }
      
        changeShowComponent();
      } else {
        globalStoreService.setValue('isLoading', false);
        showElMessage('error', errorMsg);
      }
    })
    .catch((err: any) => {
      globalStoreService.setValue('isLoading', false);
    });
}

function getNetDetail(adapterId: string, item?: any, noLoading?: any) {
  getNetDataDetail(adapterId, item?.key || '')
    .then((data: any) => {
      if (data) {
        data.adapterId = adapterId || '';
        if (showRef?.value?.resetPort) {
          showRef.value.resetPort(data.adapterId);
        }
        changeShowComponent(data, item);
      } else {
        showElMessage('error', errorMsg);
      }
    })
    .finally(() => {
      if (!noLoading) {
        globalStoreService.setValue('isLoading', false);
      }
    });
}

function getDataNoLoading() {
  getNetData().then((data: any) => {
    if (data) {
      initData(data);
      getNetDetail(currentNodeId.value, currentNode.value, true);
      checkHotPluginComplete();
      checkHasNetCardAllComplete();
    } else {
      showElMessage('error', errorMsg);
    }
  });
}

function initTimer() {
  if (timer) {
    return;
  }
  timer = setInterval(() => {
    getDataNoLoading();
  }, 1000);
}

function cancelTimer() {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
}

function checkFirstEnterHotPlugin() {
  if (!firstEntry) {
    return;
  }
  const findNetCard = netCardData.find(e => e.orderlyHotplugCtrlStatus === 'Uninstalling');
  if (findNetCard) {
    firstEntry = false;
    currentHotplugCardId = findNetCard.adapterId;
    elNotification.closeAll();
    elNotification({
      title: traduction('NET_UNINSTALLED_NOTICE_SWAP_TITLE', {
        netCard: getNetCardName(currentHotplugCardId),
      }),
      message: traduction('NET_UNINSTALLED_NOTICE_SWAP_CONTENT'),
      icon: UploadingIcon as any,
      position: 'bottom-right',
      duration: 0,
      offset: 10,
    });
    initTimer();
  } else {
    const findNetCardUninstalled = netCardData.find(
      e => e.orderlyHotplugCtrlStatus === 'Uninstalled',
    );
    if (findNetCardUninstalled) {
      initTimer();
    }
  }
}

function checkHotPluginComplete() {
  if (!currentHotplugCardId) {
    return;
  }
  const findNetCard = netCardData.find(
    e =>
      e.adapterId === currentHotplugCardId &&
      e.orderlyHotplugCtrlStatus === 'Uninstalled',
  );
  if (findNetCard) {
    elNotification.closeAll();
    elNotification({
      title: traduction('NET_UNINSTALLED_NOTICE_UNINSTALLED_TITLE', {
        netCard: getNetCardName(showData.AdapterId),
      }),
      message: traduction('NET_UNINSTALLED_NOTICE_UNINSTALLED_CONTENT'),
      type: 'success',
      position: 'bottom-right',
      offset: 10,
    });
    currentHotplugCardId = '';
  }
}

function checkHasNetCardAllComplete(): void {
  // 只有不存在卸载中和卸载完成状态时，才不需要继续请求
  const hasNetCardNotComplete = netCardData.find(e =>
    ['Uninstalling', 'Uninstalled'].includes(e.orderlyHotplugCtrlStatus),
  );
  if (!hasNetCardNotComplete) {
    cancelTimer();
  }
}

function getNetCardName(id: string) {
  return netCardData.find(e => e.adapterId === id)?.name || '';
}

getData();

onUnmounted(() => {
  cancelTimer();
});
</script>

<template>
  <div id="net" class="net-box">
    <div class="left-tree">
      <el-tree
        v-if="treeData.length > 0"
        id="netLeftMenu"
        ref="treeRef"
        v-reqKeepAlive.tree
        :data="treeData"
        :props="treeProps"
        node-key="id"
        :highlight-current="true"
        :default-checked-keys="[currentNodeKey]"
        :default-expanded-keys="defaultExpandedKeys"
        :current-node-key="currentNodeKey"
        default-expand-all
        @node-click="handleNodeClick"
      />
    </div>

    <div class="right-content">
      <component ref="showRef" :is="showComponent" :show-data="showData" @change-dialog-show="changeDialogShow" />
      <!-- 点击热插拔操作的弹窗 -->
      <Dialog ref="dialog" :config="dialogConfig" @close="sureSetting" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.net-box {
  flex: 1;
  display: flex;
  margin-right: 24px;
  overflow: hidden;
  height: 100%;

  .left-tree {
    width: 332px;
    min-width: 332px;
    padding: 16px 8px;
    position: relative;
    border-radius: 4px;
    background-color: var(--o-bg-color-base);

    :deep(.el-tree) {
      > .el-tree-node > .el-tree-node__content:hover {
        background-color: var(--o-bg-color-light) !important;

        .el-icon,
        .el-tree-node__label {
          color: var(--o-color-primary-secondary);
        }
      }

      .el-tree-node.is-checked > .el-tree-node__content {
        color: var(--o-tree-color);
        background-color: rgba(0, 0, 0, 0);
      }

      .is-expanded > .el-tree-node__content:hover {
        background-color: var(--o-bg-color-light);

        .el-tree-node__label {
          color: var(--o-color-primary-secondary);
        }
      }

      .is-expanded.is-checked > .el-tree-node__content .el-tree-node__label {
        color: var(--o-tree-color_current);
      }

      .is-expanded.is-checked > .el-tree-node__content:hover {
        > .el-tree-node__label,
        > .el-icon {
          color: var(--o-color-primary-secondary);
        }
      }

      .is-expanded.is-checked
        > .el-tree-node__children
        .el-tree-node
        .el-tree-node__content
        .el-tree-node__label {
        color: var(--o-tree-color_current);
      }

      .is-expanded.is-checked
        > .el-tree-node__children
        .el-tree-node
        .el-tree-node__content:hover
        .el-tree-node__label {
        color: var(--o-color-primary-secondary);
      }

      .is-expanded.is-checked
        > .el-tree-node__children
        .el-tree-node:nth-child(1)
        .el-tree-node__content {
        border-radius: 4px;
        background-color: var(--o-color-primary);

        .el-tree-node__label {
          color: var(--o-text-color-fourth);
          font-weight: 600;
        }
      }

      .is-expanded > .el-tree-node__children .is-checked .el-tree-node__content {
        border-radius: 4px;
        background-color: var(--o-color-primary);

        .el-tree-node__label {
          color: var(--o-text-color-fourth);
          font-weight: 600;
        }
      }

      .is-expanded > .el-tree-node__children .el-tree-node .el-tree-node__content:hover {
        color: var(--o-color-primary-secondary);
      }

      .is-expanded > .el-tree-node__children .is-checked .el-tree-node__content:hover {
        color: var(--o-text-color-fourth);
      }
    }
  }

  .right-content {
    margin-left: 8px;
    flex: 1;
    max-height: 100%;

    .card-box{
      overflow: hidden;
    }

    :deep(.el-dialog) {
      width: 432px;

      .el-dialog__body {
        .row {
          display: flex;
          align-items: center;

          .el-icon {
            margin-right: 16px;
            font-size: 24px;
          }
        }
      }
    }

    :deep(.el-table--border.table-first-floor) {
      .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-table--border {
        .el-table__cell:first-child .cell {
          padding-left: 10px;
          margin-left: 0;
        }

        .el-table__cell .cell {
          width: 100%;
          margin-left: 0;
        }

        tr,
        colgroup {
          th:nth-child(1),
          col:nth-child(1),
          td:nth-child(1) {
            width: 100%;
            max-width: none;
          }
        }
      }
    }
  }
}
</style>
