<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue';
import InfoCard from '../infocard/InfoCard.vue';
import { IInfoCard, IPowerSetting, IPSUList } from '@/model/System/power-interface';
import { deepClone } from '@/utils/utils';
import { getpowerSupply, setPowerSupply } from '../../services/power.services';
import HelpIcon from '@/components/HelpIcon/HelpIcon.vue';
import { traduction } from '@/utils/language';
import { showElMessage } from '@/utils/utils';
import { loading } from '@/utils/composition';
import useStore from '@/stores';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';

// 系统锁定
const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const isPrivileges = checkPrivil(UserPrivil.powerControl);
const saveBtnState = ref(false);
let infoList: IInfoCard[] = reactive([]);
let dialogFormVisible = ref(false);
const powerSetting: IPowerSetting = reactive({
  workingMode: null,
  activePSU: [],
  deepSleep: '',
  normalAndRedundancy: null,
});
let oldData = reactive({});
let isActiveAndStandby = '';
let deepSleep = ref(false);
let workingModeDisabled = ref(true);
const activePSUList = ref([]);
const activePSU = ref('');
let configParam: Object | null = {};
const isPowerSetting = ref(true);
const pageLoaded = ref(false);
const deepSleepSupported = ref(true);
const activeStandbySupported = ref(true);
// 初始化
function init() {
  loading(true);
  infoList.splice(0);
  powerSetting.activePSU = [];
  activePSUList.value = [];
  activePSU.value = '';
  getpowerSupply()
    .then(res => {
      loading(false);
      powerSetting.workingMode = res.data.PowerMode;
      powerSetting.deepSleep = res.data.DeepSleep;
      powerSetting.normalAndRedundancy = res.data.NormalAndRedundancy === 'Enabled';
      res?.data?.ExpectedSupplyList?.forEach((item: any, index: number) => {
        let obj: IPSUList = reactive({
          name: item.Name,
          mode: item.Mode,
        });
        powerSetting.activePSU.push(obj);
      });
      res?.data?.SupplyList?.forEach((item: any) => {
        const obj = deepClone(item);
        infoList.push(obj);
      });
      isActiveAndStandby = powerSetting.workingMode as string;
      deepSleepSupported.value = res.data.DeepSleepSupported;
      activeStandbySupported.value = res.data.ActiveStandbySupported;
      if (powerSetting.workingMode && powerSetting.deepSleep === null) {
        isPowerSetting.value = false;
      }
      if (res.data.ActiveStandbySupported === false) {
        isPowerSetting.value = false;
      }
      pageLoaded.value =true;
    })
    .then(() => {
      loading(false);
      pageLoaded.value =true;
      initDialog();
      Object.assign(oldData, deepClone(powerSetting));
      computedState();
    });
}

// 切换工作模式
function workingModeChange(val: any) {
  if (val === 'Active/Standby') {
    workingModeDisabled.value = false;
  } else if (val === 'Sharing') {
    workingModeDisabled.value = true;
    activePSUList.value = [];
    activePSU.value = '';
  }
  computedState();
}
function activePowerChange(val: any) {
  if (powerSetting.activePSU.length === 2) {
    powerSetting.activePSU.forEach(item => {
      if (activePSU.value === item.name) {
        item.mode = 'Active';
      } else {
        item.mode = 'Standby';
      }
    });
  } else {
    powerSetting.activePSU.forEach(item => {
      if (activePSUList.value.indexOf(item.name as never) !== -1) {
        item.mode = 'Active';
      } else {
        item.mode = 'Standby';
      }
    });
  }
  computedState();
}
function deepDormancyChange(val: boolean) {
  if (val) {
    powerSetting.deepSleep = 'On';
  } else {
    powerSetting.deepSleep = 'Off';
  }
  computedState();
}
// 设置
function powerConfig() {
  if (configParam === 1) {
    showElMessage('error', traduction('POWER_NO_STAND'));
  } else if (configParam === 2) {
    showElMessage('error', traduction('POWER_SELECT_MAIN'));
  } else {
    loading(true);
    setPowerSupply(configParam)
      .then(res => {
        loading(false);
        dialogFormVisible.value = false;
        if (res.data.error) {
          const msg = traduction(res.data.error[0].code + '.errorMessage');
          showElMessage('error', msg);
        } else {
          showElMessage('success', traduction('COMMON_SUCCESS'));
        }
        init();
      })
      .catch(error => {
        loading(false);
        dialogFormVisible.value = false;
        showElMessage('error', traduction('COMMON_FAILED'));
        init();
      });
  }
}

