<script setup lang="ts">
import { ref, reactive, onMounted, computed, shallowRef, onUnmounted, watch } from 'vue';
import { traduction } from '@/utils/language';
import { IPowerOnPolicy, IVirtualKeyInfo } from '@/model/System/power-interface';
import Dialog from '@/components/Dialog/Dialog.vue';
import HelpIcon from '@/components/HelpIcon/HelpIcon.vue';
import Editor from '@/components/Editor/Editor.vue';
import { getPowerControl, setPowerControl, setPowerOnOff } from '../../services/power.services';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import useStore from '@/stores';
import { compareObjectEqual, showElMessage } from '@/utils/utils';
import { loading, getStoreData, setStoreData } from '@/utils/composition';
import SingleLineFailurePrompt from '@/components/SingleLineFailurePrompt/SingleLineFailurePrompt.vue';
import { IconAlarm, IconError, IconSuccess } from '@computing/opendesign-icons';
import { showFWMessage } from '@/pages/System/Power/utils/common';

const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const isArm = getStoreData('loct', 'armspt');
const multihost = getStoreData('loct', 'multihost');
const computeDomain = getStoreData('loct', 'computeDomain');
const isPrivileges = checkPrivil(UserPrivil.powerControl);

const saveBtn = ref(true);

const safePowerOffTimoutSeconds = ref(0);
const switchState = ref(true);
const powerOnPolicySelected = ref(traduction('POWER_KEEP_ON'));
const powerOnDelayedSelected = ref('');
const leakageSupport = ref(false);
const targetData = reactive({
  powerState: '',
});
// 系统状态
const systemState = ref('POWER_OFF');
const powerType = ref('');

const panelPowerDialogConfig = reactive({
  title: traduction('COMMON_CONFIRM'),
  content: traduction('COMMON_ASK_OK'),
});

const panelPowerDialogRef = ref();

const oldData: any = {};
let oldSeconds: any = '';

let getStateTimer: any = null;

// 虚拟按键列表
const virtualKeyLists: Array<IVirtualKeyInfo> = reactive([
  {
    id: 'on',
    show: false,
    information: 'POWER_ON',
    className: 'power-on',
  },
  {
    id: 'off',
    show: false,
    information: 'POWER_OFF',
    className: 'power-off',
  },
  {
    id: 'forcedOff',
    show: false,
    information: 'POWER_STRONG_DOWN',
    promptMessage: 'POWER_STRONG_DOWN_TIP',
    promptId: 'forcePowerOff',
    helpTips: 'POWER_FORCED_OFF_TIP',
  },
  {
    id: 'forcedRestart',
    show: false,
    information: 'POWER_FORCED_RESTART',
    promptMessage: 'POWER_STRONG_REST_TIP',
    promptId: 'forcePowerRestart',
    helpTips: 'POWER_FORCED_RESTART_TIP',
  },
  {
    id: 'powerCycle',
    show: false,
    information: 'POWER_SAFE_RESTART',
    promptMessage: 'POWER_SAFE_RESTART_TIP',
    promptId: 'safePowerToggle',
    helpTips: 'POWER_SAFE_CYCLE_TIP',
  },
  {
    id: 'forcedCycle',
    show: false,
    information: 'HEADER_POWER_FORECE_OFF_ON',
    promptMessage: 'POWER_STRONG_OFF_ON_TIP',
    promptId: 'forcePowerToggle',
    helpTips: 'POWER_FORCED_CYCLE_TIP',
  },
  {
    id: 'computeOff',
    show: false,
    information: 'HEADER_POWER_COMPUTE_OFF',
    helpTips: 'POWER_OFF_COMPUTE_TIP',
    promptMessage: 'POWER_COMPUTE_OFF_TIP',
    promptId: 'computedPowerOff',
  },
  {
    id: 'computeReset',
    show: false,
    information: 'HEADER_POWER_COMPUTE_RESET',
    helpTips: 'POWER_RESET_COMPUTE_TIP',
    promptMessage: 'POWER_COMPUTE_RESTART_TIP',
    promptId: 'computedPowerReset',
  },
  {
    id: 'computeCycle',
    show: false,
    information: 'HEADER_POWER_COMPUTE_CYCLE',
    helpTips: 'POWER_CYCLING_COMPUTE_TIP',
    promptMessage: 'POWER_COMPUTE_CYCLE_TIP',
    promptId: 'computedPowerCycle',
  },
]);

