<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import {
  getBiosSetting,
  discardAllPending,
  importBiosWebConfig,
} from '@/services/system/bios-service';
import { setPowerState } from '@/services/header/header.service';
import { getStoreData, loading, showFailedMessage } from '@/utils/composition';
import { traduction, getErrorTranslate } from '@/utils/language';
import { ISettingTitle } from '../model/model';
import { ITableColumns } from '@/model/base-interface';
import Dialog from '@/components/Dialog/Dialog.vue';
import biosCollapse from '../components/biosCollapse.vue';
import { useRouter, onBeforeRouteLeave } from 'vue-router';
import { showElMessage, getMessageId } from '@/utils/utils';
import useStore from '@/stores';
import { IconRemind } from '@computing/opendesign-icons';

const disabled = ref(true);
const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const privil = getStoreData('loct', 'privil');
const hasConfigUsers = privil.includes('UserConfigEnabled');
const emits = defineEmits(['handleChange']);
let selectTitle = ref('');
const changeRef = ref();
const helpRef = ref();
const applyRef = ref();
const clearRef = ref();
const isReset = ref(false);
let editData = reactive<any[]>([]);
let tableData = reactive<any[]>([]);
const canSave = ref(false);
const changeConfig = reactive({
  title: traduction('COMMON_INFORMATION'),
  content: traduction('BIOS_JUMP_TIP'),
  okButton: { id: 'changeConfig_ok_btn', label: traduction('COMMON_OK'), hide: false },
  cancelButton: { id: 'changeConfig_cancel_btn', label: traduction('COMMON_CANCEL'), hide: false },
});

const applyConfig = reactive({
  title: traduction('BIOS_APPLY_RESET'),
  content: traduction('BIOS_APPLY_RESET_TIP'),
  okButton: { id: 'applyConfig_ok_btn', label: traduction('COMMON_OK'), hide: false },
  cancelButton: { id: 'applyConfig_cancel_btn', label: traduction('COMMON_CANCEL'), hide: false },
});

const clearConfig = reactive({
  title: traduction('BIOS_DISCARD_PENDING_ITEM'),
  content: traduction('BIOS_DISCARD_PENDING_ITEM_TIP'),
  okButton: { id: 'clearConfig_ok_btn', label: traduction('COMMON_OK'), hide: false },
  cancelButton: { id: 'clearConfig_cancel_btn', label: traduction('COMMON_CANCEL'), hide: false },
});

const helpConfig = reactive({
  type: '',
  content: '',
  title: traduction('BIOS_PENDING_TIPS_TITLE'),
  okButton: { id: 'helpConfig_ok_btn', label: traduction('HEADER_UID_OFF'), hide: false },
  cancelButton: { id: 'helpConfig_cancel_btn', label: traduction('HEADER_UID_OFF'), hide: true },
  width: '1000',
});

let helpTips = reactive([] as Array<{ isTitle?: boolean; title: string; content: string }>);
const $router = useRouter();
const route = useRoute();
const toRoute = ref('');
const routeChange = ref(false);
const paramsArray = reactive([]);

onBeforeRouteLeave((to, from, next) => {
  if (to.fullPath !== '/navigate/system/bios-settings/2') {
    toRoute.value = to.fullPath;
    if (canSave.value) {
      changeRef.value.show();
    }
    if (routeChange.value || !canSave.value) {
      next();
    }
  } else {
    next();
  }
});

const tipColumns: ITableColumns[] = [
  {
    title: 'BIOS_CONFIGURATION_ITEM',
    width: '50%',
    content: 'title',
  },
  {
    title: 'BIOS_CONFIGURATION_TIPS',
    width: '50%',
    content: 'content',
  },
];

const settingTitle = reactive([]) as Array<ISettingTitle>;
const activeName = ref('');
const canDiscard = ref(false);

