<script setup lang="ts">
import useStore from '@/stores';
import { reqPath } from '@/api/reqPath';
import { colors } from '@/model/colors';
import { traduction } from '@/utils/language';
import { getStoreData } from '@/utils/composition';
import { platform, monitorType } from '@/model/base-enum';
import { ref, reactive, shallowRef, computed, watch, nextTick } from 'vue';
import { isLowBrowserVer, showElMessage } from '@/utils/utils';
import { rangeVerification } from '@/validators/validation-functions';
import { IconDelete, IconRefresh, IconAlarm } from '@computing/opendesign-icons';
import { IMoitorThresholdPercent, IChartsData } from '@/model/System/monitor-interface';
import { getAimData, changeThresholdPercent, clearHistory } from './monitor.server';
import { UserPrivil } from '@/model/base-enum';
import { checkPrivil } from '@/apps/app-bmc/router/routes';

import Lock from '@/components/Lock/Lock.vue';
import Editor from '@/components/Editor/Editor.vue';
import Loading from '@/components/Loading/Loading.vue';
import GlobalStoreService from '@/services/gloabal-store-service';
import NetworkChart from '@/pages/System/Monitor/components/NetworkChart.vue';
import NoDataAvailable from '@/components/NoDataAvailable/NoDataAvailable.vue';
import PullDownTriangle from '@/components/PullDownTriangle/PullDownTriangle.vue';
import DiskChartOfPie from '@/pages/System/Monitor/components/DiskChartOfPie.vue';
import DiskChartOfBar from '@/pages/System/Monitor/components/DiskChartOfBar.vue';
import CpuAndMemoryChart from '@/pages/System/Monitor/components/CpuAndMemoryChart.vue';
import SingleLineFailurePrompt from '@/components/SingleLineFailurePrompt/SingleLineFailurePrompt.vue';
import { useHome, Resolution } from '@/pages/Home/hooks/useHome';


const globalStoreService = new GlobalStoreService();
const { getResolution, getWebStyle } = useHome();

const resolution = ref(getResolution);
const chartShow = ref(true);

const clearTip = traduction('COMMON_CLEAR');
const errorMsg = traduction('COMMON_FAILED');
const successMsg = traduction('COMMON_SUCCESS');
const refreshTip = traduction('COMMON_REFRESH');
const echartsTitle = traduction('MONITOR_USAGE') + '(%)';
const multihost = computed(() => getStoreData('loct', 'multihost'));
const processorSupported = computed(() => getStoreData('loct', 'processorSupported'));
const memorySupported = computed(() => getStoreData('loct', 'memorySupported'));
const storageSupported = computed(() => getStoreData('loct', 'storageSupported'));
const networkAdapterSupported = computed(() => getStoreData('loct', 'networkAdapterSupported'));
const ibmaspt = computed(() => getStoreData('loct', 'ibmaspt'));

const isPrivileges = checkPrivil(UserPrivil.baseConfig);
const dialogVisible = ref(false);
const isLowBrowserVersion = isLowBrowserVer();
const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});

// 用户信息
const user = {
  platform: getStoreData('loct', 'platform'),
  iBMARunning: getStoreData('loct', 'ibmarun'),
};

let cpuDatas = reactive(<IChartsData>[]);
let rawCpuDatas = reactive(<any>[]);
let memoryData: IChartsData = reactive({});
let networkData: IChartsData = reactive({});
let hardDiskData: IChartsData = reactive({});

// 编辑输入框的popover设置
const popoverSetting = {
  // 是否有
  show: true,
  // popover的类型,是简单的字符串还是比较复杂的自定义内容（自定义的需要传组件）
  type: 'ordinary', // ordinary(简单的字符串)或者complex(复杂的自定义展示组件)
  // 自定义的popover展示组件配置
  popoverSlotSetting: {
    // 展示的组件
    component: shallowRef(SingleLineFailurePrompt),
    // 传给组件的数据
    data: traduction('VALIDTOR_INTER_INTGER_RANGE', [0, 100]),
  },
  // popover宽度
  width: 'auto',
  // popover的类名
  popperClass: 'no-wrap-popover',
  // 展示内容
  content: traduction('VALIDTOR_INTGER_RANGE', [0, 100]),
  // 展示位置
  placement: 'top',
  // popover触发方式
  trigger: 'focus',
};

// 编辑输入框的校验规则(部分规则)
const rule = {
  required: true,
  min: 0,
  max: 100,
  isInteger: true,
  trigger: 'change',
};

const smsName = store.state.loct.smsName;
const cpuTip1 = traduction('MONITOR_CPU_ARM_TIP', { smsName });
const cpuTip2 = traduction('MONITOR_CPU_INFO', { smsName });
const cpu: IMoitorThresholdPercent = reactive({
  tip: user.platform === 'Arm' ? cpuTip1 : cpuTip2,
  loading: false,
  confirm: (value: number) => {
    return function subConfirm(systemId: number ) {
      setThresholdPercent(value, 'cpu', systemId);
    };
  },
  rule: {
    ...rule,
    validator: (vRule: any, value: any, callback: any) => {
      const res = rangeVerification(vRule, value, callback);
      if (res) {
        cpu.popoverSetting.type = 'ordinary';
      } else {
        cpu.popoverSetting.type = 'complex';
      }
    },
  },
  popoverSetting: { ...popoverSetting },
});