// 提交
const onSubmit = () => {
  powerConfig();
};

function closeDialog() {
  dialogFormVisible.value = false;
  Object.assign(powerSetting, deepClone(oldData));
  initDialog();
  computedState();
}

function initDialog() {
  activePSUList.value = [];
  activePSU.value = '';
  powerSetting.activePSU.forEach((item: any, index: number) => {
    if (item.mode === 'Active') {
      (activePSUList.value as any).push(item.name);
      activePSU.value = item.name;
    }
  });
  if (powerSetting.workingMode === 'Active/Standby') {
    workingModeDisabled.value = false;
  } else {
    workingModeDisabled.value = true;
  }
  deepSleep.value = powerSetting.deepSleep === 'On' ? true : false;
}

// 保存按钮的状态
function computedState() {
  getParam();
  if (JSON.stringify(oldData) !== JSON.stringify(powerSetting)) {
    saveBtnState.value = true;
  } else {
    saveBtnState.value = false;
  }
}
function getParam() {
  const param = {};
  let isStandby = 0;
  let deepDormancy = '';
  const supplyList: { Name: string; Mode: string | null }[] = [];
  if (powerSetting.workingMode !== isActiveAndStandby) {
    param['PowerMode'] = powerSetting.workingMode;
  }
  if (powerSetting.workingMode === 'Active/Standby') {
    let isActive = true;
    isStandby = 1;
    powerSetting.activePSU.forEach(item => {
      if (item.mode === 'Active') {
        supplyList.push({
          Name: item.name,
          Mode: 'Active',
        });
        isActive = false;
      } else {
        supplyList.push({
          Name: item.name,
          Mode: 'Standby',
        });
        isStandby = 0;
      }
    });
    if (isActive) {
      isStandby = 2;
    }
    param['SupplyList'] = supplyList;
  }
  if (
    (oldData['deepSleep'] === 'Off' && deepSleep.value) ||
    (oldData['deepSleep'] === 'On' && !deepSleep.value)
  ) {
    deepDormancy = deepSleep.value ? 'On' : 'Off';
    param['DeepSleep'] = deepDormancy;
  }
  if (JSON.stringify(param) !== '{}' && !isStandby) {
    configParam = param;
  } else {
    configParam = null;
    if (JSON.stringify(param) !== '{}') {
      if (isStandby === 1 || isStandby === 2) {
        configParam = isStandby;
      }
    }
  }
  return configParam;
}

onMounted(() => {
  init();
});
</script>