function init() {
  loading(true);
  // 获取systemId参数，如果存在则传递给getBiosSetting
  const systemId = route.query.systemId as string;
  getBiosSetting(systemId)
    .then((res: any) => {
      tableData.splice(0);
      editData.splice(0);
      for (let index = 0; index < res.length; index++) {
        const showPending = showEdit(res[index]);
        tableData.push(JSON.parse(JSON.stringify({ showPending, ...res[index] })));
        editData.push(JSON.parse(JSON.stringify({ showPending, ...res[index] })));
      }
      canDiscard.value = checkCanDiscard(tableData);
    })
    .finally(() => {
      loading(false);
    });
}

function handleChange(title: string) {
  selectTitle.value = title;
}

function closeChangeModal(reason: boolean) {
  if (reason) {
    $router.push(toRoute.value);
    canSave.value = false;
  } else {
    emits('handleChange', '2');
  }
  changeRef.value.hide();
}

function showHelpTips(item: any) {
  helpTips.splice(0);
  helpTips.push({
    isTitle: true,
    title: item.id || '',
    content: '',
  });
  for (let index = 0; index < item?.tableData?.Attributes.length; index++) {
    helpTips.push({
      title: item.tableData.Attributes[index]?.AttributeName || '',
      content: item.tableData.Attributes[index]?.HelpText || '',
    });
  }
  if (item?.tableData?.SubMenu.length > 0) {
    getTips(item.tableData.SubMenu);
  }

  helpRef.value.show();
}

function getTips(arr: Array<any>) {
  if (arr && arr.length === 0) {
    return;
  }
  for (let index = 0; index < arr.length; index++) {
    helpTips.push({
      isTitle: true,
      title: arr[index].Name || '',
      content: '',
    });

    for (let i = 0; i < arr[index]?.Attributes?.length; i++) {
      helpTips.push({
        title: arr[index].Attributes[i]?.AttributeName || '',
        content: arr[index].Attributes[i]?.HelpText || '',
      });
    }
    if (arr[index]?.SubMenu && arr[index]?.SubMenu.length > 0) {
      getTips(arr[index].SubMenu);
    }
  }
}

function clearModal(reason: boolean) {
  if (reason) {
    loading(true);
    // 获取systemId参数，如果存在则传递给discardAllPending
    const systemId = route.query.systemId as string;
    discardAllPending(systemId)
      .then(() => {
        showElMessage('success', traduction('COMMON_SUCCESS'));
        loading(false);
        init();
      })
      .catch((err: any) => {
        const errorCode = err?.data?.error?.[0]?.code;
        if (errorCode) {
          showFailedMessage(getErrorTranslate(errorCode));
        } else {
          showElMessage('error', traduction('COMMON_FAILED'));
        }
        loading(false);
      });
  }
  clearRef.value.hide();
}

function closeApplyModal(reason: boolean) {
  const params = { Attributes: {} };
  for (let item of paramsArray) {
    params.Attributes[item.AttributeName] = item.CurrentValue;
  }
  // 获取systemId参数，如果存在则传递给相关函数
  const systemId = route.query.systemId as string;
  
  if (reason) {
    loading(true);
    if (isReset.value) {
      importBiosWebConfig(params, systemId)
        .then(() => {
          showElMessage('success', traduction('COMMON_SUCCESS'));
          setPowerState({ type: 'ForceRestart', systemId }).then(() => {
            init();
            loading(false);
          });
        })
        .catch((err: any) => {
          const errorCode = err?.data?.error?.[0]?.code;
          if (errorCode) {
            showFailedMessage(getErrorTranslate(errorCode));
          } else {
            showElMessage('error', traduction('COMMON_FAILED'));
          }
          loading(false);
        });
    } else {
      importBiosWebConfig(params, systemId)
        .then(() => {
          showElMessage('success', traduction('BIOS_APPLY_SUCCESS'));
          loading(false);
          init();
        })
        .catch((err: any) => {
          const errorCode = err?.data?.error?.[0]?.code;
          if (errorCode) {
            showFailedMessage(getErrorTranslate(errorCode));
          } else {
            showElMessage('error', traduction('COMMON_FAILED'));
          }
          loading(false);
        });
    }
  }
  isReset.value = false;
  applyRef.value.hide();
}