const memoryTip1 = traduction('MONITOR_MEM_ARM_TIP', { smsName });
const memoryTip2 = traduction('MONITOR_MEM_INFO', { smsName });
const memory: IMoitorThresholdPercent = reactive({
  tip: user.platform === 'Arm' ? memoryTip1 : memoryTip2,
  loading: false,
  confirm: (value: number) => {
    setThresholdPercent(value, 'memory');
  },
  rule: {
    ...rule,
    validator: (vRule: any, value: any, callback: any) => {
      const res = rangeVerification(vRule, value, callback);
      if (res) {
        memory.popoverSetting.type = 'ordinary';
      } else {
        memory.popoverSetting.type = 'complex';
      }
    },
  },
  popoverSetting: { ...popoverSetting },
});

const network: IMoitorThresholdPercent = reactive({
  loading: false,
  tip: traduction('MONITOR_NET_INFO', { smsName }),
  confirm: (value: number) => {
    setThresholdPercent(value, 'network');
  },
  rule: {
    ...rule,
    validator: (vRule: any, value: any, callback: any) => {
      const res = rangeVerification(vRule, value, callback);
      if (res) {
        network.popoverSetting.type = 'ordinary';
      } else {
        network.popoverSetting.type = 'complex';
      }
    },
  },
  popoverSetting: { ...popoverSetting },
});

const hardDisk: IMoitorThresholdPercent = reactive({
  loading: false,
  tip: traduction('MONITOR_DISK_INFO', { smsName }),
  confirm: (value: number) => {
    setThresholdPercent(value, 'hardDisk');
  },
  rule: {
    ...rule,
    validator: (vRule: any, value: any, callback: any) => {
      const res = rangeVerification(vRule, value, callback);
      if (res) {
        hardDisk.popoverSetting.type = 'ordinary';
      } else {
        hardDisk.popoverSetting.type = 'complex';
      }
    },
  },
  popoverSetting: { ...popoverSetting },
});

function savaCpuThresholdPercent(value: number, systemId: number) {
  cpu.loading = true;
  changeThresholdPercent(reqPath.monitor.cpu, {
    SystemId: systemId,
    ThresholdPercent: Number(value),
  })
    .then(res => {
      showElMessage('success', successMsg);
      setCPUInfo(res);
      cpu.loading = false;
    })
    .catch(err => {
      showElMessage('error', errorMsg);
      cpu.loading = false;
    });
}

function savaMemoryThresholdPercent(value: number) {
  memory.loading = true;
  changeThresholdPercent(reqPath.monitor.memory, {
    ThresholdPercent: Number(value),
  })
    .then(() => {
      showElMessage('success', successMsg);
      memoryData.ThresholdPercent = value;
      memory.loading = false;
    })
    .catch(err => {
      showElMessage('error', errorMsg);
      memory.loading = false;
    });
}

function savaNetworkThresholdPercent(value: number) {
  network.loading = true;
  changeThresholdPercent(reqPath.monitor.network, {
    ThresholdPercent: Number(value),
  })
    .then(() => {
      showElMessage('success', successMsg);
      networkData.ThresholdPercent = value;
      network.loading = false;
    })
    .catch(err => {
      showElMessage('error', errorMsg);
      network.loading = false;
    });
}

function savaHardDiskThresholdPercent(value: number) {
  hardDisk.loading = true;
  changeThresholdPercent(reqPath.monitor.hardDisk, {
    ThresholdPercent: Number(value),
  })
    .then(() => {
      showElMessage('success', successMsg);
      hardDiskData.ThresholdPercent = value;
      hardDisk.loading = false;
    })
    .catch(err => {
      showElMessage('error', errorMsg);
      hardDisk.loading = false;
    });
}

// 保存编辑
function setThresholdPercent(value: number, type: string, systemId: number = 0): void {
  switch (type) {
    case monitorType.cpu: {
      savaCpuThresholdPercent(value, systemId);
      break;
    }
    case monitorType.memory: {
      savaMemoryThresholdPercent(value);
      break;
    }
    case monitorType.network: {
      savaNetworkThresholdPercent(value);
      break;
    }
    case monitorType.hardDisk: {
      savaHardDiskThresholdPercent(value);
      break;
    }
    default:
      break;
  }
}

function setCPUInfo(data: any): void {
  rawCpuDatas = data;
  let cData = <any>[];
  data.History.forEach((h: any, hIndex: number) => {
    let item: any = {
      History: JSON.parse(h.History),
      SystemId: h.SystemId,
    };
    data.ThresholdPercent.forEach((t: any) => {
      if (t.SystemId === item.SystemId) {
        item.ThresholdPercent = t.BandwidthThresholdPercent || 0;
      }
    })
    data.UsagePercent.forEach((u: any) => {
      if (u.SystemId === item.SystemId) {
        item.UsagePercent = u.BandwidthPercent !== undefined ? u.BandwidthPercent : '--';
      }
    })
    cData.push(item);
  })
  cpuDatas = cData;
  cpu.loading = false;
}

function setMemoryInfo(data: any): void {
  Object.assign(memoryData, data);
  memory.loading = false;
}

function setNetworkInfo(data: any): void {
  const { History } = data;
  Object.assign(networkData, data);
  if (History && typeof History === 'object' && History instanceof Array && History.length > 0) {
    networkChange(History[0].BWUWaveTitle);
  }
  network.loading = false;
}

