<script lang="ts" setup>
import { computed, onMounted, reactive, Ref, ref, toRaw, watch } from 'vue';
import { useRoute } from 'vue-router';
import { getBiosConfig, saveBiosBoot } from '@/services/system/bios-service';
import { getStoreData, loading, setStoreData } from '@/utils/composition';
import { traduction } from '@/utils/language';
import BootOrder from '@/components/BootOrder/BootOrder.vue';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import PullDownTriangle from '@/components/PullDownTriangle/PullDownTriangle.vue';

const route = useRoute();

const hasBaseConfigPrivil = checkPrivil(UserPrivil.baseConfig);
const isLocked = computed(() => {
  return getStoreData('glob', 'systemLocked');
});
const disabled = ref(true);
const bootOrder: Ref<string[]> = ref([]);
let fieldChange = {};
// BIOS数据字段
let baseBiosConfig: any = null;
let currentOrder: any = null;
const isArm = getStoreData('loct', 'armspt');
const biosConfig = reactive({
  ipmiSupport: {
    value: false,
  },
  bootModel: {
    value: 'Legacy',
    options: [
      { label: 'BIOS_LEGACY_BIOS', value: 'Legacy', id: 'bootModeLegacy' },
      { label: 'BIOS_UEFI', value: 'UEFI', id: 'bootModeUEFI' },
    ],
  },
  bootMedium: {
    value: 'None',
    state: true,
    options: [
      { label: 'BIOS_NO_OVERRIDE', value: 'None' },
      { label: 'BIOS_PXE', value: 'Pxe' },
      { label: 'BIOS_FDD_REMOVAVLE_DEVICE', value: 'Floppy' },
      { label: 'BIOS_CD_DVD', value: 'Cd' },
      { label: 'BIOS_HAED_DRIVE', value: 'Hdd' },
      { label: 'BIOS_SETTING', value: 'BiosSetup' },
    ],
  },
  effectivePeriod: {
    value: 'Once',
    options: [
      { label: 'BIOS_ONE_TIME', value: 'Once', id: 'bootMediaOne' },
      { label: 'BIOS_PERMANENT', value: 'Continuous', id: 'bootMediaPermanent' },
    ],
  },
});

function dataChange(field: string) {
  const baseData = JSON.parse(baseBiosConfig)[field].value;
  const curValue = biosConfig[field].value;
  if (baseData === curValue) {
    delete fieldChange[field];
  } else {
    fieldChange[field] = true;
  }
  computedState();
}

function orderChange(order: string[] | null) {
  if (order === null) {
    delete fieldChange['order'];
  } else {
    fieldChange['order'] = true;
  }
  currentOrder = order;
  computedState();
}

function computedState() {
  const isFieldChange = Object.keys(fieldChange).length > 0;
  disabled.value = !isFieldChange;
}

function saveBios() {
  if (Object.keys(fieldChange).length === 0 || isLocked.value) {
    return;
  }
  const prams: { [key: string]: any } = {};
  if (currentOrder !== null) {
    prams.BootOrder = currentOrder;
  }
  if (fieldChange['ipmiSupport']) {
    const state = biosConfig.ipmiSupport.value ? 'On' : 'Off';
    prams.BootModeConfigOverIpmiEnabled = state;
  }
  if (fieldChange['bootModel']) {
    prams.BootSourceOverrideMode = biosConfig.bootModel.value;
  }
  // 优先引导介质和有效性需放在一块传入
  if (fieldChange['bootMedium'] || fieldChange['effectivePeriod']) {
    prams.PreferredBootMedium = {};
    prams.PreferredBootMedium.Target = biosConfig.bootMedium.value;
    prams.PreferredBootMedium.EffectivePeriod = biosConfig.effectivePeriod.value;
  }
  loading(true);
  disabled.value = true;
  const systemId = route.query.systemId as string;
  saveBiosBoot(prams, systemId)
    .then(
      () => {
        setStoreData('event', 'alertMessage', {
          type: 'success',
          message: traduction('COMMON_SUCCESS'),
        });
        init();
      },
      () => {
        disabled.value = false;
      },
    )
    .finally(() => {
      loading(false);
    });
}

