<script setup lang="ts">
import { ref, reactive, toRefs } from 'vue';
import { ICustomSpeed } from '../model/fan.datatype';
import { IIntelSpeedAdjust } from '../model/fan.datatype';
import { IconError } from '@computing/opendesign-icons';
import { useI18n } from 'vue-i18n';
import type { PropType } from 'vue';

const i18n = useI18n();
const props = defineProps({
  data: {
    type: Object as PropType<IIntelSpeedAdjust>,
    required: true,
    default: () => {
      return {};
    },
  },
});
const { data } = toRefs(props);
let temperatureRangeList: any = ref([]);
let intelSpeedAdjust = reactive(data);
const emit = defineEmits(['select']);

const customSpeedPercent = reactive({
  cpuSpeed: {
    id: 'validCPU',
    label: 'FAN_HEAT_CPU_TEMPERATURE',
    tipPosition: 'top',
    hasError: false,
    showTips: false,
  } as ICustomSpeed,
  hdmSpeed: {
    id: 'validHdm',
    label: 'FAN_HEAT_HBM_TEMPERATURE',
    tipPosition: 'top',
    hasError: false,
    showTips: false,
  } as ICustomSpeed,
  aiSpeed: {
    id: 'validAi',
    label: 'FAN_HEAT_AI_TEMPERATURE',
    tipPosition: 'top',
    hasError: false,
    showTips: false,
  } as ICustomSpeed,
  outletSpeed: {
    id: 'validOutlet',
    label: 'FAN_HEAT_OUT_LET_TARGET_TEMPERATURE',
    tipPosition: 'top',
    hasError: false,
    showTips: false,
  } as ICustomSpeed,
  fanSpeed: [] as ICustomSpeed[],
} as any);

// 获取进风口温度区间转速
function getTempRangeList() {
  const tabelLabel: { label: string }[] = [];
  const temperatureRangeCelsius = intelSpeedAdjust.value.temperatureRangeCelsius || [];
  temperatureRangeCelsius.forEach((element: any, index: number) => {
    if (index === 0) {
      tabelLabel.push({
        label: `T < ${element}`,
      });
    } else if (index === temperatureRangeCelsius.length - 1) {
      tabelLabel.push({
        label: `${temperatureRangeCelsius[index - 1]} ≤ T < ${element}`,
      });
      tabelLabel.push({
        label: `T ≥ ${element}`,
      });
    } else {
      tabelLabel.push({
        label: `${temperatureRangeCelsius[index - 1]} ≤ T < ${element}`,
      });
    }
  });
  temperatureRangeList.value = tabelLabel;
}

function validateAll() {
  let hasError = false;
  for (let key in customSpeedPercent) {
    if (key === 'fanSpeed') {
      for (let item of customSpeedPercent.fanSpeed) {
        if (item.value && Number(item.value) >= item.min && Number(item.value) <= item.max) {
          item.hasError = false;
          item.showTips = false;
        } else {
          item.hasError = true;
          item.showTips = true;
          hasError = true;
          emit('select', false);
          return false;
        }
      }
    } else {
      let item = customSpeedPercent[key];
      if (!item.show) {
        continue;
      }
      if (item.value && Number(item.value) >= item.min && Number(item.value) <= item.max) {
        item.hasError = false;
        item.showTips = false;
      } else {
        item.hasError = true;
        item.showTips = true;
        hasError = true;
        emit('select', false);
        return false;
      }
    }
  }
  return !hasError;
}

