<script lang="ts" setup>
import { computed, onMounted, reactive, ref, toRaw } from 'vue';
import { getCPUData, saveCPUState } from '@/services/system/bios-service';
import { getStoreData, loading, setStoreData } from '@/utils/composition';
import { traduction } from '@/utils/language';
import CustomAert from '@/components/CustAlert/CustAlert.vue';
import HelpIcon from '@/components/HelpIcon/HelpIcon.vue';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';

const disabled = ref(true);
const isLocked = computed(() => {
  return getStoreData('glob', 'systemLocked');
});
const hasPowerControlPrivil = checkPrivil(UserPrivil.powerControl);
// alertInfo 信息
const alertInfo = traduction('BIOS_CPU_TIP1') + traduction('BIOS_CPU_TIP2');
const controlTip1 = traduction('BIOS_CONTROL_METHOD_TIP1');
const controlTip2 = traduction('BIOS_CONTROL_METHOD_TIP2');
const controlTip3 = traduction('BIOS_CONTROL_METHOD_TIP3');
const controlTip = `${controlTip1}\n${controlTip2}\n${controlTip3}`;

// CPU工作频率与空闲工作时间Tips信息
const cpuFrequency =
  traduction('BIOS_OPERATING_FREQUENCY_TIP1') + traduction('BIOS_OPERATING_FREQUENCY_TIP2');
const cpuDutyCycle = traduction('BIOS_DUTY_CYCLE_TIP1') + traduction('BIOS_DUTY_CYCLE_TIP2');

// slider数据信息
let basePstae: any = null;
const pState = reactive({
  state: 0,
  marks: {},
  max: 0,
  step: 1,
});

let baseTstae: any = null;
const tState = reactive({
  state: 0,
  marks: {},
  max: 0,
  step: 1,
});

function createStateData(limit: number, prefix: string) {
  if (limit === null) {
    return {};
  }
  const temp = {};
  for (let i = 0; i <= limit; i++) {
    temp[i] = prefix + i;
  }
  return temp;
}

function computedState() {
  const pChange = pState.state !== JSON.parse(basePstae).state;
  const tChange = tState.state !== JSON.parse(baseTstae).state;
  if (pChange || tChange) {
    disabled.value = false;
  } else {
    disabled.value = true;
  }
  return pChange || tChange;
}

function init() {
  loading(true);
  getCPUData()
    .then((res: any) => {
      const pStateData = createStateData(res.PStateLimit, 'P');
      pState.marks = pStateData;
      pState.max = res.PStateLimit;
      pState.state = res.Pstate;
      basePstae = JSON.stringify(toRaw(pState));

      const tStateData = createStateData(res.TStatelimit, 'T');
      tState.marks = tStateData;
      tState.max = res.TStatelimit;
      tState.state = res.Tstate;
      baseTstae = JSON.stringify(toRaw(tState));
    })
    .finally(() => {
      loading(false);
    });
}

function saveCpu() {
  const isChanged = computedState();

  if (!isChanged || isLocked.value || !hasPowerControlPrivil) {
    return;
  }
  const pChange = pState.state !== JSON.parse(basePstae).state;
  const tChange = tState.state !== JSON.parse(baseTstae).state;
  const params: { [key: string]: any } = {};
  if (pChange) {
    params.Pstate = pState.state;
  }
  if (tChange) {
    params.Tstate = tState.state;
  }

  loading(true);
  disabled.value = true;
  saveCPUState(params)
    .then(
      () => {
        setStoreData('event', 'alertMessage', {
          type: 'success',
          message: traduction('COMMON_SUCCESS'),
        });
        basePstae = JSON.stringify(toRaw(pState));
        baseTstae = JSON.stringify(toRaw(tState));
      },
      () => {
        disabled.value = false;
      },
    )
    .finally(() => {
      loading(false);
    });
}

function formatPTip(value: number) {
  return 'P' + value;
}
function formatTTip(value: number) {
  return 'T' + value;
}

onMounted(() => {
  init();
});
</script>
<template>
  <div class="right-container">
    <div class="cpu-alert-container">
      <CustomAert :title="$t('BIOS_CPU_TITLE')" :content="alertInfo" />
    </div>
    <div class="cpu-alert-container">
      <CustomAert
        :title="$t('BIOS_CONTROL_METHOD_LABEL')"
        :content="controlTip"
        :show-drop="true"
      />
    </div>
    <!-- PState -->
    <div class="slider-item">
      <h3>
        {{ $t('BIOS_OPERATING_FREQUENCY_LABEL') }}
        <HelpIcon :id="'operatingFrequencyId'" class="help-icon-cpu" :tips="cpuFrequency" />
      </h3>
      <div id="frequencySliderId" class="slider">
        <el-slider
          id="frequencyId"
          v-model="pState.state"
          :max="pState.max"
          :marks="pState.marks"
          :step="pState.step"
          :disabled="isLocked || !hasPowerControlPrivil || pState.state === null"
          :format-tooltip="formatPTip"
          @change="computedState"
        ></el-slider>
      </div>
    </div>
    <!-- TState -->
    <div class="slider-item">
      <h3>
        {{ $t('BIOS_DUTY_CYCLE_LABEL') }}
        <HelpIcon
          :id="'workingHoursId'"
          :append-to-body="false"
          class="help-icon-cpu"
          :tips="cpuDutyCycle"
        />
      </h3>
      <div id="freeTimeSliderId" class="slider">
        <el-slider
          id="freeTimeSlider"
          v-model="tState.state"
          :max="tState.max"
          :marks="tState.marks"
          :step="tState.step"
          :disabled="isLocked || !hasPowerControlPrivil || tState.state === null"
          :format-tooltip="formatTTip"
          @change="computedState"
        ></el-slider>
      </div>
    </div>
    <!-- 保存 -->
    <div class="save">
      <el-button
        id="cupSaveId"
        v-privil.powerConfig
        type="primary"
        :disabled="disabled || isLocked"
        @click="saveCpu"
      >
        {{ $t('COMMON_SAVE') }}
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.cpu-alert-container {
  margin-bottom: 8px;
}

.cpu-alert-container:nth-child(2) {
  margin-bottom: 16px;
}

h3 {
  font-size: $FONT-16;
  margin-bottom: 16px;
  .help-icon-cpu {
    margin-left: 3px;
    margin-top: -2px;

    :deep(.el-popper) {
      max-width: 382px;
    }
  }
}
.slider-item {
  margin-bottom: 50px;
  :deep(.el-slider__stop) {
    display: none;
  }

  .slider {
    width: calc(100% - 16px);
    margin-left: 8px;
  }
}

.right-container {
  padding: 16px 24px 24px 24px;
}
</style>
