//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { traduction } from '@/utils/language';
import { getRealColor, initOriginalData } from '@/utils/utils';
import { IEChartOption, IMonitorInfo } from '../home.datatype';
import { useHome, Resolution } from '../hooks/useHome';

const { getResolution, getWebStyle } = useHome();
const resolution = getResolution;
// 线条颜色，蓝色/橘黄色/红色，对应良好，严重，危险3种级别
const lineColors = ['#0062DC', '#F97611', '#E32020'];
function getColor(value: number | null, limitValue: number, totalValue: number) {
  let _color = '';
  const defaultColor = getRealColor('--o-border-color-light');

  if (value === null) {
    return [
      [0, lineColors[0]],
      [1, defaultColor],
    ];
  }

  if (limitValue === null || limitValue === undefined || value < limitValue) {
    _color = lineColors[0];
  } else {
    _color = lineColors[2];
  }

  return [
    [value / totalValue, _color],
    [1, defaultColor],
  ];
}

// 获取进风口的仪表颜色数据
function getTempInletColor(param: {
  curValue: number;
  minValue: number;
  maxValue: number;
  minInletLimit: number;
  maxInletLimit: number;
}): any[] {
  const defaultColor = getRealColor('--o-border-color-light');
  const percent = Math.abs(param.curValue / (Math.abs(param.minValue) + Math.abs(param.maxValue)));
  let color = '';
  if (param.curValue < param.minInletLimit) {
    color = lineColors[0];
  } else if (param.curValue >= param.maxInletLimit) {
    color = lineColors[2];
  } else {
    color = lineColors[1];
  }
  const startPos = param.curValue < 0 ? 0.5 - percent : 0.5 + percent;
  if (param.curValue < 0) {
    return [
      [0.5 - percent, defaultColor],
      [0.5, color],
      [1, defaultColor],
    ];
  } else {
    return [
      [0.5, defaultColor],
      [startPos, color],
      [1, defaultColor],
    ];
  }
}

let pad = function (s: string) {
  return s.length === 1 ? `0${s}` : s;
};

export function getBeautifulSeries(
  value: number,
  minValue: number,
  maxValue: number,
  title: string,
  lineColor: any,
) {
  const offsetAngle = 90;
  const totalAngle = 360;
  const split = 75;
  const asisWidth = 11;
  const startAngle = totalAngle + offsetAngle;
  let endAngle = 0;
  if (maxValue === minValue) {
    endAngle = startAngle;
  } else {
    endAngle = startAngle - Math.floor((value / (maxValue - minValue)) * totalAngle);
  }  
  let series: any[] = [
    {
      isCenterBg: true, // 标识是否为背景
      type: 'pie',
      radius: '56%',
      label: {
        // 默认已定义了样式： b（标题） c（值） d（标题-大） be（标题,告警色） ce（值,告警色） ded（标题-大，告警色）
        formatter: `{b|${title}}\n{t|${typeof value === 'number' ? value : '--'}}`,
        rich: {
          t: {
            fontSize: 32,
            lineHeight: 40,
            color: '--o-text-color-primary',
          },
        },
      },
    },
    {
      type: 'gauge',
      splitNumber: 1,
      startAngle: endAngle,
      endAngle: offsetAngle,
      axisLine: {
        show: false,
        lineStyle: {
          width: asisWidth,
          opacity: 0,
        },
      },
      splitLine: { show: false },
      axisTick: {
        length: asisWidth / 2,
        distance: -11,
        splitNumber: (maxValue - minValue) === 0 ? split : split - Math.floor((value / (maxValue - minValue)) * 80),
        lineStyle: {
          color: '#C3CEDF',
          width: 2,
        },
      },
      axisLabel: { show: false },
      pointer: { show: false },
      // 指针样式
      itemStyle: {},
      title: { show: false },
      detail: { show: false },
    },
  ];
  if (startAngle !== endAngle) {
    series.push({
      type: 'gauge',
      z: 5,
      splitNumber: 1,
      startAngle: startAngle === endAngle ? 0 : startAngle,
      endAngle: startAngle === endAngle ? 0 : endAngle,
      // 轴线样式
      axisLine: {
        show: false,
        lineStyle: {
          width: asisWidth,
          opacity: 0,
        },
      },
      // 分段样式
      splitLine: { show: false },
      // 刻度样式
      axisTick: {
        length: asisWidth * 2,
        distance: -27,
        splitNumber: (maxValue - minValue) ? Math.floor((value / (maxValue - minValue)) * split) : 0,
        lineStyle: {
          color: '#0062DC',
          width: 2,
          opacity: 0.25,
        },
      },
      axisLabel: { show: false },
      pointer: { show: false },
      // 指针样式
      itemStyle: {},
      progress: {
        show: false,
      },
      data: value ? [{ name: 'label22', value: value }] : [],
    });
  }
  return {
    series,
  };
}