// 输入框数据校验
function validate(item: ICustomSpeed): boolean {
  // 先判断当前的输入框
  if (item !== null) {
    const reg = /(^[1-9][0-9]*$)|^[0]$/;
    const value = item.value.toString();
    if (!reg.test(value)) {
      item.errorTip = i18n.t('VALID_VALUE_ISNOT_VALID_DIGITS');
      item.showTips = true;
      item.hasError = true;
      emit('select', false);
      return false;
    } else if (item.value < item.min || item.value > item.max) {
      item.errorTip = i18n.t('VALID_RANGE_VALUE_ERR_MSG', [item.min, item.max]);
      item.showTips = true;
      item.hasError = true;
      emit('select', false);
      return false;
    } else {
      item.hasError = false;
      item.showTips = false;
    }
  }

  if (!validateAll()) {
    return false;
  }

  const param = getCustomModeParam();
  emit('select', true, param);

  return true;
}

function focus(item: ICustomSpeed) {
  item.showTips = true;
}

// 获取自定义模式数据
function getCustomModeParam() {
  const param = {};
  if (
    customSpeedPercent.cpuSpeed.value !== null &&
    Number(customSpeedPercent.cpuSpeed.value) !== intelSpeedAdjust.value.cpuTargetTemperatureCelsius
  ) {
    param['CPUTargetTemperatureCelsius'] = Number(customSpeedPercent.cpuSpeed.value);
  }
  if (
    customSpeedPercent.hdmSpeed.value !== null &&
    Number(customSpeedPercent.hdmSpeed.value) !==
      intelSpeedAdjust.value.npuHbmTargetTemperatureCelsius
  ) {
    param['NPUHbmTargetTemperatureCelsius'] = Number(customSpeedPercent.hdmSpeed.value);
  }
  if (
    customSpeedPercent.aiSpeed.value !== null &&
    Number(customSpeedPercent.aiSpeed.value) !==
      intelSpeedAdjust.value.npuAiCoreTargetTemperatureCelsius
  ) {
    param['NPUAiCoreTargetTemperatureCelsius'] = Number(customSpeedPercent.aiSpeed.value);
  }
  if (
    customSpeedPercent.outletSpeed.value !== null &&
    Number(customSpeedPercent.outletSpeed.value) !==
      intelSpeedAdjust.value.outletTargetTemperatureCelsius
  ) {
    param['OutletTargetTemperatureCelsius'] = Number(customSpeedPercent.outletSpeed.value);
  }

  const newVal: number[] = [];
  customSpeedPercent.fanSpeed.forEach((fanSpeed: ICustomSpeed) => {
    newVal.push(Number(fanSpeed.value));
  });

  if (newVal.toString() !== intelSpeedAdjust.value.fanSpeedPercents.toString()) {
    param['FanSpeedPercents'] = newVal;
  }
  return param;
}

