<script setup lang="ts">
import { ref, reactive, toRefs, onUnmounted, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import type { PropType } from 'vue';
import { ISpeedAdjustmentMode } from '../model/fan.datatype';
import { IIntelSpeedAdjust } from '../model/fan.datatype';
import { IconCheckBold } from '@computing/opendesign-icons';
import { AlarmAlert } from '@/components/AlarmAlert';
import CustomAdjustSpeed from './CustomAdjustSpeed.vue';

const i18n = useI18n();
const emit = defineEmits(['dialogClose']);
const props = defineProps({
  visible: Boolean,
  mpcShow: Boolean,
  data: {
    type: Object as PropType<IIntelSpeedAdjust>,
    required: true,
    default: () => {
      return {};
    },
  },
});
const { visible, data } = toRefs(props);
const dialogVisible = ref(visible.value);
const showCustom = ref(false);
const intelSpeedAdjust = reactive(data);
const oldSelectedMode = ref();
const selectedMode = ref();
const oldModelPredictiveControlEnabled = ref(false);
const modelPredictiveControlEnabled = ref(false);
let postParam: any = {};
const saveBtnDisable = ref(true);
let hasError = false;
let newCustomParam = {};
const enum MODE_INDEX {
  energySaving = 0,
  lowNoise = 1,
  highPerformance = 2,
  liquidCooling = 3,
  custom = 4
}
const speedMode = ref([
  {
    id: 'EnergySaving',
    label: i18n.t('FAN_MODEL_TITLE1'),
    content: i18n.t('FAN_MODEL_CONTENT1'),
    isSelect: false,
    isShow: true,
  },
  {
    id: 'LowNoise',
    label: i18n.t('FAN_MODEL_TITLE2'),
    content: i18n.t('FAN_MODEL_CONTENT2'),
    isSelect: false,
    isShow: true,
  },
  {
    id: 'HighPerformance',
    label: i18n.t('FAN_MODEL_TITLE3'),
    content: i18n.t('FAN_MODEL_CONTENT3'),
    isSelect: false,
    isShow: true,
  },
  {
    id: 'LiquidCooling',
    label: i18n.t('FAN_LIQUID_COOLING'),
    content: i18n.t('FAN_LIQUID_COOLING_CONTENT'),
    isSelect: false,
    isShow: true,
  },
  {
    id: 'Custom',
    label: i18n.t('FAN_MODEL_TITLE4'),
    content: i18n.t('FAN_MODEL_CONTENT4'),
    isSelect: false,
    isShow: true,
    tip: i18n.t('FAN_HEAT_MODE_WARNING'),
  },
] as ISpeedAdjustmentMode[]);

function handleDialogClose(item: any) {
  // 关闭弹窗
  dialogVisible.value = false;
  if (item === 'intelSpeedSave') {
    emit('dialogClose', postParam);
  }
  // 业务处理
  emit('dialogClose');
}

// 选择智能调速模式
function selected(mode: ISpeedAdjustmentMode) {
  speedMode.value.forEach(element => {
    element.isSelect = false;
  });
  mode.isSelect = true;

  if (mode.id === 'Custom') {
    mointorBtn(mode.id, newCustomParam);
  } else {
    mointorBtn(mode.id, {});
  }
}

function mointorBtn(selectId: string, customParam: any) {
  selectedMode.value = selectId;
  if (selectId === 'Custom' && customParam !== newCustomParam) {
    newCustomParam = customParam;
  }
  const param = getParam(selectId, newCustomParam);
  if (param === null || param === undefined) {
    saveBtnDisable.value = true;
  } else {
    postParam = param;
    if (hasError && selectId === 'Custom') {
      saveBtnDisable.value = true;
    } else {
      saveBtnDisable.value = false;
    }
  }
}

// 获取设置的数据
function getParam(selectId: string, customParam: any) {
  let param: any = {
    SmartCooling: {},
  };
  if (oldModelPredictiveControlEnabled.value !== modelPredictiveControlEnabled.value) {
    param['ModelPredictiveControlEnabled'] = modelPredictiveControlEnabled.value;
  }
  if (selectId === intelSpeedAdjust.value.fanSmartCoolingMode) {
    if (selectId === 'Custom') {
      if (JSON.stringify(customParam) !== '{}') {
        param.SmartCooling['CustomConfig'] = customParam;
      }
    }
  } else {
    param.SmartCooling['Mode'] = selectId;
    if (selectId === 'Custom') {
      if (JSON.stringify(customParam) !== '{}') {
        param.SmartCooling['CustomConfig'] = customParam;
      }
    }
  }
  if (JSON.stringify(param.SmartCooling) === '{}') {
    param = null;
  }
  param = param;
  return param;
}

function getFanMode() {
  oldModelPredictiveControlEnabled.value = intelSpeedAdjust.value.modelPredictiveControlEnabled;
  modelPredictiveControlEnabled.value = intelSpeedAdjust.value.modelPredictiveControlEnabled;
  const coolingMedium = intelSpeedAdjust.value.coolingMedium;
  const fanSmartCoolingMode = intelSpeedAdjust.value.fanSmartCoolingMode;
  if (coolingMedium === 'AirCooled') {
    // 风冷模式
    speedMode.value[MODE_INDEX.liquidCooling].isShow = false;
  } else if (coolingMedium === 'LiquidCooled') {
    // 液冷模式
    speedMode.value[MODE_INDEX.energySaving].isShow = false;
    speedMode.value[MODE_INDEX.lowNoise].isShow = false;
    speedMode.value[MODE_INDEX.highPerformance].isShow = false;
  }

  switch (fanSmartCoolingMode) {
    case 'EnergySaving':
      // 节能模式
      speedMode.value[MODE_INDEX.energySaving].isSelect = true;
      selectedMode.value = speedMode.value[MODE_INDEX.energySaving].id;
      break;
    case 'LowNoise':
      // 低噪音模式
      speedMode.value[MODE_INDEX.lowNoise].isSelect = true;
      selectedMode.value = speedMode.value[MODE_INDEX.lowNoise].id;
      break;
    case 'HighPerformance':
      // 高性能模式
      speedMode.value[MODE_INDEX.highPerformance].isSelect = true;
      selectedMode.value = speedMode.value[MODE_INDEX.highPerformance].id;
      break;
    case 'LiquidCooling':
      // 液冷模式
      speedMode.value[MODE_INDEX.liquidCooling].isSelect = true;
      selectedMode.value = speedMode.value[MODE_INDEX.liquidCooling].id;
      break;
    case 'Custom':
      // 用户自定义模式
      speedMode.value[MODE_INDEX.custom].isSelect = true;
      selectedMode.value = speedMode.value[MODE_INDEX.custom].id;
      break;
    default:
      break;
  }
  oldSelectedMode.value = selectedMode.value;
}

// 选择自定义模式回调函数
function selectCustom(result: boolean, param: any) {
  selectedMode.value = 'Custom';
  hasError = !result;
  if (result) {
    mointorBtn('Custom', param);
  } else {
    saveBtnDisable.value = true;
  }
}

function selectEnergy(): void {
  if (selectedMode.value === 'Custom') {
    return;
  }
  nextTick(() => {
    if (postParam) {
      postParam['ModelPredictiveControlEnabled'] = modelPredictiveControlEnabled.value;
    } else {
      postParam = {
        ModelPredictiveControlEnabled: modelPredictiveControlEnabled.value,
      };
    }

    if (selectedMode.value !== 'Custom') {
      saveBtnDisable.value = false;
      return;
    }

    if (!hasError) {
      const isChanged =
        oldModelPredictiveControlEnabled.value !== modelPredictiveControlEnabled.value;
      saveBtnDisable.value = !isChanged && selectedMode.value === oldSelectedMode.value;
    } else {
      saveBtnDisable.value = true;
    }
  });
}

function init() {
  showCustom.value = true;
  getFanMode();
}

init();

onUnmounted(() => {
  showCustom.value = false;
});
</script>

<template>
  <div v-if="dialogVisible" v-reqKeepAlive.dialog>
    <el-dialog
      v-model="dialogVisible"
      :title="$t('FAN_HEAT_NAME_DIALOG')"
      :class="'intel-speed-adjust'"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
      :width="'928px'"
    >
      <div v-if="mpcShow" class="item" style="margin-bottom: 16px">
        <div class="mpc-title">{{ $t('POWER_MPC') }}</div>
        <div class="mpc-content">
          <el-switch
            id="mpcEnable"
            v-model="modelPredictiveControlEnabled"
            :change="selectEnergy()"
          ></el-switch>
        </div>
      </div>
      <div class="item">
        <div class="mpc-title">{{ $t('POWER_SELECT_MODE') }}</div>
      </div>
      <div id="intelSpeedAdjustId">
        <div id="customTip">
          <AlarmAlert
            v-if="speedMode[MODE_INDEX.custom].isSelect"
            :content="speedMode[MODE_INDEX.custom].tip"
            :show-close="true"
          />
        </div>
        <div>
          <div id="intelSpeedAdjust" class="tab">
            <div
              v-for="(mode, index) in speedMode"
              v-show="mode.isShow"
              :id="mode.id"
              :key="index"
              class="custom-mode"
              :class="{
                isSelectedLabel: mode.isSelect,
                unselectedLabel: !mode.isSelect,
                tdBottomNone: index === 4
              }"
              @click="selected(mode)"
            >
              <div class="tdContent">
                <div class="label">{{ mode.label }}</div>
                <span v-if="index !== 4" class="content">{{ mode.content }}</span>
                <div class="imgState" :class="{ selectedImg: mode.isSelect }">
                  <el-icon :size="8">
                    <IconCheckBold v-if="mode.isSelect" />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
          <div
            class="custom-mode"
            :class="{
              customSelected: speedMode[MODE_INDEX.custom].isSelect,
              customUnselected: !speedMode[MODE_INDEX.custom].isSelect
            }"
            @click="selected(speedMode[MODE_INDEX.custom])"
          >
            <CustomAdjustSpeed v-if="showCustom" :data="intelSpeedAdjust" @select="selectCustom" />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            id="intelSpeedSave"
            class="confirmBtn"
            type="primary"
            size="small"
            :disabled="saveBtnDisable"
            @click="handleDialogClose('intelSpeedSave')"
          >
            {{ $t('COMMON_SAVE') }}
          </el-button>
          <el-button
            id="intelSpeedCancel"
            class="confirmBtn"
            size="small"
            @click="handleDialogClose"
          >
            {{ $t('COMMON_CANCEL') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.item {
  .mpc-title {
    font-size: 12px;
    color: var(--o-text-color-primary);
    letter-spacing: 0;
    line-height: 16px;
    display: inline-block;
  }
  .mpc-content {
    display: inline-block;
    margin-left: 16px;
  }
}

.intel-speed-adjust {
  .custom-mode {
    background: var(--o-bg-color-light);
    border-radius: 2px;
    margin-bottom: 12px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .isSelectedLabel {
    border: 2px solid var(--o-color-primary);
    border-radius: 2px;
    cursor: pointer;
  }
  .unselectedLabel {
    border-radius: 2px;
    cursor: pointer;
  }

  .isSelectedImg {
    border-right: 2px solid var(--o-color-primary);
    border-top: 2px solid var(--o-color-primary);
    border-bottom: 2px solid var(--o-color-primary);
    border-radius: 2px;
    cursor: pointer;
  }
  .unselectedImg {
    border-radius: 2px;
    cursor: pointer;
  }
  .tab {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0 16px;
    tr {
      height: 40px;
    }
  }
  .tdContent {
    padding-left: 16px;
    padding-top: 8px;
    padding-bottom: 8px;
  }
  .label {
    font-size: 14px;
    line-height: 20px;
    white-space: nowrap;
    font-weight: 600;
    color: var(--o-text-color-primary);
  }
  .content {
    width: 100%;
    font-size: 12px;
    color: var(--o-text-color-tertiary);
    letter-spacing: 0;
    line-height: 16px;
    margin-top: 4px;
  }
  .imgState {
    float: right;
    margin-top: -24px;
    margin-right: 4px;
    height: 12px;
    width: 12px;
  }
  .selectedImg {
    background: var(--o-color-primary);
    text-align: center;
  }
  .tdBottomNone {
    border-bottom: none !important;
  }
  .customSelected {
    width: 100%;
    border: solid var(--o-color-primary) 2px;
    margin-top: -17px;
    border-top: solid 0;
    padding: 8px 16px;
  }
  .customUnselected {
    width: 100%;
    margin-top: -17px;
    padding: 8px 16px;
  }
  .selectedImg {
    .el-icon {
      color: #ffffff;
      top: -3px;
    }
  }

  .alarm-alert .el-icon {
    top: auto !important;
  }

  #customTip {
    margin-bottom: 8px;
  }
}
</style>

<style lang="scss">
.intel-speed-adjust {
  .el-dialog__header {
    background: var(--o-bg-color-base);
    box-shadow: inset 0 -1px 0 0 var(--o-border-color-light);
    border-radius: 4px 4px 0 0;
  }

  .el-dialog__body {
    max-height: fit-content;
    padding-top: 24px;
    padding-left: 24px;
    font-size: 12px;
    color: var(--o-text-color-secondary);
    letter-spacing: 0;
    line-height: 16px;
    display: block;
  }

  .el-button {
    padding: 0 12px 0 12px;
    min-width: 64px;
    height: 24px;
    font-size: 12px;
  }

  .integration-controller {
    margin: 16px 0 24px;
  }
  .conten-title {
    font-size: 14px;
    color: var(--o-text-color-secondary);
    letter-spacing: 0;
    line-height: 20px;
  }

  .confirmBtn {
    height: 24px;
    font-size: 12px;
  }
  a,
  a:link,
  a:hover,
  a:visited,
  a:active {
    text-decoration: none;
    color: var(--o-color-primary);
  }

  .dialog-footer {
    text-align: center;
  }
}
</style>
