//  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 type { IFanInfo, IIntelSpeedAdjust, IPumpInfo } from '../model/fan.datatype';
import { getRealColor, getThemeMode } from '@/utils/utils';
import { getStoreData } from '@/utils/composition';

const currentValuePadding = {
  zh: [-32, 0, 0, 8],
  en: [-32, 0, 0, 48],
  ja: [-32, 0, 0, 18],
  fr: [-32, 0, 0, 55],
  ru: [-32, 0, 0, 82],
};

let chartOption = {
  title: [
    {
      right: '0',
      text: '',
      textStyle: {
        rich: {
          title: {
            fontSize: 12,
            fontFamily: 'HarmonyOS Sans SC Medium',
            color: '',
            lineHeight: 16,
          },
          unit: {
            color: '',
            fontSize: 12,
            fontFamily: 'HarmonyOS Sans SC Medium',
            lineHeight: 16,
            padding: [-16, 0, 0, 24],
          },
          value: {
            fontSize: 32,
            fontFamily: 'HarmonyOS Sans SC Medium',
            color: '',
            lineHeight: 40,
            padding: [-32, 0, 0, 8],
          },
        },
      },
    },
  ],
  tooltip: {
    trigger: 'axis',
    extraCssText: 'padding:8px 16px; border-radius:1px;',
    backgroundColor: '',
    borderColor: '',
    formatter(param: any) {
      let res = '';
      for (const item of param) {
        res += `<div class="tooltip-item"><div class="tooltip-icon"></div><span class="tooptip-temp">${traduction(
          'FDM_TEMPERATURE',
        )}</span><span class="tooltip-value">${item.data}</span></div>`;
      }
      return `<span class="tooltip-time">${param[0].axisValue}</span><br>${res}`;
    },
  },
  xAxis: {
    show: true,
    type: 'category',
    boundaryGap: false,
    data: [] as string[],
    axisLine: {
      show: true,
      lineStyle: {
        width: 1,
        type: 'solid',
        color: '',
      },
    },
    axisTick: {
      show: false,
    },
    splitLine: {
      show: false,
    },
    axisLabel: {
      margin: 15,
      color: '',
      fontSize: 10,
      fontFamily: 'HarmonyOS Sans SC Medium',
      formatter(v: any) {
        return v.slice(5).replace(' ', '\n');
      },
    },
  },
  yAxis: {
    name: `${traduction('FDM_TEMPERATURE')} (°C)`,
    nameLocation: 'end',
    nameTextStyle: {
      color: '',
      fontSize: 12,
      lineHeight: 16,
      padding: [8, 0, 8, -8],
      fontFamily: 'HarmonyOS Sans SC Medium',
    },
    type: 'value',
    axisLine: {
      show: false,
    },
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '',
      },
    },
    offset: 2,
    axisTick: {
      show: false,
    },
    axisLabel: {
      margin: 14,
      textStyle: {
        align: 'right',
        baseline: 'bottom',
        color: '',
        fontSize: 12,
        fontFamily: 'HarmonyOS Sans SC Medium',
        lineHeight: 16,
      },
    },
    splitNumber: 4,
  },
  grid: {
    borderWidth: 0,
    containLabel: true,
    x: 2,
    y: 40,
    x2: 20,
    y2: 0,
  },
  series: [
    {
      name: traduction('FDM_TEMPERATURE'),
      smooth: true,
      showSymbol: false,
      type: 'line',
      lineStyle: {
        normal: {
          width: 2,
          color: '#0062DC',
        },
      },
      itemStyle: {
        normal: {
          color: '#0062DC',
        },
      },
      areaStyle: {
        normal: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#0062DC',
              },
              {
                offset: 1,
                color: '#fff',
              },
            ],
          },
          opacity: 0.2,
        },
      },
      data: [] as number[],
    },
  ],
};

export function getAirInletTemperature(data: any) {
  const history = data?.Inlet?.History;
  const inletTime: string[] = [];
  const inletTemp: number[] = [];
  history?.forEach((element: any) => {
    inletTime.push(element.Time.replace(' ', '\n'));
    inletTemp.push(element.InletTempCelsius);
  });
  const airInletInfo = {
    inletTemperature:
      data?.Inlet && data?.Inlet?.CurrentValue !== null && data?.Inlet?.CurrentValue !== undefined
        ? data?.Inlet?.CurrentValue
        : '--',
    time: inletTime,
    inletTempCelsius: inletTemp,
  };
  return airInletInfo;
}