export function getSeries(
  minValue: number,
  maxValue: number,
  title: string,
  lineColor: any,
  theme: string,
  value?: number,
) {
  return {
    series: [
      {
        isCenterBg: true, // 标识是否为背景
        type: 'pie',
        radius: '56%',
        label: {
          // 默认已定义了样式： b（标题） c（值） d（标题-大） be（标题,告警色） ce（值,告警色） ded（标题-大，告警色）
          formatter: (resolution.value === Resolution.SMALL && theme !== 'ibma') ? `{t|${typeof value === 'number' ? value : '--'}}` : `{b|${title}}\n{t|${typeof value === 'number' ? value : '--'}}`,
          rich: {
            t: {
              fontSize: 32,
              lineHeight: 40,
              color: '--o-text-color-primary',
            },
          },
        },
      },
      {
        type: 'gauge',
        data: value ? [{ name: 'label22', value: value }] : [],
        min: minValue,
        max: maxValue,
        splitNumber: 4,
        axisTick: {
          splitNumber: 10,
        },
        progress: {
          show: false,
        },
        axisLine: {
          // 坐标轴线
          lineStyle: {
            // 属性lineStyle控制线条样式,渐变色
            color: lineColor,
          },
        },
      },
    ],
  };
}

// 磁盘图
function getDiskMonitorOption(monitorInfo: IMonitorInfo, theme: string) {
  const limitValDisk = initOriginalData(monitorInfo.diskThresholdPercent, 100);
  const diskUsagePercent: any = monitorInfo.diskUsagePercent;
  const diskData = Number(monitorInfo.diskUsagePercent) || 0;
  const lineColor = getColor(diskData, limitValDisk, 100);
  if (theme === 'beautiful') {
    return getBeautifulSeries(
      typeof monitorInfo.diskUsagePercent === 'number' ? diskUsagePercent : null,
      0,
      100,
      `${traduction('HOME_DISK_USAGE').split('\n')[1]} (%)`,
      lineColor,
    );
  } else {
    return getSeries(
      0,
      100,
      `${traduction('HOME_DISK_USAGE').split('\n')[1]} (%)`,
      lineColor,
      theme,
      typeof monitorInfo.diskUsagePercent === 'number' ? diskUsagePercent : null,
    );
  }
}

// CPU图
function getCPUMonitorOption(monitorInfo: IMonitorInfo, theme: string) {
  const limitCPU = initOriginalData(monitorInfo.proThresholdPercent, 100);
  const proUseagePercent: any = monitorInfo.proUseagePercent;
  const cpuData = Number(monitorInfo.proUseagePercent) || 0;
  const lineColor = getColor(cpuData, limitCPU, 100);
  if (theme === 'beautiful') {
    return getBeautifulSeries(
      typeof monitorInfo.proUseagePercent === 'number' ? proUseagePercent : null,
      0,
      100,
      `${traduction('HOME_CPU_USAGE').split('\n')[1]} (%)`,
      lineColor,
    );
  } else {
    return getSeries(
      0,
      100,
      `${traduction('HOME_CPU_USAGE').split('\n')[1]} (%)`,
      lineColor,
      theme,
      typeof monitorInfo.proUseagePercent === 'number' ? proUseagePercent : null,
    );
  }
}