function powerOffTimeChange(val: boolean) {
  loading(true);
  const params = {
    PowerOffAfterTimeout: {
      Enabled: val ? 'On' : 'Off',
    },
  };
  setPowerControl(params)
    .then(res => {
      powerOffChecked.value = res.data.PowerOffAfterTimeout[0].Enabled === 'On';
      showElMessage('success', traduction('COMMON_SUCCESS'));
      loading(false);
    })
    .catch(error => {
      powerOffChecked.value = error.error.data.PowerOffAfterTimeout[0].Enabled === 'On';
      showElMessage('error', traduction('COMMON_FAILED'));
      loading(false);
    });
}

const offTimeRule = {
  required: true,
  min: 10,
  max: 6000,
  isInteger: true,
  trigger: 'change',
  validator: (vRule: any, valueParams: any, callback: any): boolean => {
    const { max, min, required } = vRule;
    let value = valueParams;
    // 为空校验 与 数字校验
    if (required && !value && value !== 0) {
      offTimePopoverSetting.type = 'complex';
      offTimePopoverSetting.popoverSlotSetting.data = traduction(
        'VALIDTOR_INTER_INTGER_RANGE',
        [10, 6000],
      );
      callback(new Error());
      return false;
    }
    // 输入的要是数字字符串 或者 数字，前提是整数
    const reg = /(^[\-0-9][0-9]*)$/;
    if (!reg.test(value)) {
      offTimePopoverSetting.type = 'complex';
      offTimePopoverSetting.popoverSlotSetting.data = traduction('VALID_INTEGER_INFO');
      callback(new Error());
      return false;
    }
    if (typeof value === 'string') {
      value = Number(value);
    }
    if (value || value === 0) {
      // 最小值
      if ((min || min === 0) && value < min) {
        offTimePopoverSetting.type = 'complex';
        offTimePopoverSetting.popoverSlotSetting.data = traduction(
          'VALIDTOR_INTER_INTGER_RANGE',
          [10, 6000],
        );
        callback(new Error());
        return false;
      }
      // 最大值
      if ((max || max === 0) && value > max) {
        offTimePopoverSetting.type = 'complex';
        offTimePopoverSetting.popoverSlotSetting.data = traduction(
          'VALIDTOR_INTER_INTGER_RANGE',
          [10, 6000],
        );
        callback(new Error());
        return false;
      }
    }
    offTimePopoverSetting.type = 'ordinary';
    callback();
    return true;
  },
};

const offTimePopoverSetting = reactive({
  // 是否有
  show: true,
  // popover的类型,是简单的字符串还是比较复杂的自定义内容（自定义的需要传组件）
  type: 'ordinary', // ordinary(简单的字符串)或者complex(复杂的自定义展示组件)
  // 自定义的popover展示组件配置
  popoverSlotSetting: {
    // 展示的组件
    component: shallowRef(SingleLineFailurePrompt),
    // 传给组件的数据
    data: traduction('VALIDTOR_INTER_INTGER_RANGE', [10, 6000]),
  },
  // popover的类名
  popperClass: 'no-wrap-popover',
  // 展示内容
  content: traduction('VALID_VALUE_POWER_OFF_RANGE_TIP', [10, 6000, 600]),
  // 展示位置
  placement: 'top',
  // popover触发方式
  trigger: 'focus',
});

const delayPopoverSetting = reactive({
  show: true,
  type: 'ordinary',
  popoverSlotSetting: {
    component: shallowRef(SingleLineFailurePrompt),
    data: traduction('VALIDTOR_INTER_INTGER_RANGE', [0, 120]),
  },
  popperClass: 'no-wrap-popover',
  content: traduction('VALID_DELAY_POLICY_TIP'),
  placement: 'top',
  trigger: 'focus',
});

const delayRule = {
  required: true,
  min: 0,
  max: 120,
  isInteger: false,
  trigger: 'change',
  validator: (vRule: any, valueParams: any, callback: any) => {
    let value = valueParams;
    const { max, min, required } = vRule;
    const reg = /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/;
    // 为空校验 与 数字校验
    const condition = required && !value && value !== 0;
    if (condition || !reg.test(String(value))) {
      delayPopoverSetting.type = 'complex';
      delayPopoverSetting.popoverSlotSetting.data = traduction('VALID_NUMBER_INFO');
      callback(new Error());
      return;
    }

    if (typeof value === 'string') {
      value = Number(value);
    }
    if (value || value === 0) {
      // 最大精度0.1
      const reg0 = /^((\d+)|(\d+\.\d))$/;
      if (!reg0.test(String(value)) || Object.is(value, -0)) {
        delayPopoverSetting.type = 'complex';
        delayPopoverSetting.popoverSlotSetting.data = traduction('VALID_OUT_DECIMAL_PPOINT');
        callback(new Error());
        return;
      }
      // 最小值
      if ((min || min === 0) && value < min) {
        delayPopoverSetting.type = 'complex';
        delayPopoverSetting.popoverSlotSetting.data = traduction(
          'VALID_DELAY_POLICY_TIP',
          [0, 120],
        );
        callback(new Error());
        return;
      }
      // 最大值
      if ((max || max === 0) && value > max) {
        delayPopoverSetting.type = 'complex';
        delayPopoverSetting.popoverSlotSetting.data = traduction(
          'VALID_DELAY_POLICY_TIP',
          [0, 120],
        );
        callback(new Error());
        return;
      }
    }
    delayPopoverSetting.type = 'ordinary';
    callback();
  },
};