export function getFanInfo(data: any) {
  const fanInfoList: IFanInfo[] = [];
  const fans = data.Fans;
  fans?.forEach((element: any) => {
    const fanInfo = fanStitching(element);
    if (data.FanCtrlMode === 'Auto') {
      fanInfo.expectedSpeedRatio = '--';
    } else {
      fanInfo.expectedSpeedRatio = element[0].ExpectedSpeedRatio ? element[0].ExpectedSpeedRatio : 20;
    }
    fanInfoList.push(fanInfo);
  });
  return fanInfoList;
}

export function getPumpInfo(data: any): IPumpInfo[] {
  const pumpInfoList: IPumpInfo[] = [];
  const pumps = data.Pumps;
  pumps?.forEach((element: any) => {
    const pumpInfo = pumpStitching(element);
    pumpInfoList.push(pumpInfo);
  });
  return pumpInfoList;
}

function getDoubleFan(fans: any): IFanInfo {
  let frontFan = null;
  let rearFan = null;
  if (fans[0].Name.indexOf('Front') > -1) {
    frontFan = fans[0];
    rearFan = fans[1];
  } else {
    frontFan = fans[1];
    rearFan = fans[0];
  }
  const id = frontFan.FanId;
  const fanName = `${traduction('FAN_NAME')}${frontFan.FanId} ${traduction('FAN_LOCATION_NAME')}`;
  const frontReading = frontFan.Speed === null ? '--' : frontFan.Speed;
  const rearReading = rearFan.Speed === null ? '--' : rearFan.Speed;
  const reading = `${frontReading}/${rearReading}`;
  let frontRatio = '--';
  if (frontFan.SpeedRatio !== null) {
    frontRatio = frontFan.SpeedRatio > 100 ? 100 : frontFan.SpeedRatio;
  }
  let rearRatio = '--';
  if (rearFan.SpeedRatio !== null) {
    rearRatio = rearFan.SpeedRatio > 100 ? 100 : rearFan.SpeedRatio;
  }
  const speedRatio = `${frontRatio}/${rearRatio}`;
  const presence = frontFan?.Presence === 0 ? traduction('POWER_NOT_DETECTED') : '';
  if (presence === '') {
    return {
      id,
      fanName,
      fanModel: (frontFan.Model !== '' && frontFan.Model !== null) ? frontFan.Model : '--',
      fanSpeed: reading,
      fanRate: speedRatio,
      fanPartNumber: (frontFan.PartNumber !== '' && frontFan.PartNumber !== null) ? frontFan.PartNumber : '--',
      fanDutyCycle: frontFan.DutyCycle !== null && frontFan.DutyCycle !== undefined ? frontFan.DutyCycle : '--',
      presence,
    };
  } else {
    return {
      id,
      fanName,
      fanModel: '--',
      fanSpeed: '--',
      fanRate: '--',
      fanPartNumber: '--',
      fanDutyCycle: '--',
      presence,
    };
  }
}

export function fanStitching(fans: any): IFanInfo {
  let fanInfo: IFanInfo = null as any;
  // 双风扇处理
  if (fans.length === 2) {
    fanInfo = getDoubleFan(fans);
  } else {
    const fan = fans[0];
    const name = traduction('FAN_NAME') + fan.FanId;
    const speedRatio = fan.SpeedRatio > 100 ? 100 : fan.SpeedRatio;
    const presence = fan?.Presence === 0 ? traduction('POWER_NOT_DETECTED') : '';
    if (presence === '') {
      fanInfo = {
        id: fan.FanId,
        fanName: name,
        fanModel: (fan.Model !== '' && fan.Model !== null) ? fan.Model : '--',
        fanSpeed: fan.Speed !== null ? fan.Speed : '--',
        fanRate: speedRatio !== null ? speedRatio : '--',
        fanPartNumber: (fan.PartNumber !== '' && fan.PartNumber !== null) ? fan.PartNumber : '--',
        fanDutyCycle: fan.DutyCycle !== null && fan.DutyCycle !== undefined ? fan.DutyCycle : '--',
        presence,
      };
    } else {
      fanInfo = {
        id: fan.FanId,
        fanName: name,
        fanModel: presence === '' ? fan.Model : '--',
        fanSpeed: presence === '' ? fan.Speed : '--',
        fanRate: presence === '' ? speedRatio : '--',
        fanPartNumber: presence === '' ? fan.PartNumber : '--',
        fanDutyCycle: presence === '' ? fan.DutyCycle : '--',
        presence,
      };
    }
  }
  return fanInfo;
}

