<script setup lang="ts">
import DropMemu from '@/components/DropMenu/DropMenu.vue';
import Dialiog from '@/components/Dialog/Dialog.vue';
import { computed, reactive, ref, watch } from 'vue';
import { traduction } from '@/utils/language';
import { setPowerState } from '@/services/header/header.service';
import { getStoreData, loading, setStoreData } from '@/utils/composition';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import { IconAlarm, IconError, IconSuccess } from '@computing/opendesign-icons';
import { showFWMessage } from '@/pages/System/Power/utils/common';

const multihost = computed(() => getStoreData('loct', 'multihost'));
const computeDomain = computed(() => getStoreData('loct', 'computeDomain'));
const globalDomainPowerState = computed(() => getStoreData('loct', 'globalDomainPowerState'));
const powerCtrlCapabilities = computed(() => getStoreData('loct', 'powerCtrlCapabilities'));

const props = defineProps({
  state: {
    type: String,
    default: ''
  },
  theme: {
    type: String,
    default: 'default'
  }
});
watch(
  () => props.state,
  (newVal: string) => {
    setOptions(newVal);
  }
);

const dialogRef = ref();
const show = ref(false);
const powerRef = ref(null);
const hasPowerPrivil = checkPrivil(UserPrivil.powerControl);
const dialogConfig = reactive({
  title: traduction('COMMON_CONFIRM'),
  content: ''
});

const emits = defineEmits(['reload']);

const powerState = computed(() => getStoreData('loct', 'powerState'));
watch(
  () => powerState.value,
  (newVal: string) => {
    setOptions(newVal);
  }
);

let currentType = '';
const powerOptions = [
  { id: 'powerStateOn', label: 'HEADER_POWER_ON', value: 'On', state: 'Off' },
  { id: 'multiPowerStateOn', label: 'HEADER_POWER_ON', value: 'On', state: 'On' },
  { id: 'powerStateShutdown', label: 'POWER_OFF', value: 'GracefulShutdown', state: 'On' },
  { id: 'powerStateOff', label: 'HEADER_POWER_FORCE_OFF', value: 'ForceOff', state: 'On' },
  {
    id: 'powerStateRestart',
    label: 'HEADER_POWER_FORCE_RESET',
    value: 'ForceRestart',
    state: 'On/Off'
  },
  {
    id: 'powerStatePowerCycle',
    label: 'POWER_SAFE_RESTART',
    value: 'PowerCycle',
    state: 'On'
  },
  {
    id: 'powerStateCycle',
    label: 'HEADER_POWER_FORECE_OFF_ON',
    value: 'ForcePowerCycle',
    state: 'On'
  }
];

let options = ref([Object.assign({}, powerOptions[0])]);

function leave() {
  show.value = false;
}

function showDrop() {
  show.value = true;
}

function hideDrop(ev: MouseEvent) {
  show.value = false;
}

// 选择下拉项
function select(ev: any) {
  getTip(ev);
  if (multihost.value) {
    if (ev.value === 'On') {
      dialogConfig.content += `<br/>${traduction('POWER_STRONG_ON_POWER_TIP')}`;
    } else if (ev.value === 'ForceRestart') {
      dialogConfig.content += `<br/>${traduction('POWER_OTHER_OFF_ALERT_TIP')}<br/>${traduction(
        'POWER_STRONG_ON_POWER_TIP'
      )}`;
    } else if (['PowerCycle', 'ForcePowerCycle'].includes(ev.value)) {
      dialogConfig.content += `<br/>${traduction('POWER_OTHER_OFF_ALERT_TIP')}<br/>${traduction(
        'POWER_STRONG_ON_POWER_TIP'
      )}`;
    } else {
      dialogConfig.content += `<br/>${traduction('POWER_OTHER_OFF_ALERT_TIP')}`;
    }
  } else {
    if (ev.value !== 'On') {
      dialogConfig.content += `<br/>${traduction('POWER_OTHER_OFF_ALERT_TIP')}`;
    }
  }
  currentType = ev.value;
  if (multihost.value && currentType === 'PowerCycle') {
    currentType = 'GracefulPowerCycle';
  }
  dialogRef.value.show();
}

function getTip(ev: any) {
  switch (ev.value) {
    // 下电
    case 'GracefulShutdown':
      if (multihost.value) {
        dialogConfig.content = traduction('COMMON_ASK_ALL_OK');
      } else {
        dialogConfig.content = traduction('COMMON_ASK_OK');
      }
      break;
    case 'ForceOff':
      if (multihost.value) {
        dialogConfig.content = traduction('MULTI_POWER_STRONG_DOWN_POWER_TIP');
      } else {
        dialogConfig.content = traduction('POWER_STRONG_DOWN_POWER_TIP');
      }
      break;
    case 'ForceRestart':
      if (multihost.value) {
        dialogConfig.content = traduction('MULTI_POWER_REST_START_TIP');
      } else {
        dialogConfig.content = traduction('POWER_REST_START_TIP');
      }
      break;
    case 'PowerCycle':
      if (multihost.value) {
        dialogConfig.content = traduction('MULTI_POWER_SAFE_LABLE_TIP');
      } else {
        dialogConfig.content = traduction('POWER_SAFE_LABLE_TIP');
      }
      break;
    case 'ForcePowerCycle':
      if (multihost.value) {
        dialogConfig.content = traduction('MULTI_POWER_OFF_POWER_ON_TIP');
      } else {
        dialogConfig.content = traduction('POWER_OFF_POWER_ON_TIP');
      }
      break;
    case 'ACCycle':
      dialogConfig.content = traduction('POWER_AC_LABLE_TIP');
      break;
    case 'Nmi':
      if (multihost.value) {
        dialogConfig.content = traduction('MULTI_POWER_NMI_LABEL_TIP');
      } else {
        dialogConfig.content = traduction('POWER_NMI_LABEL_TIP');
      }
      break;
    case 'ForceRestart_4':
      dialogConfig.content = traduction('POWER_COMPUTE_RESTART_LABEL_TIP');
      break;
    case 'GracefulShutdown_4':
      dialogConfig.content = traduction('POWER_COMPUTE_OFF_LABEL_TIP');
      break;
    case 'PowerCycle_4':
      dialogConfig.content = traduction('POWER_COMPUTE_CYCLE_LABEL_TIP');
      break;
    default:
      if (multihost.value) {
        dialogConfig.content = traduction('COMMON_ASK_ALL_OK');
      } else {
        dialogConfig.content = traduction('COMMON_ASK_OK');
      }
  }
}