// 屏蔽面板电源按钮 发生修改
function panelPowerChange(val: boolean) {
  panelPowerDialogRef.value.show();
}

// 是否确认 屏蔽面板电源按钮 开关的修改
function panelPowerDialogClose(flag: boolean) {
  if (flag) {
    loading(true);
    const params = {
      PanelPowerButtonEnabled: switchState.value ? 'Off' : 'On',
    };
    setPowerControl(params)
      .then(() => {
        loading(false);
        panelPowerDialogRef.value.hide();
        showElMessage('success', traduction('COMMON_SUCCESS'));
        init();
      })
      .catch(() => {
        loading(false);
        panelPowerDialogRef.value.hide();
        switchState.value = !switchState.value;
        showElMessage('error', traduction('COMMON_FAILED'));
      });
  } else {
    switchState.value = !switchState.value;
    panelPowerDialogRef.value.hide();
  }
}

const powerOnPolicyType = {
  alwaysPowerOn: 'AlwaysPowerOn',
  alwaysPowerOff: 'AlwaysPowerOff',
  lastState: 'LastState',
};

const leakageSwitchStateDialogRef = ref();

const leakageSwitchStateDialogConfig = reactive({
  title: traduction('COMMON_CONFIRM'),
  content: traduction('COMMON_ASK_OK'),
});

const powerState = computed(() => getStoreData('loct', 'powerState'));
watch(
  () => powerState.value,
  () => {
    init(false);
  },
);

// 漏液检测卡在位时生效 开关发生修改
function leakageSwitchStateChange() {
  if (leakage.switchState) {
    leakageSwitchStateDialogConfig.content = traduction('POWER_LEAKAGE_DIALOG_TIP');
  } else {
    leakageSwitchStateDialogConfig.content = traduction('COMMON_ASK_OK');
  }
  leakageSwitchStateDialogRef.value.show();
}

// 是否确认 屏蔽面板电源按钮 开关的修改
function leakageSwitchStateDialogClose(flag: boolean) {
  if (flag) {
    loading(true);
    const params = {
      LeakStrategy: leakage.switchState ? 'AutoPowerOff' : 'ManualPowerOff',
    };
    setPowerControl(params)
      .then(() => {
        loading(false);
        leakageSwitchStateDialogRef.value.hide();
        showElMessage('success', traduction('COMMON_SUCCESS'));
        init();
      })
      .catch(() => {
        loading(false);
        leakageSwitchStateDialogRef.value.hide();
        leakage.switchState = !leakage.switchState;
        showElMessage('error', traduction('COMMON_FAILED'));
      });
  } else {
    leakage.switchState = !leakage.switchState;
    leakageSwitchStateDialogRef.value.hide();
  }
}