// 网口带宽数据 下拉切换 改变展示数据
function networkChange(title: string) {
  networkData.BWUWaveTitle = title;
  networkData.showData = networkData.History.find((item: any) => {
    return item.BWUWaveTitle === title;
  });
  networkData.showData.showLineState = [];
  networkData.showData.showLineText = [];
  const length = networkData.showData.CurrentUtilisePercents.length;
  if (length) {
    for (let i = 1; i <= length; i++) {
      networkData.showData.showLineState.push(true);
      const current = networkData.showData.CurrentUtilisePercents[i-1];
      if (current !== null) {
        networkData.showData.showLineText.push(`Port${i} ( ${parseInt(current, 10)}% )`);
      } else {
        networkData.showData.showLineText.push(`Port${i} ( - - )`);
      }
    }
  } else {
    for (let i = 1; i <= networkData.showData.PortCount; i++) {
      networkData.showData.showLineText.push(`Port${i} ( - - )`);
    }
  }
}
function setDiskInfo(data: any): void {
  Object.assign(hardDiskData, data);
  hardDisk.loading = false;
}

function setTipInfo(usr: any) {
  if (usr.platform !== platform.ARM) {
    cpu.tip = cpuTip2;
    memory.tip = memoryTip2;
  }
}
setTipInfo(user);

// 刷新
function refresh(type: string): void {
  switch (type) {
    case monitorType.cpu:
      cpu.loading = true;
      getAimData('cpu')
        .then((data: any) => {
          setCPUInfo(data);
        })
        .catch(() => {
          showElMessage('error', errorMsg);
          cpu.loading = false;
        });
      break;
    case monitorType.memory:
      memory.loading = true;
      getAimData('memory')
        .then((data: any) => {
          setMemoryInfo(data);
        })
        .catch(() => {
          showElMessage('error', errorMsg);
          memory.loading = false;
        });
      break;
    case monitorType.network:
      network.loading = true;
      getAimData('network')
        .then((data: any) => {
          setNetworkInfo(data);
        })
        .catch(() => {
          showElMessage('error', errorMsg);
          network.loading = false;
        });
      break;
    case monitorType.hardDisk:
      hardDisk.loading = true;
      getAimData('hardDisk')
        .then((data: any) => {
          setDiskInfo(data);
        })
        .catch(() => {
          showElMessage('error', errorMsg);
          hardDisk.loading = false;
        });
      break;
    default:
      break;
  }
}

// 确认删除网口带宽数据
function networkClear(): void {
  if (isSystemLock.value) {
    return;
  }

  network.loading = true;
  clearHistory({
    BWUWaveTitle: networkData.BWUWaveTitle,
  })
    .then(() => {
      changeDialogShow(false);
      getAimData('network')
        .then((data: any) => {
          setNetworkInfo(data);
          showElMessage('success', successMsg);
        })
        .catch(err => {
          showElMessage('error', errorMsg);
          network.loading = false;
        });
    })
    .catch(err => {
      changeDialogShow(false);
      network.loading = false;
    });
}

// 修改弹窗显示状态
function changeDialogShow(state: boolean) {
  if (isSystemLock.value) {
    return;
  } else {
    dialogVisible.value = state;
  }
}

// 点击网口带宽占用率的图例
function checkLegendItem(index: number) {
  networkData.showData.showLineState[index] = !networkData.showData.showLineState[index];
}

function setLegendStyle(state: boolean, index: number) {
  return {
    background: state ? colors.lineColors[index] : 'var(--o-color-info-secondary)',
  };
}

watch(
  () => resolution.value,
  newVal => {
    chartShow.value = false;
    nextTick(() => {
      chartShow.value = true;
    });
  },
);

// 获取数据
function getData() {
  globalStoreService.setValue('isLoading', true);
  const reqList = [
    getAimData('cpu'),
    getAimData('memory'),
    getAimData('network'),
    getAimData('hardDisk'),
  ];
  Promise.all(reqList)
    .then(res => {
      setCPUInfo(res[0]);
      setMemoryInfo(res[1]);
      setNetworkInfo(res[2]);
      setDiskInfo(res[3]);
      globalStoreService.setValue('isLoading', false);
    })
    .catch(() => {
      globalStoreService.setValue('isLoading', false);
    })
    .finally(() => {
      chartShow.value = false;
      nextTick(() => {
        chartShow.value = true;
      });
    });
}

getData();
</script>