// 内存图
function getRamMonitorOption(monitorInfo: IMonitorInfo, theme: string) {
  const limitMemory = initOriginalData(monitorInfo.memThresholdPercent, 100);
  const usagePercent: any = monitorInfo.memUseagePercent;
  const ramData = Number(usagePercent) || 0;
  const lineColor = getColor(ramData, limitMemory, 100);
  if (theme === 'beautiful') {
    return getBeautifulSeries(
      typeof monitorInfo.memUseagePercent === 'number' ? usagePercent : null,
      0,
      100,
      `${traduction('HOME_MEMORY_OCCUPANCY_RATE').split('\n')[1]} (%)`,
      lineColor,
    );
  } else {
    return getSeries(
      0,
      100,
      `${traduction('HOME_MEMORY_OCCUPANCY_RATE').split('\n')[1]} (%)`,
      lineColor,
      theme,
      typeof monitorInfo.memUseagePercent === 'number' ? usagePercent : null,
    );
  }
}

// 进风口图
function getTempMonitorOption(monitorInfo: IMonitorInfo, theme: string) {
  let inletTempMin = monitorInfo.inletTempMinorThreshold;
  let inletTempMax = monitorInfo.inletTempMajorThreshold || 0;
  const inletTemperature: any = monitorInfo.inletTemperature;
  if (!inletTempMin && inletTempMax) {
    inletTempMin = inletTempMax + 1;
  }
  if (inletTempMin && !inletTempMin) {
    inletTempMax = inletTempMin - 1;
  }
  if (!inletTempMin && !inletTempMax) {
    inletTempMax = inletTemperature + 1;
    inletTempMin = inletTemperature + 1;
  }
  inletTempMin = inletTempMin ? inletTempMin : 0;
  const _liner = getTempInletColor({
    curValue: inletTemperature,
    minValue: -100,
    maxValue: 100,
    minInletLimit: inletTempMin,
    maxInletLimit: inletTempMax,
  });
  if (theme === 'beautiful') {
    return getBeautifulSeries(
      typeof monitorInfo.inletTempMajorThreshold === 'number' ? inletTemperature : null,
      -100,
      100,
      `${traduction('HOME_INLET_TEMPERATURE').split('\n')[1]} (℃)`,
      _liner,
    );
  } else {
    return getSeries(
      -100,
      100,
      `${traduction('HOME_INLET_TEMPERATURE').split('\n')[1]} (℃)`,
      _liner,
      theme,
      typeof monitorInfo.inletTempMajorThreshold === 'number' ? inletTemperature : null,
    );
  }
}

// 功率图
function getPowerMonitorOption(monitorInfo: IMonitorInfo, theme: string) {
  // 当前值
  const powerConsumedWatts: any = monitorInfo.powerConsumedWatts;
  // 总容量
  const powerCapacityWatts = monitorInfo.powerCapacityWatts || 0;
  // 设置的阈值（超出阈值，颜色变为红色）
  let limitPower = initOriginalData(monitorInfo.upperPowerThresholdWatts, powerCapacityWatts);
  if (limitPower === null && powerConsumedWatts !== null) {
    limitPower = powerConsumedWatts + 1;
  }
  const lineColor = getColor(powerConsumedWatts, limitPower, powerCapacityWatts);
  if (theme === 'beautiful') {
    return getBeautifulSeries(
      typeof monitorInfo.powerConsumedWatts === 'number' ? powerConsumedWatts : null,
      0,
      powerCapacityWatts as number,
      `${traduction('HOME_POWERW').split('\n')[1]} (W)`,
      lineColor,
    );
  } else {
    return getSeries(
      0,
      powerCapacityWatts as number,
      `${traduction('HOME_POWERW').split('\n')[1]} (W)`,
      lineColor,
      theme,
      typeof monitorInfo.powerConsumedWatts === 'number' ? powerConsumedWatts : null,
    );
  }
}