function closeHelpModal() {
  helpRef.value.hide();
}

function applyAndReset(reset: boolean) {
  isReset.value = reset;
  if (!reset) {
    applyConfig.title = traduction('BIOS_APPLY_NEXT_RESET');
    applyConfig.content = traduction('BIOS_APPLY_NEXT_RESET_TIP');
  } else {
    applyConfig.title = traduction('BIOS_APPLY_RESET');
    applyConfig.content = traduction('BIOS_APPLY_RESET_TIP');
  }
  applyRef.value.show();
}

function discardAll() {
  clearRef.value.show();
}

function validate() {
  paramsArray.splice(0);
  let result = compareData(editData, tableData);
  canSave.value = result === 'noPass' ? false : result;
}

function compareData(newArray, oldArray) {
  let result = false;

  for (let index = 0; index < newArray.length; index++) {
    let targetArray = newArray[index];
    let oldTargetArray = oldArray[index];
    for (let i = 0; i < targetArray?.Attributes?.length; i++) {
      if (targetArray.Attributes[i].pass === false) {
        return 'noPass';
      }
      if (targetArray.Attributes[i].CurrentValue !== oldTargetArray.Attributes[i].CurrentValue) {
        result = true;
        paramsArray.push(targetArray.Attributes[i]);
      }
    }
    if (targetArray?.SubMenu?.length > 0) {
      let temp = compareData(targetArray.SubMenu, oldTargetArray.SubMenu);
      result = temp === 'noPass' ? 'noPass' : result || temp;
    }
  }

  return result;
}

function showEdit(item: any, flag: boolean = false): any {
  let resultSubMenu = !item.SubMenu || item?.SubMenu?.length === 0;
  let resultAttributes = !item.Attributes || item?.Attributes?.length === 0;
  if (resultSubMenu && resultAttributes) {
    return false;
  }
  item.Attributes = item.Attributes.filter(i => !i.Hidden);
  let result = false;
  for (let index = 0; index < item.Attributes.length; index++) {
    if (flag) {
      delete item.Attributes[index].LowerBound;
      delete item.Attributes[index].UpperBound;
    }
    if (item.Attributes[index].CurrentValue === null) {
      item.Attributes[index].CurrentValue = item.Attributes[index].DefaultValue;
    }
    item.Attributes[index].standardValue = item.Attributes[index].CurrentValue;
    if (item.Attributes[index].SettingValue) {
      result = true;
    }
  }
  for (let index = 0; index < item.SubMenu.length; index++) {
    let subFlag = false;
    if (item.Name === 'NICConfiguration') {
      subFlag = true;
    }
    let temp = showEdit(item.SubMenu[index], subFlag);
    result = temp || result;
  }
  return result;
}

function checkCanDiscard(newArray) {
  let result = false;

  for (let index = 0; index < newArray.length; index++) {
    let targetArray = newArray[index];
    for (let i = 0; i < targetArray?.Attributes?.length; i++) {
      if (targetArray?.Attributes[i]?.SettingValue) {
        result = true;
      }
    }
    if (targetArray?.SubMenu?.length > 0) {
      result = result || checkCanDiscard(targetArray.SubMenu);
    }
  }

  return result;
}

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