init();
function init() {
  getTempRangeList();
  const minCPU = intelSpeedAdjust.value.minCPUTargetTemperatureCelsius;
  const maxCPU = intelSpeedAdjust.value.maxCPUTargetTemperatureCelsius;
  const minHbm = intelSpeedAdjust.value.minHdmTargetTemperatureCelsius;
  const maxHbm = intelSpeedAdjust.value.maxHdmTargetTemperatureCelsius;
  const minAi = intelSpeedAdjust.value.minAiTargetTemperatureCelsius;
  const maxAi = intelSpeedAdjust.value.maxAiTargetTemperatureCelsius;
  const minOutlet = intelSpeedAdjust.value.minOutletTargetTemperatureCelsius;
  const maxOutlet = intelSpeedAdjust.value.maxOutletTargetTemperatureCelsius;
  const minFan = intelSpeedAdjust.value.minFanSpeedPercents;
  const maxFan = intelSpeedAdjust.value.maxFanSpeedPercents;
  const fanSpeedPercents = intelSpeedAdjust.value.fanSpeedPercents || [];

  customSpeedPercent.cpuSpeed.min = minCPU;
  customSpeedPercent.cpuSpeed.max = maxCPU;
  customSpeedPercent.cpuSpeed.show = intelSpeedAdjust.value.cpuTargetTemperatureCelsius !== null;
  customSpeedPercent.cpuSpeed.tip = i18n.t('VALID_VALUE_RANGE_TIP', [minCPU, maxCPU]);
  customSpeedPercent.cpuSpeed.errorTip = i18n.t('VALID_RANGE_VALUE_ERR_MSG', [minCPU, maxCPU]);
  customSpeedPercent.cpuSpeed.value = intelSpeedAdjust.value.cpuTargetTemperatureCelsius;

  customSpeedPercent.hdmSpeed.min = minHbm;
  customSpeedPercent.hdmSpeed.max = maxHbm;
  customSpeedPercent.hdmSpeed.show = intelSpeedAdjust.value.npuHbmTargetTemperatureCelsius !== null;
  customSpeedPercent.hdmSpeed.tip = i18n.t('VALID_VALUE_RANGE_TIP', [minHbm, maxHbm]);
  customSpeedPercent.hdmSpeed.errorTip = i18n.t('VALID_RANGE_VALUE_ERR_MSG', [minHbm, maxHbm]);
  customSpeedPercent.hdmSpeed.value = intelSpeedAdjust.value.npuHbmTargetTemperatureCelsius;

  customSpeedPercent.aiSpeed.min = minAi;
  customSpeedPercent.aiSpeed.max = maxAi;
  customSpeedPercent.aiSpeed.show =
    intelSpeedAdjust.value.npuAiCoreTargetTemperatureCelsius !== null;
  customSpeedPercent.aiSpeed.tip = i18n.t('VALID_VALUE_RANGE_TIP', [minAi, maxAi]);
  customSpeedPercent.aiSpeed.errorTip = i18n.t('VALID_RANGE_VALUE_ERR_MSG', [minAi, maxAi]);
  customSpeedPercent.aiSpeed.value = intelSpeedAdjust.value.npuAiCoreTargetTemperatureCelsius;

  customSpeedPercent.outletSpeed.min = minOutlet;
  customSpeedPercent.outletSpeed.max = maxOutlet;
  customSpeedPercent.outletSpeed.show =
    intelSpeedAdjust.value.outletTargetTemperatureCelsius !== null;
  customSpeedPercent.outletSpeed.tip = i18n.t('VALID_VALUE_RANGE_TIP', [minOutlet, maxOutlet]);
  customSpeedPercent.outletSpeed.errorTip = i18n.t('VALID_RANGE_VALUE_ERR_MSG', [
    minOutlet,
    maxOutlet,
  ]);
  customSpeedPercent.outletSpeed.value = intelSpeedAdjust.value.outletTargetTemperatureCelsius;

  setFanSpeedArray(fanSpeedPercents, minFan, maxFan);
}