export function getChartData(
  monitorInfo: IMonitorInfo,
  showmointer: boolean,
  theme: string,
): IEChartOption[] {
  const chartOptions = [
    {
      id: 'homeDiskMonitor',
      option: getDiskMonitorOption(monitorInfo, theme),
      navigatorUrl: ['/navigate/system/monitor'],
      show: true || !!monitorInfo.diskUsagePercent,
      title: traduction('HOME_DISK_USAGE').split('\n')[0],
      label: `${traduction('HOME_DISK_USAGE').split('\n')[1]} (%)`,
    },
    {
      id: 'homeCPUMonitor',
      option: getCPUMonitorOption(monitorInfo, theme),
      navigatorUrl: ['/navigate/system/monitor'],
      show: true || !!monitorInfo.proUseagePercent,
      title: traduction('HOME_CPU_USAGE').split('\n')[0],
      label: `${traduction('HOME_CPU_USAGE').split('\n')[1]} (%)`,
    },
    {
      id: 'homeRamMonitor',
      option: getRamMonitorOption(monitorInfo, theme),
      navigatorUrl: ['/navigate/system/monitor'],
      show: true || !!monitorInfo.memUseagePercent,
      title: traduction('HOME_MEMORY_OCCUPANCY_RATE').split('\n')[0],
      label: `${traduction('HOME_MEMORY_OCCUPANCY_RATE').split('\n')[1]} (%)`,
    },
    {
      id: 'homeTempMonitor',
      option: getTempMonitorOption(monitorInfo, theme),
      navigatorUrl: ['/navigate/system/fans'],
      show: true || !!monitorInfo.inletTemperature,
      title: traduction('HOME_INLET_TEMPERATURE').split('\n')[0],
      label: `${traduction('HOME_INLET_TEMPERATURE').split('\n')[1]} (℃)`,
    },
    {
      id: 'homePowerMonitor',
      option: getPowerMonitorOption(monitorInfo, theme),
      navigatorUrl: ['/navigate/system/power'],
      routerParam: 'capping',
      show: true || !!monitorInfo.powerConsumedWatts,
      title: traduction('HOME_POWERW').split('\n')[0],
      label: `${traduction('HOME_POWERW').split('\n')[1]} (W)`,
    },
  ];
  return chartOptions;
}

export function factoryMonitorInfo(overviewData: any) {
  let monitorInfo: IMonitorInfo = {};
  const {
    Summary: {
      Processor: processor,
      Memory: memory,
      Storage: storage,
      Power: power,
      Thermal: thermal,
    },
  } = overviewData;

  const defaultValue = 0;
  if (processor) {
    monitorInfo = {
      ...monitorInfo,
      proUseagePercent: processor.UseagePercent === null ? '--' : processor.UseagePercent,
      proThresholdPercent: processor.ThresholdPercent,
    };
  }
  if (memory) {
    monitorInfo = {
      ...monitorInfo,
      memUseagePercent: memory.UseagePercent === null ? '--' : memory.UseagePercent,
      memThresholdPercent: memory.ThresholdPercent,
    };
  }
  if (storage) {
    storage.DiskUsagePercent = storage.DiskUsagePercent || defaultValue,
    monitorInfo = {
      ...monitorInfo,
      diskUsagePercent: storage.DiskUsagePercent === 255 ? '--' : storage.DiskUsagePercent,
      diskThresholdPercent: storage.DiskThresholdPercent,
    };
  }
  if (power) {
    monitorInfo = {
      ...monitorInfo,
      powerConsumedWatts: power.PowerConsumedWatts,
      powerCapacityWatts: power.PowerCapacityWatts,
      upperPowerThresholdWatts: power.UpperPowerThresholdWatts,
    };
  }
  if (thermal) {
    monitorInfo = {
      ...monitorInfo,
      inletTemperature: thermal.InletTemperature,
      inletTempMinorThreshold: thermal.InletTempMinorAlarmThreshold,
      inletTempMajorThreshold: thermal.InletTempMajorAlarmThreshold,
    };
  }
  return monitorInfo;
}