export function pumpStitching(pumps: any): IPumpInfo {
  let pumpInfo: IPumpInfo = null as any;
  const name = traduction('PUMP_NAME') + pumps.Name.substr(4, 1);
  const speedPercent = pumps.SpeedPercent > 100 ? 100 : pumps.SpeedPercent;
  const presence = pumps?.Presence === 0 ? traduction('POWER_NOT_DETECTED') : '';
  pumpInfo = {
    id: pumps.Name,
    pumpName: name,
    pumpSpeedRPM: presence === '' ? pumps.SpeedRPM : '--',
    pumpSpeedPercent: presence === '' ? speedPercent : '--',
    pumpPartNumber: presence === '' ? pumps.PartNumber : '--',
    presence,
  };
  return pumpInfo;
}

export function getIntelSpeedAdjustInfo(data: any): IIntelSpeedAdjust {
  const thermalInfo = data?.SmartCooling;
  const customConfig = thermalInfo?.CustomConfig;
  let intelSpeedAdjust: any = { fanSpeedCustom: false };
  if (customConfig) {
    intelSpeedAdjust = {
      fanSmartCoolingMode: thermalInfo.Mode,
      fanSmartCoolingModeText: intelligentInit(thermalInfo.Mode),
      coolingMedium: thermalInfo.CoolingMedium,
      cpuTargetTemperatureCelsius: customConfig.CPUTargetTemperatureCelsius,
      minCPUTargetTemperatureCelsius: customConfig.MinCPUTargetTemperatureCelsius,
      maxCPUTargetTemperatureCelsius: customConfig.MaxCPUTargetTemperatureCelsius,
      npuHbmTargetTemperatureCelsius: customConfig.NPUHbmTargetTemperatureCelsius,
      minHdmTargetTemperatureCelsius: customConfig.NPUHbmMinTargetTemperatureCelsius,
      maxHdmTargetTemperatureCelsius: customConfig.NPUHbmMaxTargetTemperatureCelsius,
      npuAiCoreTargetTemperatureCelsius: customConfig.NPUAiCoreTargetTemperatureCelsius,
      minAiTargetTemperatureCelsius: customConfig.NPUAiCoreMinTargetTemperatureCelsius,
      maxAiTargetTemperatureCelsius: customConfig.NPUAiCoreMaxTargetTemperatureCelsius,
      outletTargetTemperatureCelsius: customConfig.OutletTargetTemperatureCelsius,
      minOutletTargetTemperatureCelsius: customConfig.MinOutletTargetTemperatureCelsius,
      maxOutletTargetTemperatureCelsius: customConfig.MaxOutletTargetTemperatureCelsius,
      temperatureRangeCelsius: customConfig.TemperatureRangeCelsius || [],
      minTemperatureRangeCelsius: customConfig.MinTemperatureRangeCelsius,
      maxTemperatureRangeCelsius: customConfig.MaxTemperatureRangeCelsius,
      fanSpeedPercents: customConfig.FanSpeedPercents || [],
      minFanSpeedPercents: customConfig.MinFanSpeedPercents,
      maxFanSpeedPercents: customConfig.MaxFanSpeedPercents,
      fanSpeedCustom: true,
      modelPredictiveControlEnabled: data.ModelPredictiveControlEnabled || false,
      fanSpeedDeviationThresholdPercent: data.FanSpeedDeviationThresholdPercent || 10,
    };
  }
  return intelSpeedAdjust;
}

export function intelligentInit(fanSmartCoolingMode: string) {
  let fanSmartCoolingModeText = '';
  if (fanSmartCoolingMode === 'EnergySaving') {
    fanSmartCoolingModeText = traduction('FAN_MODEL_TITLE1');
  } else if (fanSmartCoolingMode === 'LowNoise') {
    fanSmartCoolingModeText = traduction('FAN_MODEL_TITLE2');
  } else if (fanSmartCoolingMode === 'HighPerformance') {
    fanSmartCoolingModeText = traduction('FAN_MODEL_TITLE3');
  } else if (fanSmartCoolingMode === 'LiquidCooling') {
    fanSmartCoolingModeText = traduction('FAN_LIQUID_COOLING');
  } else if (fanSmartCoolingMode === 'Custom') {
    fanSmartCoolingModeText = traduction('FAN_MODEL_TITLE4');
  } else {
    fanSmartCoolingModeText = traduction('FAN_MODEL_NONE');
  }
  return fanSmartCoolingModeText;
}