function dataFactory1(data: any) {
  switchState.value = data.PanelPowerButtonEnabled === 'Off' ? true : false;
  leakageSupport.value = data.LeakDetectionSupport;
  leakage.switchState = data.LeakStrategy === 'AutoPowerOff';
  const powerOffAfterTimeout = data.PowerOffAfterTimeout[0];
  if (powerOffAfterTimeout) {
    safePowerOffTimoutSeconds.value = powerOffAfterTimeout?.TimeoutSeconds;
    powerOffChecked.value = powerOffAfterTimeout?.Enabled === 'On';
    offTimeRule.min = powerOffAfterTimeout?.MinSeconds;
    offTimeRule.max = powerOffAfterTimeout?.MaxSeconds;
    let num = powerOffAfterTimeout?.DefaultSeconds;
    if (!(num || num === 0)) {
      num = 600;
    }
    offTimePopoverSetting.content = traduction('VALID_VALUE_POWER_OFF_RANGE_TIP', [
      offTimeRule.min,
      offTimeRule.max,
      num,
    ]);
  }
  const powerRestoreDelay = data?.PowerRestoreDelay;
  if (powerRestoreDelay) {
    powerOnDelayedSelected.value = powerRestoreDelay?.Mode;
    powerOnDelayed[1].editor.value = powerRestoreDelay?.Seconds;
    powerOnDelayed[2].editor.value = powerRestoreDelay?.Seconds;
    powerOnDelayed[3].editor.value = powerRestoreDelay?.Seconds;
    powerOnDelayed[1].editor.oldValue = powerRestoreDelay?.Seconds;
    powerOnDelayed[2].editor.oldValue = powerRestoreDelay?.Seconds;
    powerOnDelayed[3].editor.oldValue = powerRestoreDelay?.Seconds;
    oldSeconds = powerRestoreDelay?.Seconds;
  }
  const powerOnStrategy = data.PowerOnStrategy;
  if (powerOnStrategy === powerOnPolicyType.alwaysPowerOn) {
    powerOnPolicySelected.value = traduction('POWER_KEEP_ON');
  } else if (powerOnStrategy === powerOnPolicyType.alwaysPowerOff) {
    powerOnPolicySelected.value = traduction('POWER_KEEP_DOWN');
  } else if (powerOnStrategy === powerOnPolicyType.lastState) {
    powerOnPolicySelected.value = traduction('POWER_KEEP_CONSISTT');
  }
  oldData.powerOnPolicySelected = powerOnPolicySelected.value;
  oldData.powerOnDelayedSelected = powerOnDelayedSelected.value;
}

function dataFactory2() {
  setStoreData('loct', 'powerState', targetData.powerState);
  const status = targetData.powerState === 'On';
  const powerS = status ? 'POWER_ON' : 'POWER_OFF';
  if (powerS !== systemState.value) {
    dialogRef.value?.hide();
  }
  systemState.value = powerS;
  powerType.value = status ? 'success' : 'info';
  const offShowLists = ['on'];
  let onShowLists = ['off', 'forcedOff', 'forcedCycle', 'powerCycle', 'forcedRestart', 'acCycle'];
  if (computeDomain) {
    onShowLists = ['off', 'forcedOff', 'forcedCycle', 'powerCycle', 'forcedRestart', 'acCycle', 'computeOff', 'computeReset', 'computeCycle'];
  }
  virtualKeyLists.forEach(item => {
    item.show =
      (status && onShowLists.includes(item.id)) ||
      (targetData.powerState === 'Off' && offShowLists.includes(item.id));
  });
  virtualKeyLists.push({
    id: 'nmi',
    show: !isArm,
    className: 'nmi',
    information: 'NMI',
    helpTips: 'POWER_NMI_TIP',
  });
}

function init(needLoading?: boolean) {
  if (needLoading !== false) {
    loading(true);
  }
  getPowerControl()
    .then(res => {
      loading(false);
      targetData.powerState = res?.data?.PowerState[0].State || 'Off';
      // 定时器只修改上下电状态，不修改其他的展示项
      if (res && res.data && needLoading !== false) {
        dataFactory1(res.data);
      }
    })
    .then(() => {
      if (needLoading !== false) {
        loading(false);
      }
      dataFactory2();
    })
    .catch(() => {
      loading(false);
    });
}

const powerOffChecked = ref(false);
const dialogRef = ref();

const powerOffTimeEdit = reactive({
  editor: () => {},
  cancel: () => {},
  confirm: (val: any) => {
    loading(true);
    const param = {
      PowerOffAfterTimeout: {
        TimeoutSeconds: parseInt(val, 10),
      },
    };
    setPowerControl(param)
      .then((response: any) => {
        showElMessage('success', traduction('COMMON_SUCCESS'));
        init();
      })
      .catch((error: any) => {
        loading(false);
        showElMessage('error', traduction('COMMON_FAILED'));
        init();
      });
  },
});

// 通电开机策略
const powerOnPolicy: Array<IPowerOnPolicy> = [
  {
    id: 'TurnOn',
    label: traduction('POWER_KEEP_ON'),
    disabled: false,
  },
  {
    id: 'StayOff',
    label: traduction('POWER_KEEP_DOWN'),
    disabled: false,
  },
  {
    id: 'RestorePreviousState',
    label: traduction('POWER_KEEP_CONSISTT'),
    disabled: false,
  },
];

function powerOnPolicyChange() {
  setBtnState();
}