function init() {
  loading(true);
  // 获取systemId参数，如果存在则传递给getBiosConfig
  const systemId = route.query.systemId as string;
  getBiosConfig(systemId)
    .then((res: any) => {
      fieldChange = {};
      biosConfig.ipmiSupport.value = res.BootModeConfigOverIpmiEnabled === 'On';
      biosConfig.bootModel.value = res.BootSourceOverrideMode;
      biosConfig.bootMedium.value = res.PreferredBootMedium.Target;
      // EffectivePeriod为非Continuous值时，统一认为是Once
      biosConfig.effectivePeriod.value =
        res.PreferredBootMedium.EffectivePeriod === 'Continuous' ? 'Continuous' : 'Once';
      bootOrder.value = res.BootOrder || [];
      // 保存为基础数据
      baseBiosConfig = JSON.stringify(toRaw(biosConfig));
    })
    .finally(() => {
      loading(false);
    });
}

onMounted(() => {
  init();
});

// 监听路由参数变化，当systemId改变时重新获取数据
watch(
  () => route.query.systemId,
  (newSystemId, oldSystemId) => {
    if (newSystemId !== oldSystemId) {
      init();
    }
  },
);
</script>

<template>
  <div class="right-container">
    <el-form label-width="150px" label-position="left">
      <!-- 支持IPMI设置启动模式 -->
      <el-form-item v-if="!isArm" :label="$t('BIOS_IPMI_BOOT_MODE')" class="switch-item">
        <el-switch
          :id="'ipmiSwitchId'"
          v-model="biosConfig.ipmiSupport.value"
          :disabled="!hasBaseConfigPrivil || isLocked"
          @change="dataChange('ipmiSupport')"
        />
      </el-form-item>

      <!-- 启动模式 -->
      <el-form-item v-if="!isArm" :label="$t('BIOS_BOOT_MODE')" class="switch-item">
        <el-radio-group v-model="biosConfig.bootModel.value" @change="dataChange('bootModel')">
          <el-radio
            v-for="item in biosConfig.bootModel.options"
            :key="item.value"
            v-addId.radio="item.id"
            :label="item.value"
            :disabled="!hasBaseConfigPrivil || isLocked"
          >
            {{ $t(item.label) }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 优先引导介质 -->
      <el-form-item :label="$t('BIOS_BOOT_MEDIUM')">
        <el-select
          v-model="biosConfig.bootMedium.value"
          v-addId.select="'bootMediaId'"
          :teleported="false"
          :placeholder="' '"
          :suffix-icon="PullDownTriangle"
          :disabled="!hasBaseConfigPrivil || isLocked"
          @change="dataChange('bootMedium')"
        >
          <el-option
            v-for="item in biosConfig.bootMedium.options"
            :key="item.value"
            :label="$t(item.label)"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-radio-group
          v-model="biosConfig.effectivePeriod.value"
          @change="dataChange('effectivePeriod')"
        >
          <el-radio
            v-for="item in biosConfig.effectivePeriod.options"
            :key="item.value"
            v-addId.radio="item.id"
            :label="item.value"
            :disabled="!hasBaseConfigPrivil || isLocked"
          >
            {{ $t(item.label) }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 启动顺序 -->
      <el-form-item :label="$t('BIOS_BOOT_PRIORITY')">
        <BootOrder :orders="bootOrder" @change="orderChange" />
      </el-form-item>
      <el-form-item class="clear" :label="''">
        <el-button
          id="bootDeviceSaveId"
          v-privil.baseConfig
          type="primary"
          :disabled="isLocked || disabled"
          @click="saveBios"
        >
          {{ $t('COMMON_SAVE') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.clear {
  margin-bottom: 0;
}
:deep(.el-select) {
  min-width: 240px;
  margin-right: 26px;
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 24px;
  }

  .switch-item {
    .el-form-item__label {
      padding: 0 24px 0 0;
      font-size: 12px;
    }

    .el-form-item__content {
      .el-radio {
        height: auto;
      }
    }
  }

  .clear {
    margin-bottom: 0;
  }
}

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