// 监听路由参数变化，当systemId改变时重新获取数据
watch(
  () => route.query.systemId,
  (newSystemId, oldSystemId) => {
    if (newSystemId !== oldSystemId) {
      init();
    }
  },
);
</script>
<template>
  <div class="right-container">
    <div id="biosBtnBox" class="btnBox">
      <el-button
        id="applyAndReset"
        class="save"
        type="primary"
        :disabled="!canSave || isSystemLock || !hasConfigUsers"
        @click="applyAndReset(true)"
      >
        {{ $t('BIOS_APPLY_RESET') }}
      </el-button>
      <el-button
        id="applyNoReset"
        class="save"
        type="primary"
        :disabled="!canSave || isSystemLock || !hasConfigUsers"
        @click="applyAndReset(false)"
      >
        {{ $t('BIOS_APPLY_NEXT_RESET') }}
      </el-button>
      <el-button
        id="clear"
        :disabled="!canDiscard || isSystemLock || !hasConfigUsers"
        class="save"
        @click="discardAll"
      >
        {{ $t('BIOS_DISCARD_PENDING_ITEM') }}
      </el-button>
    </div>
    <div id="biosSettingTips" class="alert">
      <el-icon>
        <IconRemind />
      </el-icon>
      <span class="text">
        {{ $t('BIOS_SETTING_TIPS') }}
      </span>
    </div>
    <div id="biosContent">
      <biosCollapse
        v-if="tableData"
        id="biosCollapseContent"
        :data="editData"
        :root-data="tableData"
        :is-root="true"
        @show-help-tips="showHelpTips"
        @validate="validate"
      />
    </div>
    <Dialog
      id="changeRef"
      ref="changeRef"
      :config="changeConfig"
      @close="closeChangeModal"
    ></Dialog>
    <Dialog id="applyRef" ref="applyRef" :config="applyConfig" @close="closeApplyModal"></Dialog>
    <Dialog id="clearRef" ref="clearRef" :config="clearConfig" @close="clearModal"></Dialog>
    <Dialog id="helpRef" ref="helpRef" :config="helpConfig" @close="closeHelpModal">
      <template #other>
        <div class="help-tips-box">
          <el-table
            v-addId.table="'assetChangeTable'"
            :data="helpTips"
            :class="{ tableHeight: helpTips.length > 0 }"
          >
            <el-table-column
              v-for="(item, index) in tipColumns"
              :key="item.title"
              :label="$t(item.title)"
              :min-width="item.width"
            >
              <template #default="scope">
                <span v-if="scope.row.isTitle" :id="item.content + index" class="tips-title">
                  {{ scope.row[item.content] }}
                </span>
                <span v-else :id="item.content + index" class="tips-content">
                  {{ scope.row[item.content] }}
                </span>
              </template>
            </el-table-column>
            <template #empty>
              <TableNoData />
            </template>
          </el-table>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<style lang="scss" scoped>
.cpu-alert-container {
  margin-bottom: 8px;
}

.cpu-alert-container:nth-child(2) {
  margin-bottom: 16px;
}

h3 {
  font-size: $FONT-16;
  margin-bottom: 16px;
  .help-icon-cpu {
    margin-left: 3px;
    margin-top: -2px;

    :deep(.el-popper) {
      max-width: 382px;
    }
  }
}
.slider-item {
  margin-bottom: 50px;
  :deep(.el-slider__stop) {
    display: none;
  }

  .slider {
    width: calc(100% - 16px);
    margin-left: 8px;
  }
}

.right-container {
  padding: 16px 24px 24px 24px;
  .btnBox {
    margin-bottom: 16px;
  }

  .selectBox {
    width: 200px;
  }
}
.help-tips-box {
  width: 100%;
  :deep(.el-scrollbar) {
    .el-scrollbar__bar {
      display: none;
    }
  }
  .tips-title {
    font-size: 12px;
    color: var(--o-color-black);
    font-family: HarmonyOS Sans SC;
    font-weight: bold;
    line-height: 16px;
  }
  .tips-content{
    font-size: 12px;
    color: var(--o-color-black);
    font-family: HarmonyOS Sans SC;
    line-height: 16px;
  }
}
.alert {
  margin-top: 8px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: var(--o-color-state-primary-secondary);
  border-radius: 4px;

  .el-icon {
    font-size: 16px;
    margin-right: 8px;
  }

  .text {
    color: var(--o-text-color-primary);
  }
}
</style>