// 延迟上电设置
const powerOnDelayed: any = reactive([
  {
    value: 'DefaultDelay',
    label: traduction('POWER_DEFAULT_DELAY'),
    disabled: false,
    desc: traduction('POWER_DEFAULT_DELAY_INFO1'),
    editor: {
      show: false,
    },
  },
  {
    value: 'HalfDelay',
    label: traduction('POWER_HALF_DELAY'),
    disabled: false,
    desc: traduction('POWER_HALF_DELAY_INFO'),
    editor: {
      show: true,
      value: '',
      oldValue: '',
      editor: () => {
        saveBtn.value = true;
      },
      cancel: () => {
        setBtnState(1);
      },
      confirm: (val: any) => {
        powerOnDelayed[1].editor.value = val;
        if (powerOnDelayed[1].editor.oldValue !== val) {
          saveBtn.value = false;
        } else {
          setBtnState();
        }
      },
    },
    delayRule: { ...delayRule },
  },
  {
    value: 'FixedDelay',
    label: traduction('POWER_FIXED_DELAY'),
    disabled: false,
    desc: traduction('POWER_FIXED_DELAY_INFO'),
    editor: {
      show: true,
      value: '',
      oldValue: '',
      editor: () => {
        saveBtn.value = true;
      },
      cancel: () => {
        setBtnState(2);
      },
      confirm: (val: any) => {
        powerOnDelayed[2].editor.value = val;
        if (powerOnDelayed[2].editor.oldValue !== val) {
          saveBtn.value = false;
        } else {
          setBtnState();
        }
      },
    },
    delayRule: { ...delayRule },
  },
  {
    value: 'RandomDelay',
    label: traduction('POWER_RANDOM_DELAY'),
    disabled: false,
    desc: traduction('POWER_RANDOM_DELAY_INFO'),
    editor: {
      show: true,
      value: '',
      oldValue: '',
      editor: () => {
        saveBtn.value = true;
      },
      cancel: () => {
        setBtnState(3);
      },
      confirm: (val: any) => {
        powerOnDelayed[3].editor.value = val;
        if (powerOnDelayed[3].editor.oldValue !== val) {
          saveBtn.value = false;
        } else {
          setBtnState();
        }
      },
    },
    delayRule: { ...delayRule },
  },
]);

const dialogConfig = reactive({
  value: '',
  id: '',
  content: traduction('COMMON_ASK_OK'),
  title: traduction('ALARM_OK'),
});
const powerControlParam = {
  OperateType: '',
};

// 虚拟按键二次确认弹框
function virtualKeyClick(val: any) {
  switch (val) {
    case 'on':
      dialogConfig.content = traduction('COMMON_ASK_OK');
      powerControlParam.OperateType = 'On';
      dialogConfig.value = 'On';
      break;
    case 'off':
      dialogConfig.content = traduction('COMMON_ASK_OK');
      powerControlParam.OperateType = 'GracefulShutdown';
      dialogConfig.value = 'GracefulShutdown';
      break;
    case 'forcedOff':
      dialogConfig.content = traduction('POWER_STRONG_DOWN_POWER_TIP');
      powerControlParam.OperateType = 'ForceOff';
      dialogConfig.value = 'ForceOff';
      break;
    case 'forcedRestart':
      dialogConfig.content = traduction('POWER_REST_START_TIP');
      powerControlParam.OperateType = 'ForceRestart';
      dialogConfig.value = 'ForceRestart';
      break;
    case 'powerCycle':
      dialogConfig.content = traduction('POWER_SAFE_LABLE_TIP');
      powerControlParam.OperateType = 'PowerCycle';
      dialogConfig.value = 'PowerCycle';
      break;
    case 'forcedCycle':
      dialogConfig.content = traduction('POWER_OFF_POWER_ON_TIP');
      powerControlParam.OperateType = 'ForcePowerCycle';
      dialogConfig.value = 'ForcePowerCycle';
      break;
    case 'acCycle':
      dialogConfig.content = traduction('POWER_AC_LABLE_TIP');
      powerControlParam.OperateType = 'ACCycle';
      dialogConfig.value = 'ACCycle';
      break;
    case 'nmi':
      dialogConfig.content = traduction('POWER_NMI_LABEL_TIP');
      powerControlParam.OperateType = 'Nmi';
      dialogConfig.value = 'Nmi';
      break;
    case 'computeReset':
      dialogConfig.content = traduction('POWER_COMPUTE_RESTART_LABEL_TIP');
      powerControlParam.OperateType = 'ForceRestart_4';
      dialogConfig.value = 'ForceRestart_4';
      break;
    case 'computeOff':
      dialogConfig.content = traduction('POWER_COMPUTE_OFF_LABEL_TIP');
      powerControlParam.OperateType = 'GracefulShutdown_4';
      dialogConfig.value = 'GracefulShutdown_4';
      break;
    case 'computeCycle':
      dialogConfig.content = traduction('POWER_COMPUTE_CYCLE_LABEL_TIP');
      powerControlParam.OperateType = 'PowerCycle_4';
      dialogConfig.value = 'PowerCycle_4';
      break;
    default:
      break;
  }
  if (val !== 'on') {
    dialogConfig.content += `<br/>${traduction('POWER_OTHER_OFF_ALERT_TIP')}`;
  }
  dialogRef.value.show();
}
// 关闭dialog
function dialogClose(reason: boolean) {
  dialogRef.value.hide();
  if (reason) {
    setPowerOnOff(powerControlParam).then(res => {
      showElMessage('success', traduction('COMMON_SUCCESS'));
    })
    .catch((error: any) => {
      showFWMessage(error);
    });
  }
}
// 漏液自动下电
const leakage = reactive({
  switchState: false,
});