<template>
  <div v-if="pageLoaded" class="page-box">
    <div v-privil.base.powerControl class="power-setting">
      <el-button
        v-if="isPrivileges && isPowerSetting"
        id="powerSetting"
        class="power-setting-btn"
        :disabled="isSystemLock"
        @click="dialogFormVisible = true"
      >
        {{ $t('POWER_SETTING') }}
      </el-button>
      <!-- 电源设置 -->
      <div v-if="dialogFormVisible" v-reqKeepAlive.dialog>
        <el-dialog
          v-model="dialogFormVisible"
          :close-on-click-modal="false"
          width="auto"
          top="412px"
          @close="closeDialog"
        >
          <template #title>
            <span class="el-dialog__title">{{ $t('POWER_SETTING') }}</span>
            <HelpIcon
              :append-to-body="true"
              class="help-icon"
              pop-class="help-tip"
              placement="top"
              :tips="$t('POWER_SETTING_TIPS')"
            ></HelpIcon>
          </template>
          <el-form label-width="auto" label-position="left" :model="powerSetting">
            <!-- 工作模式 -->
            <el-form-item class="work-mode" :label="$t('POWER_WORKING_MODE')">
              <el-radio-group
                v-model="powerSetting.workingMode"
                :disabled="powerSetting.normalAndRedundancy"
                @change="workingModeChange"
              >
                <el-radio v-addId.radio="'sharing'" label="Sharing">
                  {{ $t('POWER_LOAD_BALANCING') }}
                </el-radio>
                <el-radio v-addId.radio="'failover'" label="Active/Standby">
                  {{ $t('POWER_MAIN_STANDBY') }}
                </el-radio>
              </el-radio-group>
              <HelpIcon
                :append-to-body="true"
                class="help-icon"
                pop-class="help-tip"
                placement="top"
                :tips="$t('POWER_WORKING_MODE_TIP')"
              ></HelpIcon>
            </el-form-item>
            <!-- 主用电源 -->
            <el-form-item v-if="activeStandbySupported" :label="$t('POWER_MAIN')">
              <el-radio-group
                v-if="powerSetting.activePSU.length === 2"
                v-model="activePSU"
                :disabled="workingModeDisabled || powerSetting.normalAndRedundancy"
                @change="activePowerChange"
              >
                <el-radio
                  v-for="(item, index) in powerSetting.activePSU"
                  :key="item.name"
                  v-addId.radio="'power' + index"
                  :label="item.name">
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
              <el-checkbox-group
                v-else
                v-model="activePSUList"
                :disabled="workingModeDisabled || powerSetting.normalAndRedundancy"
                @change="activePowerChange"
              >
                <el-checkbox
                  v-for="(item, index) in powerSetting.activePSU"
                  :key="item.name"
                  v-addId.checkbox="'power' + index"
                  :label="item.name"
                />
              </el-checkbox-group>
            </el-form-item>
            <!-- 深度休眠 -->
            <el-form-item v-if="deepSleepSupported" class="deep-sleep">
              <template #label>
                <span>{{ $t('POWER_DEEP_DORMANCY') }}</span>
                <HelpIcon
                  class="help-icon"
                  placement="top"
                  :tips="$t('POWER_OS_SHUTDOWN')"
                ></HelpIcon>
              </template>
              <el-switch id="powerSwitch" v-model="deepSleep" @change="deepDormancyChange" />
            </el-form-item>
            <!-- 设置按钮 -->
          </el-form>
          <template #footer>
            <el-button
              id="powerSetSave"
              :disabled="!saveBtnState"
              size="small"
              type="primary"
              @click="onSubmit"
            >
              {{ $t('COMMON_SAVE') }}
            </el-button>
            <el-button id="powerSetCancel" size="small" @click="closeDialog()">
              {{ $t('COMMON_CANCEL') }}
            </el-button>
          </template>
        </el-dialog>
      </div>
    </div>
    <div class="info-list">
      <!-- 电源信息列表 -->
      <InfoCard v-for="item in infoList" :key="item.id" :data="item" :support="activeStandbySupported"></InfoCard>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page-box {
  .power-setting-btn {
    margin-top: 16px;
  }
  .power-setting {
    :deep(.el-dialog) {
      min-width: 432px;
      .el-form-item {
        height: 16px;

        .el-form-item__label {
          padding: 0 24px 0 0;
          height: 16px;
        }
      }
      .el-form-item__label {
        padding-top: 0;
        padding-bottom: 0;
        display: flex;
        align-items: center;
      }

      .el-radio,
      .el-checkbox {
        height: auto;
      }
    }
  }
  .info-list {
    display: flex;
    flex-wrap: wrap;
    
    .card-box{
      margin-top: 16px;
      margin-right: 16px;
    }
  }
  :deep(.el-form-item) {
    &:nth-last-child(1) {
      margin-bottom: 0;
    }
  }
  .help-icon {
    display: inline-block;
    margin: 0 4px;
  }
}
</style>
<style>
.help-tip {
  max-width: 381px;
}
</style>