export function initializingIntelSpeedAdjustInfo(intelSpeedAdjustInfo: any): IIntelSpeedAdjust {
  if (intelSpeedAdjustInfo) {
    return {
      fanSmartCoolingModeText: intelSpeedAdjustInfo.fanSmartCoolingModeText,
      fanSpeedCustom: true,
      cpuTargetTemperatureCelsius: intelSpeedAdjustInfo.cpuTargetTemperatureCelsius,
      npuHbmTargetTemperatureCelsius: intelSpeedAdjustInfo.npuHbmTargetTemperatureCelsius,
      npuAiCoreTargetTemperatureCelsius: intelSpeedAdjustInfo.npuAiCoreTargetTemperatureCelsius,
      outletTargetTemperatureCelsius: intelSpeedAdjustInfo.outletTargetTemperatureCelsius,
      temperatureRangeCelsius: intelSpeedAdjustInfo.temperatureRangeCelsius,
      fanSpeedPercents: intelSpeedAdjustInfo.fanSpeedPercents,
      fanSmartCoolingMode: intelSpeedAdjustInfo.fanSmartCoolingMode,
      coolingMedium: intelSpeedAdjustInfo.coolingMedium,
      minCPUTargetTemperatureCelsius: intelSpeedAdjustInfo.minCPUTargetTemperatureCelsius,
      maxCPUTargetTemperatureCelsius: intelSpeedAdjustInfo.maxCPUTargetTemperatureCelsius,
      minHdmTargetTemperatureCelsius: intelSpeedAdjustInfo.minHdmTargetTemperatureCelsius,
      maxHdmTargetTemperatureCelsius: intelSpeedAdjustInfo.maxHdmTargetTemperatureCelsius,
      minAiTargetTemperatureCelsius: intelSpeedAdjustInfo.minAiTargetTemperatureCelsius,
      maxAiTargetTemperatureCelsius: intelSpeedAdjustInfo.maxAiTargetTemperatureCelsius,
      minOutletTargetTemperatureCelsius: intelSpeedAdjustInfo.minOutletTargetTemperatureCelsius,
      maxOutletTargetTemperatureCelsius: intelSpeedAdjustInfo.maxOutletTargetTemperatureCelsius,
      minTemperatureRangeCelsius: intelSpeedAdjustInfo.minTemperatureRangeCelsius,
      maxTemperatureRangeCelsius: intelSpeedAdjustInfo.maxTemperatureRangeCelsius,
      minFanSpeedPercents: intelSpeedAdjustInfo.minFanSpeedPercents,
      maxFanSpeedPercents: intelSpeedAdjustInfo.maxFanSpeedPercents,
      modelPredictiveControlEnabled: intelSpeedAdjustInfo.modelPredictiveControlEnabled,
    };
  }
  return null as any;
}

export function getFanOption(currentValue: string | number): any {
  chartOption.title[0].text = `{title|${traduction(
    'FAN_CURRENT_VAL',
  )}}\n{unit|˚C}{value|${currentValue}}`;
  chartOption.title[0].textStyle.rich.value.padding =
    currentValuePadding[getStoreData('loct', 'locale')];
  chartOption.title[0].textStyle.rich.title.color = getRealColor('--o-text-color-secondary');
  chartOption.title[0].textStyle.rich.unit.color = getRealColor('--o-text-color-secondary');
  chartOption.title[0].textStyle.rich.value.color = getRealColor('--o-text-color-primary');
  chartOption.yAxis.nameTextStyle.color = getRealColor('--o-text-color-secondary');
  chartOption.yAxis.axisLabel.textStyle.color = getRealColor('--o-text-color-tertiary');
  chartOption.yAxis.splitLine.lineStyle.color = getRealColor('--o-border-color-base');
  chartOption.xAxis.axisLabel.color = getRealColor('--o-text-color-tertiary');
  chartOption.xAxis.axisLine.lineStyle.color = getRealColor('--o-border-color-base');
  chartOption.tooltip.backgroundColor =
    getThemeMode() === 'light' ? 'rgba(255,255,255,0.85)' : 'rgba(0, 0, 0, 0.85)';
  chartOption.tooltip.borderColor = chartOption.tooltip.backgroundColor;
  return chartOption;
}