// 延迟上电设置的radio发生修改
function delayRadioChange(val: any, key?: number) {
  setBtnState(key);
}

// 设置保存按钮的状态
function setBtnState(key?: number) {
  const obj = {
    powerOnPolicySelected: powerOnPolicySelected.value,
    powerOnDelayedSelected: powerOnDelayedSelected.value,
  };
  let diff = false;
  if (key && powerOnDelayed[key].editor.value !== powerOnDelayed[key].editor.oldValue) {
    diff = true;
  }
  saveBtn.value = !diff && compareObjectEqual(obj, oldData);
}

// 获取请求参数
function getParams() {
  let param: any = {};
  if (powerOnPolicySelected.value !== oldData.powerOnPolicySelected) {
    if (powerOnPolicySelected.value === traduction('POWER_KEEP_ON')) {
      param.PowerOnStrategy = powerOnPolicyType.alwaysPowerOn;
    } else if (powerOnPolicySelected.value === traduction('POWER_KEEP_DOWN')) {
      param.PowerOnStrategy = powerOnPolicyType.alwaysPowerOff;
    } else if (powerOnPolicySelected.value === traduction('POWER_KEEP_CONSISTT')) {
      param.PowerOnStrategy = powerOnPolicyType.lastState;
    }
  }
  if (powerOnDelayedSelected.value !== oldData.powerOnDelayedSelected) {
    param.PowerRestoreDelay = {
      Mode: powerOnDelayedSelected.value,
    };
  }
  switch (powerOnDelayedSelected.value) {
    case 'HalfDelay':
      param = setSeconds(1, param);
      break;
    case 'FixedDelay':
      param = setSeconds(2, param);
      break;
    case 'RandomDelay':
      param = setSeconds(3, param);
      break;
    default:
      break;
  }
  return param;
}
function setSeconds(val: number, param: any) {
  if (powerOnDelayed[val].editor.value !== oldSeconds) {
    if (param.PowerRestoreDelay) {
      param.PowerRestoreDelay['Seconds'] = parseFloat(powerOnDelayed[val].editor.value);
    } else {
      param.PowerRestoreDelay = {
        Seconds: parseFloat(powerOnDelayed[val].editor.value),
      };
    }
  }
  return param;
}

// 点击保存按钮
function save() {
  loading(true);
  setPowerControl(getParams())
    .then(() => {
      loading(false);
      showElMessage('success', traduction('COMMON_SUCCESS'));
      saveBtn.value = true;
      init();
    })
    .catch(() => {
      loading(false);
      saveBtn.value = true;
      init();
    });
}

onMounted(() => {
  init();
  getStateTimer = setInterval(() => {
    init(false);
  }, 10000);
});

onUnmounted(() => {
  if (getStateTimer) {
    clearInterval(getStateTimer);
  }
});
</script>