// 切换上下电时的下拉菜单的选项
function setOptions(state: string) {
  let list: any = [];
  if (state === 'On') {
    if (multihost.value) {
      list = powerOptions.slice(1);
    } else {
      list = powerOptions.slice(2);
    }
  } else {
    list = powerOptions.slice(0, 1);
  }
  setComputeOptions(list, state);
  // 除了arm机型,任何时候都有
  const isArm = getStoreData('loct', 'armspt');
  if (!isArm) {
    list.push({
      id: 'powerStateNmi',
      label: 'NMI',
      value: 'Nmi',
      state: 'On/Off'
    });
  }
  options.value = list;
}

function setComputeOptions(list: any, state: any) {
  const operatorArr = ['ForceRestart', 'ForceOff', 'PowerCycle', 'ForcePowerCycle'];
  for (let i = 0; i < operatorArr.length; i++) {
    if (powerCtrlCapabilities.value && !powerCtrlCapabilities.value[operatorArr[i]]) {
      let forceRestartIndex = list.findIndex((item: any) => item.value === operatorArr[i]);
      if (forceRestartIndex > -1) {
        list.splice(forceRestartIndex, 1);
      }
    }
  }
  if (computeDomain.value) {
    if (state === 'On' || (globalDomainPowerState.value && globalDomainPowerState.value === 'On')) {
      if (!powerCtrlCapabilities.value || powerCtrlCapabilities.value.GlobalPowerOff) {
        list.push({
          id: 'powerStateComputeOff',
          label: 'HEADER_POWER_COMPUTE_OFF',
          value: 'GracefulShutdown_4',
          state: 'On'
        });
      }
      if (!powerCtrlCapabilities.value || powerCtrlCapabilities.value.GlobalRestart) {
        list.push({
          id: 'powerStateComputeReset',
          label: 'HEADER_POWER_COMPUTE_RESET',
          value: 'ForceRestart_4',
          state: 'On/Off'
        });
      }
      if (!powerCtrlCapabilities.value || powerCtrlCapabilities.value.GlobalPowerCycle) {
        list.push({
          id: 'powerStateComputePowerCycle',
          label: 'HEADER_POWER_COMPUTE_CYCLE',
          value: 'PowerCycle_4',
          state: 'On/Off'
        });
      }
    }
  }
}

// 关闭确认弹出框
function closeModal(reason: boolean) {
  if (reason) {
    loading(true);
    setPowerState({ type: currentType })
      .then(() => {
        setStoreData('event', 'alertMessage', {
          type: 'success',
          message: traduction('COMMON_SUCCESS')
        });
        setTimeout(() => {
          emits('reload');
        }, 2000);
      })
      .catch((error: any) => {
        showFWMessage(error);
      })
      .finally(() => {
        loading(false);
      });
  }
  dialogRef.value.hide();
}
</script>
<template>
  <div class="menu-container" @mouseenter="showDrop()" @mouseleave="hideDrop($event)">
    <div id="powerOperatorContainer" ref="powerRef" class="power-container">
      <i
        id="powerIcon"
        class="icon-kaiguan"
        :class="[{ active: powerState === 'On', disabled: !hasPowerPrivil }, `${theme}-power`]"
      ></i>
    </div>
    <DropMemu
      v-privil.powerConfig
      :offset-x="-15"
      :show="show"
      :options="options"
      @leave="leave()"
      @select="select($event)"
    />
  </div>
  <Dialiog ref="dialogRef" :config="dialogConfig" @close="closeModal">
    <template #default>
      <div class="content-item">
        <el-icon :size="24">
          <IconAlarm />
        </el-icon>
      </div>
      <div class="content-item text">
        <div v-html="dialogConfig.content"></div>
      </div>
    </template>
  </Dialiog>
</template>

<style lang="scss" scoped>
.menu-container {
  display: flex;
  height: 100%;
}
.power-container {
  display: flex;
  height: 100%;
  align-items: center;
  i {
    font-size: 24px;
    &.active::before {
      color: var(--o-color-success);
    }
    &.disabled {
      cursor: not-allowed;
    }
  }
}

.standard-power {
  &:before {
    color: #fffffe !important;
  }
}

.ibma-power {
  &:before {
    color: #fffffe !important;
  }
}

.beautiful-power {
  &:before {
    color: #fffffe !important;
  }
}

.content-item.text {
  margin-left: 16px;
  padding-top: 4px;
}
</style>