<template>
  <div id="monitorViewId" class="monitor-box">
    <!-- 内容区域 -->
    <div class="monitor-content">
      <!-- 主要内容区域 -->
      <div v-if="chartShow" class="content-details">
        <!-- CPU占用率 和 内存占用率 -->
        <div class="cup-npu-box" v-if="processorSupported.CPU">
          <!-- CPU占用率 -->
          <div 
            v-for="(cpuData, cIndex) in cpuDatas" 
            :key="cIndex" 
            class="cup-npu-part"
            :class="resolution === Resolution.DEFAULT ? '' : 'max-width'"
          >
            <Loading :state="cpu.loading" />
            <!-- title和刷新按钮 -->
            <div class="monitor-header">
              <span class="monitor-title">
                {{ (multihost ? $t('BMC_LOG_HOST') + cpuData.SystemId + ' ' : '') + $t('MONITOR_CPU_USAGE') }}
              </span>
              <el-tooltip :content="refreshTip" :teleported="false" placement="top" trigger-keys>
                <span id="cpuRefreshId" class="refresh" @click="refresh('cpu', cIndex)">
                  <el-icon>
                    <IconRefresh />
                  </el-icon>
                </span>
              </el-tooltip>
            </div>

            <!-- 鼠标移动上去有弹窗的部分 -->
            <el-tooltip :content="cpu.tip" :teleported="false" placement="top" trigger-keys>
              <div
                v-if="!cpuData || !cpuData.History || !cpuData.History.length"
                id="cpuTipId"
                class="tip"
              >
                {{ cpu.tip }}
              </div>
            </el-tooltip>

            <!-- 门限值-当前值 -->
            <div class="subtext">
              <div class="left-part">
                <div class="threshold-num">
                  <div class="threshold">{{ $t('MONITOR_THRESHOLD') }}</div>
                  <div v-if="!isPrivileges || isSystemLock" class="num">
                    {{ cpuData.ThresholdPercent }}%
                  </div>

                  <Editor
                    v-if="isPrivileges && !isSystemLock"
                    :id-str="'cpuEditorId'"
                    :input-type="'text'"
                    :value="cpuData.ThresholdPercent"
                    :unit="'%'"
                    :rule="cpu.rule"
                    :popover-setting="cpu.popoverSetting"
                    @editor="cpu.editor"
                    @cancel="cpu.cancel"
                    @confirm="cpu.confirm($event)(cpuData.SystemId)"
                  />
                </div>
              </div>

              <div class="right-part">
                <div class="now-num-left">
                  <div>{{ $t('MONITOR_CURRENT_VAL') }}</div>
                  <div v-if="cpuData.UsagePercent !== '--' && cpuData.UsagePercent !== null">%</div>
                </div>
                <div v-if="cpuData.UsagePercent !== null" id="cpuCurrentId" class="current-value num">
                  {{ cpuData.UsagePercent }}
                </div>
                <div v-else id="cpuCurrentId" class="display-value num">
                  -- 
                </div>
              </div>
            </div>

            <!-- echarts区域 -->
            <div
              v-if="
                cpuData && cpuData.History && cpuData.History.length !== 0 && !isLowBrowserVersion
              "
              class="chart-box"
            >
              <CpuAndMemoryChart
                :type="$t('MONITOR_CPU_USAGE')"
                :title="echartsTitle"
                :show-data="cpuData"
                :system-id="cpuData.SystemId"
              />
            </div>

            <!-- 无数据 -->
            <NoDataAvailable
              v-if="
                (!cpuData || !cpuData.History || cpuData.History.length === 0) &&
                  !isLowBrowserVersion
              "
            />

            <!-- 浏览器版本不支持 -->
            <div v-if="isLowBrowserVersion" class="no-data-box">
              <img class="no-data-img" src="@/assets/common/image/no-data.svg" />
              <div class="no-data-text">
                {{ $t('LOGIN_BROWSER_UPDATE') }}
              </div>
            </div>
          </div>

          <!-- 内存占用率 -->
          <div v-if="resolution === Resolution.DEFAULT && memorySupported && ibmaspt" class="cup-npu-part">
            <Loading :state="memory.loading" />
            <div class="monitor-header">
              <span class="monitor-title">{{ $t('MONITOR_MEMORY_USAGE') }}</span>
              <el-tooltip :content="refreshTip" :teleported="false" placement="top" trigger-keys>
                <span id="memoryRefreshId" class="refresh" @click="refresh('memory')">
                  <el-icon>
                    <IconRefresh />
                  </el-icon>
                </span>
              </el-tooltip>
            </div>

            <!-- 鼠标移动上去有弹窗的部分 -->
            <el-tooltip
              class="item"
              :content="memory.tip"
              :teleported="false"
              placement="top"
              trigger-keys
            >
              <div
                v-if="!memoryData || !memoryData.History || !memoryData.History.length"
                id="memoryTip"
                class="tip"
              >
                {{ memory.tip }}
              </div>
            </el-tooltip>

            <!-- 门限值-当前值 -->
            <div class="subtext">
              <div class="left-part">
                <div class="threshold-num">
                  <span class="threshold">{{ $t('MONITOR_THRESHOLD') }}</span>
                  <span v-if="!isPrivileges || isSystemLock" class="num">
                    {{ memoryData.ThresholdPercent }}%
                  </span>
                  <Editor
                    v-if="isPrivileges && !isSystemLock"
                    :id-str="'memoryEditorId'"
                    :input-type="'text'"
                    :value="memoryData.ThresholdPercent"
                    :unit="'%'"
                    :rule="memory.rule"
                    :popover-setting="memory.popoverSetting"
                    @editor="memory.editor"
                    @cancel="memory.cancel"
                    @confirm="memory.confirm"
                  />
                </div>

                <div class="nums-box">
                  <!-- 总内存 -->
                  <span
                    v-if="memoryData.CapacityGiB || memoryData.CapacityGiB === 0"
                    id="totalMemoryId"
                    :title="
                      $t('MONITOR_TOTAL_SYSTEM_MEMORY_GIB') + String(memoryData.CapacityGiB) + 'GB'
                    "
                    class="memory-info"
                  >
                    <span class="key">{{ $t('MONITOR_TOTAL_SYSTEM_MEMORY_GIB') }}</span>
                    <span class="value">{{ memoryData.CapacityGiB }}</span>
                    <span class="unit">GB</span>
                  </span>

                  <!-- 剩余内存 -->
                  <span
                    v-if="memoryData.FreeGiB || memoryData.FreeGiB === 0"
                    id="freeMemoryId"
                    :title="
                      $t('MONITOR_SYSTEM_MEMORY_FREE_GIB') + String(memoryData.FreeGiB) + 'GB'
                    "
                    class="memory-info"
                  >
                    <span class="key">{{ $t('MONITOR_SYSTEM_MEMORY_FREE_GIB') }}</span>
                    <span class="value">{{ memoryData.FreeGiB }}</span>
                    <span class="unit">GB</span>
                  </span>

                  <!-- 缓存区 -->
                  <span
                    v-if="memoryData.CachedGiB || memoryData.CachedGiB === 0"
                    id="cacheMemoryId"
                    :title="
                      $t('MONITOR_SYSTEM_MEMORY_CACHED_GIB') + String(memoryData.CachedGiB) + 'GB'
                    "
                    class="memory-info"
                  >
                    <span class="key">{{ $t('MONITOR_SYSTEM_MEMORY_CACHED_GIB') }}</span>
                    <span class="value">{{ memoryData.CachedGiB }}</span>
                    <span class="unit">GB</span>
                  </span>

                  <!-- 缓冲器 -->
                  <span
                    v-if="memoryData.BuffersGiB || memoryData.BuffersGiB === 0"
                    id="bufferMemoryId"
                    :title="
                      $t('MONITOR_SYSTEM_MEMORY_BUFFERS_GIB') + String(memoryData.BuffersGiB) + 'GB'
                    "
                    class="memory-info"
                  >
                    <span class="key">{{ $t('MONITOR_SYSTEM_MEMORY_BUFFERS_GIB') }}</span>
                    <span class="value">{{ memoryData.BuffersGiB }}</span>
                    <span class="unit">GB</span>
                  </span>
                </div>
              </div>

              <!-- 当前值 -->
              <div class="right-part">
                <div class="now-num-left">
                  <div>{{ $t('MONITOR_CURRENT_VAL') }}</div>
                  <div v-if="memoryData.UsagePercent !== '--' && memoryData.UsagePercent !== null">%</div>
                </div>
                <div v-if="memoryData.UsagePercent !== null" id="memoryCurrentId" class="current-value num">
                  {{ memoryData.UsagePercent }}
                </div>
                <div v-else id="memoryCurrentId" class="display-value num">
                  --
                </div>
              </div>
            </div>

            <!-- echarts区域 -->
            <div
              v-if="
                memoryData &&
                  memoryData.History &&
                  memoryData.History.length !== 0 &&
                  !isLowBrowserVersion
              "
              class="chart-box"
            >
              <CpuAndMemoryChart
                id="memoryChartsId"
                :type="$t('MONITOR_MEMORY_USAGE')"
                :title="echartsTitle"
                :show-data="memoryData"
              />
            </div>

            <!-- 无数据 -->
            <NoDataAvailable
              v-if="
                (!memoryData || !memoryData.History || memoryData.History.length === 0) &&
                  !isLowBrowserVersion
              "
            />

            <!-- 浏览器版本不支持 -->
            <div v-if="isLowBrowserVersion" class="no-data-box">
              <img class="no-data-img" src="@/assets/common/image/no-data.svg" />
              <div class="no-data-text">
                {{ $t('LOGIN_BROWSER_UPDATE') }}
              </div>
            </div>
          </div>
        </div>
        <!-- 内存占用率 -->
        <div v-if="resolution !== Resolution.DEFAULT && memorySupported && ibmaspt" class="cup-npu-part">
          <Loading :state="memory.loading" />
          <div class="monitor-header">
            <span class="monitor-title">{{ $t('MONITOR_MEMORY_USAGE') }}</span>
            <el-tooltip :content="refreshTip" :teleported="false" placement="top" trigger-keys>
              <span id="memoryRefreshId" class="refresh" @click="refresh('memory')">
                <el-icon>
                  <IconRefresh />
                </el-icon>
              </span>
            </el-tooltip>
          </div>

          <!-- 鼠标移动上去有弹窗的部分 -->
          <el-tooltip
            class="item"
            :content="memory.tip"
            :teleported="false"
            placement="top"
            trigger-keys
          >
            <div
              v-if="!memoryData || !memoryData.History || !memoryData.History.length"
              id="memoryTip"
              class="tip"
            >
              {{ memory.tip }}
            </div>
          </el-tooltip>

          <!-- 门限值-当前值 -->
          <div class="subtext">
            <div class="left-part">
              <div class="threshold-num">
                <span class="threshold">{{ $t('MONITOR_THRESHOLD') }}</span>
                <span v-if="!isPrivileges || isSystemLock" class="num">
                  {{ memoryData.ThresholdPercent }}%
                </span>
                <Editor
                  v-if="isPrivileges && !isSystemLock"
                  :id-str="'memoryEditorId'"
                  :input-type="'text'"
                  :value="memoryData.ThresholdPercent"
                  :unit="'%'"
                  :rule="memory.rule"
                  :popover-setting="memory.popoverSetting"
                  @editor="memory.editor"
                  @cancel="memory.cancel"
                  @confirm="memory.confirm"
                />
              </div>

              <div class="nums-box">
                <!-- 总内存 -->
                <span
                  v-if="memoryData.CapacityGiB || memoryData.CapacityGiB === 0"
                  id="totalMemoryId"
                  :title="
                    $t('MONITOR_TOTAL_SYSTEM_MEMORY_GIB') + String(memoryData.CapacityGiB) + 'GB'
                  "
                  class="memory-info"
                >
                  <span class="key">{{ $t('MONITOR_TOTAL_SYSTEM_MEMORY_GIB') }}</span>
                  <span class="value">{{ memoryData.CapacityGiB }}</span>
                  <span class="unit">GB</span>
                </span>

                <!-- 剩余内存 -->
                <span
                  v-if="memoryData.FreeGiB || memoryData.FreeGiB === 0"
                  id="freeMemoryId"
                  :title="$t('MONITOR_SYSTEM_MEMORY_FREE_GIB') + String(memoryData.FreeGiB) + 'GB'"
                  class="memory-info"
                >
                  <span class="key">{{ $t('MONITOR_SYSTEM_MEMORY_FREE_GIB') }}</span>
                  <span class="value">{{ memoryData.FreeGiB }}</span>
                  <span class="unit">GB</span>
                </span>

                <!-- 缓存区 -->
                <span
                  v-if="memoryData.CachedGiB || memoryData.CachedGiB === 0"
                  id="cacheMemoryId"
                  :title="
                    $t('MONITOR_SYSTEM_MEMORY_CACHED_GIB') + String(memoryData.CachedGiB) + 'GB'
                  "
                  class="memory-info"
                >
                  <span class="key">{{ $t('MONITOR_SYSTEM_MEMORY_CACHED_GIB') }}</span>
                  <span class="value">{{ memoryData.CachedGiB }}</span>
                  <span class="unit">GB</span>
                </span>

                <!-- 缓冲器 -->
                <span
                  v-if="memoryData.BuffersGiB || memoryData.BuffersGiB === 0"
                  id="bufferMemoryId"
                  :title="
                    $t('MONITOR_SYSTEM_MEMORY_BUFFERS_GIB') + String(memoryData.BuffersGiB) + 'GB'
                  "
                  class="memory-info"
                >
                  <span class="key">{{ $t('MONITOR_SYSTEM_MEMORY_BUFFERS_GIB') }}</span>
                  <span class="value">{{ memoryData.BuffersGiB }}</span>
                  <span class="unit">GB</span>
                </span>
              </div>
            </div>

            <!-- 当前值 -->
            <div class="right-part">
              <div class="now-num-left">
                <div>{{ $t('MONITOR_CURRENT_VAL') }}</div>
                <div v-if="memoryData.UsagePercent !== '--' && memoryData.UsagePercent !== null">%</div>
              </div>
              <div v-if="memoryData.UsagePercent !== null" id="memoryCurrentId" class="current-value num">
                {{ memoryData.UsagePercent }}
              </div>
              <div v-else id="memoryCurrentId" class="display-value num">
                --
              </div>
            </div>
          </div>

          <!-- echarts区域 -->
          <div
            v-if="
              memoryData &&
                memoryData.History &&
                memoryData.History.length !== 0 &&
                !isLowBrowserVersion
            "
            class="chart-box"
          >
            <CpuAndMemoryChart
              id="memoryChartsId"
              :type="$t('MONITOR_MEMORY_USAGE')"
              :title="echartsTitle"
              :show-data="memoryData"
            />
          </div>

          <!-- 无数据 -->
          <NoDataAvailable
            v-if="
              (!memoryData || !memoryData.History || memoryData.History.length === 0) &&
                !isLowBrowserVersion
            "
          />

          <!-- 浏览器版本不支持 -->
          <div v-if="isLowBrowserVersion" class="no-data-box">
            <img class="no-data-img" src="@/assets/common/image/no-data.svg" />
            <div class="no-data-text">
              {{ $t('LOGIN_BROWSER_UPDATE') }}
            </div>
          </div>
        </div>
        <!-- 网口带宽占用率 -->
        <div v-if="networkAdapterSupported && ibmaspt" class="full-width">
          <Loading :state="network.loading" />
          <div class="monitor-header">
            <span class="monitor-title">{{ $t('MONITOR_BANDWIDTH_USAGE') }}</span>

            <div class="right-actions">
              <!-- 下拉选择 -->
              <el-select
                v-if="networkData.History && networkData.History.length !== 0"
                v-model="networkData.BWUWaveTitle"
                v-addId.select="'monitorSelectId'"
                :teleported="false"
                :suffix-icon="PullDownTriangle"
                @change="networkChange"
              >
                <el-option
                  v-for="item in networkData.History"
                  :key="item.BWUWaveTitle"
                  :label="item.BWUWaveTitle"
                  :value="item.BWUWaveTitle"
                />
              </el-select>

              <!-- 删除 -->
              <el-tooltip
                v-if="
                  networkData.showData &&
                    networkData.showData.UtilisePercents &&
                    networkData.showData.UtilisePercents.length &&
                    isPrivileges
                "
                :content="clearTip"
                :teleported="false"
                placement="top"
                trigger-keys
              >
                <span
                  id="networkClearId"
                  :class="['del', 'img', isSystemLock ? 'disabled-btn' : '']"
                  @click="changeDialogShow(true)"
                >
                  <el-icon>
                    <IconDelete />
                  </el-icon>
                </span>
              </el-tooltip>

              <!-- 确认删除的弹窗 -->
              <div v-if="dialogVisible" v-reqKeepAlive.dialog>
                <el-dialog
                  v-model="dialogVisible"
                  :title="$t('ALARM_OK')"
                  :close-on-click-modal="false"
                >
                  <div class="content">
                    <el-icon>
                      <IconAlarm />
                    </el-icon>
                    <span>{{ $t('COMMON_ASK_OK') }}</span>
                  </div>
                  <template #footer>
                    <span class="dialog-footer">
                      <el-button
                        type="primary"
                        :disabled="isSystemLock"
                        size="small"
                        @click="networkClear"
                      >
                        {{ $t('COMMON_OK') }}
                      </el-button>
                      <el-button size="small" @click="changeDialogShow(false)">
                        {{ $t('COMMON_CANCEL') }}
                      </el-button>
                    </span>
                  </template>
                </el-dialog>
              </div>

              <!-- 刷新 -->
              <el-tooltip :content="refreshTip" :teleported="false" placement="top" trigger-keys>
                <span id="networkRefreshId" class="refresh" @click="refresh('network')">
                  <el-icon>
                    <IconRefresh />
                  </el-icon>
                </span>
              </el-tooltip>
            </div>
          </div>

          <!-- 鼠标移动上去有弹窗的部分 -->
          <el-tooltip :content="network.tip" :teleported="false" placement="top" trigger-keys>
            <div
              v-if="!networkData.History || !networkData.History.length"
              id="networkTip"
              class="tip"
            >
              {{ network.tip }}
            </div>
          </el-tooltip>

          <!-- 门限值 -->
          <div class="subtext">
            <span class="threshold">{{ $t('MONITOR_THRESHOLD') }}</span>
            <span v-if="!isPrivileges || isSystemLock" class="num">
              {{ networkData.ThresholdPercent }}%
            </span>
            <Editor
              v-if="isPrivileges && !isSystemLock"
              :id-str="'networkEditorId'"
              :input-type="'text'"
              :value="networkData.ThresholdPercent"
              :unit="'%'"
              :rule="network.rule"
              :popover-setting="network.popoverSetting"
              @editor="network.editor"
              @cancel="network.cancel"
              @confirm="network.confirm"
            />

            <div
              v-if="networkData && networkData.showData && networkData.showData.showLineState"
              class="legend-box"
            >
              <div
                v-for="(item, index) in networkData.showData.showLineState"
                :key="index"
                :class="['legend-item', item ? '' : 'no-check-legend-item']"
                @click="checkLegendItem(index)"
              >
                <span class="block-line" :style="setLegendStyle(item, index)"></span>
                <span class="text">{{ networkData.showData.showLineText[index] }}</span>
              </div>
            </div>
          </div>

          <!-- 图表数据 -->
          <div
            v-if="
              !isLowBrowserVersion &&
                networkData.History &&
                networkData.History.length &&
                networkData.showData &&
                networkData.showData.UtilisePercents &&
                networkData.showData.UtilisePercents.length
            "
          >
            <NetworkChart
              id="networkChartsId"
              :title="echartsTitle"
              :show-data="networkData.showData"
              :threshold-percent="Number(networkData.ThresholdPercent)"
            />
          </div>

          <!-- 无数据 -->
          <NoDataAvailable
            v-if="
              (!networkData ||
                !networkData.History ||
                networkData.History.length === 0 ||
                !networkData.showData ||
                !networkData.showData.UtilisePercents ||
                networkData.showData.UtilisePercents.length === 0) &&
                !isLowBrowserVersion
            "
          />

          <!-- 浏览器版本不支持 -->
          <div v-if="isLowBrowserVersion" class="no-data-box">
            <img class="no-data-img" src="@/assets/common/image/no-data.svg" />
            <div class="no-data-text">
              {{ $t('LOGIN_BROWSER_UPDATE') }}
            </div>
          </div>
        </div>

        <!-- 磁盘占用率 -->
        <div v-if="storageSupported && ibmaspt" class="full-width hard-disk-box">
          <Loading :state="hardDisk.loading" />
          <!-- 标题和刷新 -->
          <div class="monitor-header">
            <span class="monitor-title">{{ $t('MONITOR_DISK_USAGE') }}</span>
            <el-tooltip :content="refreshTip" :teleported="false" placement="top" trigger-keys>
              <span id="diskRefresh" class="refresh" @click="refresh('hardDisk')">
                <el-icon>
                  <IconRefresh />
                </el-icon>
              </span>
            </el-tooltip>
          </div>

          <!-- 鼠标移动上去有弹窗的部分 -->
          <el-tooltip :content="hardDisk.tip" :teleported="false" placement="top" trigger-keys>
            <div
              v-if="!hardDiskData.Partitions || !hardDiskData.Partitions.length"
              id="networkTip"
              class="tip"
            >
              {{ hardDisk.tip }}
            </div>
          </el-tooltip>

          <!-- 门限值 -->
          <div class="subtext">
            <span class="threshold">{{ $t('MONITOR_THRESHOLD') }}</span>
            <span v-if="!isPrivileges || isSystemLock" class="num">
              {{ hardDiskData.ThresholdPercent }}%
            </span>
            <Editor
              v-if="isPrivileges && !isSystemLock"
              :id-str="'hardDiskEditorId'"
              :input-type="'text'"
              :value="hardDiskData.ThresholdPercent"
              :unit="'%'"
              :rule="hardDisk.rule"
              :popover-setting="hardDisk.popoverSetting"
              @editor="hardDisk.editor"
              @cancel="hardDisk.cancel"
              @confirm="hardDisk.confirm"
            />
          </div>

          <!-- 图表数据 -->
          <div
            v-if="!isLowBrowserVersion && hardDiskData.Partitions && hardDiskData.Partitions.length"
          >
            <DiskChartOfPie
              v-if="hardDiskData.Partitions.length <= 8"
              id="hardDiskChartsId"
              :charts-data="hardDiskData.Partitions"
              :threshold-percent="Number(hardDiskData.ThresholdPercent)"
            />
            <DiskChartOfBar
              v-else
              id="hardDiskChartsId"
              :title="echartsTitle"
              :charts-data="hardDiskData.Partitions"
              :threshold-percent="Number(hardDiskData.ThresholdPercent)"
            />
          </div>

          <!-- 无数据 -->
          <NoDataAvailable
            v-if="
              (!hardDiskData || !hardDiskData.Partitions || hardDiskData.Partitions.length === 0) &&
                !isLowBrowserVersion
            "
          />

          <!-- 浏览器版本不支持 -->
          <div v-if="isLowBrowserVersion" class="no-data-box">
            <img class="no-data-img" src="@/assets/common/image/no-data.svg" />
            <div class="no-data-text">
              {{ $t('LOGIN_BROWSER_UPDATE') }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.monitor-box {
  font-size: 12px;
  color: var(--o-text-color-secondary);
  padding-right: 24px;

  .monitor-content {
    .content-details {
      .monitor-header {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .monitor-title {
          line-height: 24px;
          font-weight: 600;
          font-size: 16px;
          color: var(--o-text-color-primary);
        }

        .right-actions {
          display: flex;
          align-items: center;

          .el-select {
            width: 240px;
          }

          .del {
            margin-left: 16px;

            .el-icon {
              font-size: 18px;
            }
          }

          :deep(.el-select) {
            .el-select__caret.el-input__icon {
              margin: 0 !important;
            }
          }

          .refresh {
            margin-left: 10px;
          }
        }
      }

      :deep(.no-data-box) {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        top: 45%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        max-width: 290px;
        text-align: center;

        .no-data-text {
          color: var(--o-text-color-tertiary);
        }
      }

      .cup-npu-box {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        .cup-npu-part{
          width: calc(50% - 8px);
          margin-top: 0;
        }
        .max-width{
          margin-top: 16px;
          width: 100%;
        }
      }

      .cup-npu-part {
          background-color: var(--o-bg-color-base);
          padding: 24px 24px 16px 24px;
          position: relative;
          height: 380px;
          display: flex;
          margin-top: 16px;
          flex-direction: column;
          border-radius: 4px;

          &:first-of-type {
            margin-top: 0;
          }

          :deep(.el-popper) {
            max-width: 86%;
          }

          .subtext {
            margin-top: 16px;
            display: flex;
            justify-content: flex-start;
            align-items: flex-start;
            height: 48px;
            margin-bottom: 8px;
            .left-part {
              flex: 1;
              display: flex;
              align-items: flex-start;
              justify-content: space-between;

              .threshold-num {
                display: flex;
                align-items: center;
                margin-right: 16px;
                height: 23px;
                .threshold {
                  margin-right: 8px;
                }

                .num {
                  font-size: 16px;
                  color: var(--o-text-color-primary);
                }
              }

              .nums-box {
                display: flex;
                align-items: center;
                justify-content: flex-end;
                flex-wrap: wrap;
                .memory-info {
                  margin-right: 16px;
                  display: flex;
                  align-items: center;

                  .value {
                    margin: 0 4px;
                    font-size: 16px;
                    line-height: 24px;
                    font-weight: 500;
                    color: var(--o-text-color-primary);
                  }
                }
              }
            }

            .right-part {
              display: flex;
              align-items: center;

              .now-num-left {
                margin-right: 8px;
                display: flex;
                flex-direction: column;
                align-items: flex-end;
              }

              .current-value {
                font-size: 32px;
                color: var(--o-text-color-primary);
                line-height: 34px;
              }
              .display-value{
                font-size: 16px;
                color: var(--o-text-color-primary);
                line-height: 24px;
              }
            }
          }

          .chart-box {
            flex: 1;
          }
        }

      .full-width {
        margin-top: 16px;
        background-color: var(--o-bg-color-base);
        padding: 24px 24px 16px 24px;
        position: relative;
        min-height: 352px;
        border-radius: 4px;

        .subtext {
          margin-top: 10px;
          margin-bottom: 8px;
          display: flex;
          align-items: center;
          line-height: 32px;

          .threshold {
            margin-right: 8px;
            white-space: nowrap;
          }

          .editor-box {
            margin-right: 4px;
            :deep(#networkEditorIdSave) {
              white-space: nowrap;
            }
            :deep(#networkEditorIdCancel) {
              white-space: nowrap;
            }
          }

          .num {
            font-size: 16px;
            color: var(--o-text-color-primary);
          }

          .legend-box {
            display: flex;
            align-items: center;
            width: 100%;
            flex-wrap: wrap;

            .legend-item {
              margin-right: 24px;
              display: flex;
              align-items: center;
              cursor: pointer;

              .block-line {
                margin-right: 8px;
                display: inline-block;
                width: 16px;
                height: 3px;
              }

              .text {
                color: var(--o-text-color-secondary);
              }
            }

            .no-check-legend-item .text {
              color: var(--o-color-info-secondary);
            }
          }
        }

        :deep(.el-select .el-input .el-select__caret) {
          line-height: 32px;
        }

        :deep(.el-input__suffix .el-input__icon) {
          margin-right: 5px;
        }
      }

      .hard-disk-box {
        min-height: 360px;
      }

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

        .el-button {
          border-radius: 4px;
        }
      }

      .tip {
        margin-top: 4px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        color: var(--o-text-color-tertiary);
        font-size: 12px;
      }
    }

    .el-icon {
      font-size: 16px;
      color: var(--o-text-color-tertiary);
      cursor: pointer;
    }

    .el-icon:hover {
      color: var(--o-color-primary-secondary);
    }
  }

  .el-overlay {
    .content {
      display: flex;
      align-items: center;

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

  :deep(.el-form-item__error) {
    display: none;
  }

  .disabled-btn .el-icon {
    cursor: not-allowed !important;
    color: var(--o-text-color-tertiary) !important;
  }
}

@media screen and (max-width: 1919px) {
  .cup-npu-part {
    width: 100%;
  }
}
</style>