<template>
  <div class="page-top">
    <!-- 系统状态 -->
    <div id="powerState" class="system-state">
      <div class="title">{{ $t('POWER_SYSTEM_STATE') }}</div>
      <el-tag :type="powerType">{{ $t(systemState) }}</el-tag>
    </div>
    <!-- 虚拟按钮 -->
    <div class="power-virtual-keys">
      <div class="title">{{ $t('POWER_VIRTUAL_KEYS') }}</div>
      <!-- 虚拟按键列表 -->
      <div class="button-list">
        <template v-for="item in virtualKeyLists" :key="item.id">
          <div v-if="item.show" :class="['list-item', item.className]">
            <el-button
              :id="item.id"
              v-addTooltip.elButton
              :disabled="!isPrivileges"
              @click="virtualKeyClick(item.id)"
            >
              {{ $t(item.information) }}
            </el-button>
            <HelpIcon
              v-if="item.id !== 'on' && item.id !== 'off'"
              class="substitute"
              :tips="$t(item.helpTips || '')"
            />
            <span v-if="item.promptId" :id="item.promptId" class="item-info">
              {{ $t(item.promptMessage || '') }}
            </span>
            <template v-if="item.id === 'off'">
              <!-- 空icon占位 -->
              <el-icon class="substitute"></el-icon>
              <el-checkbox
                v-model="powerOffChecked"
                v-addId.select="'powerOffTime'"
                :disabled="!isPrivileges || isSystemLock"
                @change="powerOffTimeChange"
              >
                {{ $t('POWER_OFF_TIME') }}
              </el-checkbox>
              <Editor
                v-if="powerOffChecked && isPrivileges && !isSystemLock"
                :id-str="'powerOffEditor'"
                :input-style="{ width: '56px' }"
                :input-type="'text'"
                :value="safePowerOffTimoutSeconds"
                :rule="offTimeRule"
                :popover-setting="offTimePopoverSetting"
                @editor="powerOffTimeEdit.editor"
                @cancel="powerOffTimeEdit.cancel"
                @confirm="powerOffTimeEdit.confirm"
              />
            </template>
          </div>
        </template>
      </div>
      <Dialog ref="dialogRef" :config="dialogConfig" @close="dialogClose">
        <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>
      </Dialog>
    </div>
  </div>
  <div v-if="leakageSupport || !multihost" class="page-buttom">
    <!-- 面板电源按钮 -->
    <div v-if="!multihost" class="panel-btn">
      <div class="title">{{ $t('POWER_PANLE_BUTTON') }}</div>
      <div class="panel-btn-content">
        <span>
          {{ $t('POWER_PANLE_BUTTON_OFF') }}
        </span>
        <HelpIcon class="panel-tip" :placement="'top'" :tips="$t('POWER_PANEL_BTN_TIP')" />
        <el-switch
          id="panelPower"
          v-model="switchState"
          :disabled="!isPrivileges || isSystemLock"
          @change="panelPowerChange"
        />
      </div>
    </div>
    <!-- 网络唤醒功能 -->
    <div v-if="false" class="wake-on-lan">
      <div class="title">{{ $t('POWER_WAKE_ON_LAN_STATUS') }}</div>
      <span class="wake-label">{{ $t('POWER_WAKE_ON_LAN_STATUS_LABEL') }}</span>
      <el-switch id="wakeOnLan" :disabled="!isPrivileges || isSystemLock" />
    </div>
    <!-- 通电开机策略 -->
    <div v-if="!multihost" id="powerOnPolicy" class="power-on-policy">
      <div class="title">{{ $t('POWER_POLICY') }}</div>
      <el-radio-group
        v-model="powerOnPolicySelected"
        :disabled="!isPrivileges || isSystemLock"
        @change="powerOnPolicyChange"
      >
        <el-radio-button
          v-for="item in powerOnPolicy"
          :id="item.id"
          :key="item.label"
          v-addTooltip.elRadioButton="200"
          :label="item.label"
          :disabled="item.disabled || isSystemLock"
        ></el-radio-button>
      </el-radio-group>
    </div>
    <!-- 延迟上电设置 -->
    <div v-if="!multihost" class="power-on-delayed">
      <div class="title">{{ $t('POWER_DELAY_CONFIG') }}</div>
      <el-radio-group
        v-model="powerOnDelayedSelected"
        class="delayed-content"
        :disabled="!isPrivileges || isSystemLock"
      >
        <el-radio
          v-for="(item, index) in powerOnDelayed"
          :key="item.label"
          v-addId.radio="item.value"
          :label="item.value"
          @change="delayRadioChange($event, index)"
        >
          <div class="radio-content">
            <span>{{ item.label }}</span>
            <span class="desc-info">{{ item.desc }}</span>
            <Editor
              v-if="
                item.editor.show &&
                  powerOnDelayedSelected === item.value &&
                  isPrivileges &&
                  !isSystemLock
              "
              :id-str="'powerOnDelayedEditor'"
              :input-style="{ width: '56px' }"
              :input-type="'text'"
              :value="item.editor.value"
              :rule="item.delayRule"
              :popover-setting="delayPopoverSetting"
              @editor="item.editor.editor"
              @cancel="item.editor.cancel"
              @confirm="item.editor.confirm"
            />
            <span
              v-if="
                item.editor.show &&
                  (powerOnDelayedSelected !== item.value || !isPrivileges || isSystemLock)
              "
              class="info"
            >
              --
            </span>
          </div>
        </el-radio>
      </el-radio-group>
    </div>
    <el-button
      v-if="isPrivileges && !multihost"
      id="powerContorlSaveId"
      :disabled="saveBtn || isSystemLock"
      type="primary"
      @click="save"
    >
      {{ $t('COMMON_SAVE') }}
    </el-button>
    <!-- 漏液自动下电 -->
    <div v-if="leakageSupport" class="leakage" :class="multihost ? 'no-margin' : ''">
      <div class="title leakage-title">{{ $t('POWER_LEAKAGE_POWEROFF') }}</div>
      <div class="leakage-content">
        <el-switch
          id="leakage"
          v-model="leakage.switchState"
          :disabled="!isPrivileges || isSystemLock"
          @change="leakageSwitchStateChange"
        ></el-switch>
        <span>{{ $t('POWER_LEAKAGE_TIP') }}</span>
      </div>
    </div>

    <Dialog
      ref="panelPowerDialogRef"
      :config="panelPowerDialogConfig"
      @close="panelPowerDialogClose"
    ></Dialog>
    <Dialog
      ref="leakageSwitchStateDialogRef"
      :config="leakageSwitchStateDialogConfig"
      @close="leakageSwitchStateDialogClose"
    ></Dialog>
  </div>