function setFanSpeedArray(fanSpeedPercents: any, minFan: any, maxFan: any) {
  fanSpeedPercents.forEach((fanSpeed: any) => {
    customSpeedPercent.fanSpeed.push({
      id: 'fanSpeedPercent',
      label: 'FAN_HEAT_TEMPERATURE_RANGE',
      tip: i18n.t('VALID_VALUE_RANGE_TIP', [minFan, maxFan]),
      errorTip: i18n.t('VALID_RANGE_VALUE_ERR_MSG', [minFan, maxFan]),
      tipPosition: 'top',
      hasError: false,
      value: fanSpeed,
      min: minFan,
      max: maxFan,
      show:
        intelSpeedAdjust.value.temperatureRangeCelsius.length > 0 &&
        intelSpeedAdjust.value.fanSpeedPercents.length > 0,
      showTips: false,
    });
  });
}
</script>
<template>
  <div id="customContent" class="custom" group="customForm">
    <table>
      <template v-for="(value, key) in customSpeedPercent" :key="key">
        <tr v-if="key + '' !== 'fanSpeed' && value.show" class="cpu-outlet-temperature">
          <td>
            <label v-t="value.label" class="model-tabel3" />
          </td>
          <td>
            <el-tooltip
              v-model:visible="value.showTips"
              class="tip"
              :placement="value.tipPosition"
              trigger="focus"
              trigger-keys
            >
              <template #content>
                <el-icon v-if="value.hasError" :size="16" class="error-icon">
                  <IconError />
                </el-icon>
                <span
                  :id="value.id + 'TipContent'"
                  v-t="value.hasError ? value.errorTip : value.tip"
                  :class="value.hasError ? 'error-text' : ''"
                />
              </template>
              <el-input
                v-model="value.value"
                v-addId.input="value.id"
                :class="value.hasError ? 'error-input' : ''"
                form-control-name="cpuTargetTemperatureCelsius"
                @input="validate(value)"
                @focus="focus(value)"
              />
            </el-tooltip>
          </td>
        </tr>
      </template>
    </table>
    <div v-if="customSpeedPercent.fanSpeed[0].show" class="range-temperature">
      <table frame="below" rules="rows">
        <tr class="one-tr">
          <td>
            <label v-t="'FAN_HEAT_TEMPERATURE_RANGE'" />
          </td>
          <td v-for="(item, i) in temperatureRangeList" :key="i">
            <el-divider direction="vertical" />
            <label :id="'temperatureRange' + i">{{ item.label }}</label>
          </td>
        </tr>
        <tr class="two-tr">
          <td class="label-td">
            <label v-t="'FAN_ROTATIONAL_SPEED'" />
          </td>
          <td v-for="(speed, i) in customSpeedPercent.fanSpeed" :key="i">
            <el-tooltip
              v-model:visible="speed.showTips"
              class="tip"
              :placement="speed.tipPosition"
              trigger="focus"
              trigger-keys
            >
              <template #content>
                <el-icon v-if="speed.hasError" :size="16" class="error-icon">
                  <IconError />
                </el-icon>
                <span
                  :id="'temperatureRangeTipContent' + i"
                  v-t="speed.hasError ? speed.errorTip : speed.tip"
                  :class="speed.hasError ? 'error-text' : ''"
                />
              </template>
              <el-input
                v-model="speed.value"
                v-addId.input="'fanSpeedPercent' + i"
                type="number"
                class="fans-class"
                :class="speed.hasError ? 'error-input' : ''"
                @input="validate(speed)"
                @focus="focus(speed)"
              />
            </el-tooltip>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<style lang="scss" scoped>
#customContent {
  .model-tabel3 {
    font-size: 12px;
    color: var(--o-text-color-tertiary);
    line-height: 16px;
    padding-right: 16px;
    white-space: nowrap;
  }
  .range-temperature {
    overflow: auto;
    margin-top: 8px;
    color: var(--o-text-color-secondary);
    table {
      width: 100%;
      border-spacing: none;
      tr {
        border-bottom-color: var(--o-border-color-light);
      }
      :deep(.el-input__wrapper) {
        height: 32px !important;
      }
    }
    td {
      label {
        white-space: pre;
      }
    }
    .one-tr td {
      padding-top: 4px;
      padding-bottom: 4px;
    }
    .label-td {
      padding-top: 8px;
      padding-bottom: 8px;
    }
  }
  .cpu-outlet-temperature {
    height: 32px;

    .el-input {
      width: 56px;
    }
  }

  table {
    border-collapse: collapse !important;
    border-spacing: 0 !important;
  }
}
.error-icon {
  top: 3px;
}

.error-text {
  margin-left: 8px;
}
.el-divider--vertical {
  margin-left: 0;
}
</style>
<style lang="scss">
.fans-class {
  width: 100%;
  height: 32px;
  .el-input__inner {
    border: none;
    box-shadow: 0 0px 0px #fff;
  }
}

.error-input {
  .el-input__inner {
    background: var(--o-color-danger-secondary);
    border-color: var(--o-form-item-border-color_error);
    box-shadow: 0 0 0 1px var(--el-color-danger) inset;
  }
  .el-input__inner:focus {
    border-color: var(--o-form-item-border-color_error);
  }
}
</style>