</template>

<style lang="scss" scoped>
.page-top,
.page-buttom {
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  padding: 24px;
  margin-bottom: 16px;
  margin-right: 24px;
  .title {
    font-size: 16px;
    font-weight: 600;
    color: var(--o-text-color-primary);
    line-height: 24px;
    margin-bottom: 16px;
  }
  .el-icon {
    color: var(--o-text-color-tertiary);
    &:hover {
      color: var(--o-color-primary-secondary);
      cursor: pointer;
    }
  }
}
.system-state {
  margin-bottom: 24px;

  .title {
    margin-bottom: 14px;
  }

  .el-tag {
    height: 16px;
    width: 64px;
    padding: 0;
    font-weight: 600;
  }
}
.power-virtual-keys {
  .button-list {
    .list-item {
      margin-bottom: 24px;
      height: 32px;
      line-height: 32px;
      display: flex;
      align-items: center;
      &:nth-last-child(1) {
        margin-bottom: 0;
      }
      .editor-icon {
        vertical-align: middle;
        margin-left: 8px;
        &:hover {
          cursor: pointer;
        }
      }
      .el-checkbox {
        margin-right: 16px;
      }
      .seconds {
        color: var(--o-text-color-secondary);
        line-height: 16px;
      }
    }
    .el-button {
      width: 200px;
      height: 32px;
      margin-right: 8px;
    }
    .item-info {
      color: var(--o-text-color-tertiary);
      line-height: 16px;
      vertical-align: middle;
    }
    .power-off {
      :deep(.el-input) {
        width: 56px;
        .el-input__inner {
          padding-left: 0 !important;
          text-align: center;
        }
      }
    }
  }
}
.panel-btn {
  margin-bottom: 24px;

  .panel-btn-content {
    display: flex;
    align-items: center;
  }

  span {
    color: var(--o-text-color-secondary);
    line-height: 16px;
    margin-right: 4px;
  }
}
.wake-on-lan {
  margin-bottom: 24px;
  .wake-label {
    margin-right: 24px;
  }
}
.power-on-policy {
  margin-bottom: 24px;

  :deep(.el-radio-group .el-radio-button) {
    margin-bottom: 0 !important;
  }
}
.power-on-delayed {
  margin-bottom: 16px;
}
.leakage {
  margin-top: 24px;

  .leakage-content {
    display: flex;
    align-items: center;
  }

  .el-switch {
    margin-right: 24px;
  }
}
.no-margin{
  margin-top: 0px;
}
.substitute {
  width: 16px;
  height: 16px;
  margin-right: 16px;
}
.panel-tip {
  margin-right: 24px;
}
.delayed-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  :deep(.el-radio__label) {
    display: flex;
    align-items: center;
  }

  :deep(.radio-content) {
    display: flex;
    align-items: center;

    .desc-info {
      margin-left: 8px;
      color: var(--o-text-color-tertiary);
    }
    .editor-box .btn-box .value span {
      font-size: 12px;
      color: #8d98aa;
      letter-spacing: 0;
      line-height: 16px;
    }
  }

  :deep(.el-radio) {
    margin-bottom: 8px;

    &:nth-last-child(1) {
      margin-bottom: 0;
    }
  }
}
.list-item {
  display: flex;
}
.content-item.text {
  margin-left: 16px;
  padding-top: 4px;
}
</style>
