<script setup lang="ts">
import { WEBVNC_PAGE_ENABLED } from '@/model/configure';
import { computed, reactive, ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import Dialog from '@/components/Dialog/Dialog.vue';
import { reset } from '../../services/home.service';
import CollectProgress from './CollectProgress.vue';
import useStore from '@/stores';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { SecondAuthorityFail, SystemModel, UserPrivil } from '@/model/base-enum';
import SecondPassword from '@/components/SecondPassword/SecondPassword.vue';
import { traduction, getErrorTranslate } from '@/utils/language';
import { IconUser, IconAlarm } from '@computing/opendesign-icons';
import { clearCurrentLoginInfo } from '@/utils/common-service';
import { getStoreData, showFailedMessage } from '@/utils/composition';
import { getBrowserType, urlReplace } from '@/utils/utils';
import { Resolution, useHome, WebStyleType, IPVersionType } from '../../hooks/useHome';
import { getKvmData } from '@/pages/Service/Kvm/services/kvm.services';
import { getVncData } from '@/pages/Service/Vnc/vnc.server';
import { getPortInfo } from '@/services/port-service';

const { getResolution, getWebStyle } = useHome();
const multihost = computed(() => getStoreData('loct', 'multihost'));
const kvmSupported = computed(() => {
  return getStoreData('loct', 'kvmspt');
});
const vncSupported = computed(() => {
  return getStoreData('loct', 'vncspt');
});
const resolution = getResolution;
const webStyle = getWebStyle();
const props = defineProps({
  fusionPartition: {
    type: String,
    required: true,
    default: '',
  },
  ipAdress: {
    type: Object,
    required: true,
    default: {
      addressIPv4: '',
      addressIPv6: '',
      ipVersion: '',
    },
  },
  customerType: {
    type: String,
    required: false,
    default: '',
  },
});
const dialogRef = ref();
const currentId = ref('');
const router = useRouter();
const collectState = ref('');
const store = useStore();
const dialogConfig = reactive({
  title: '',
  content: '',
  id: '',
});
const secondRef = ref();
// 获取locked锁定值
let systemLockDownEnabled = computed(() => {
  return store.state.glob.systemLocked;
});
const hasSecurityConfig = checkPrivil(UserPrivil.securityConfig);
const hasUserConfig = checkPrivil(UserPrivil.userConfig);
const hasBaseConfig = checkPrivil(UserPrivil.baseConfig);
const hasQuery = checkPrivil(UserPrivil.query);
const remoteControl = checkPrivil(UserPrivil.remoteControl);
const hardShow = store.state.glob.partityspt;
const nopwd = getStoreData('loct', 'nopwd');
const userRole = getStoreData('loct', 'ur');
let vncCheckTimer = null as any;
let webVncStorageListened = false;

const collectVisible = ref(false);
const productLabel = ref(store.state.loct.sn);
const showCollection = () => {
  const isAdminOrOper = userRole.indexOf('Administrator') > -1 || userRole.indexOf('Operator') > -1;
  return hasSecurityConfig || (props.customerType?.includes('ByteDance') && isAdminOrOper);
};

const accesses: any = ref([
  // 本地用户
  {
    show: hasQuery,
    title: 'HOME_LOCALUSER',
    id: 'LocalUser',
    imgClass: 'home-style-icon-icon2',
    state: '/navigate/user/local-users',
    disable: !hasQuery,
    lock: false,
  },
  // 网络配置
  {
    show: hasQuery,
    title: 'HOME_NETWORK_CONFIGURATION',
    id: 'Network',
    imgClass: 'home-style-icon-icon3',
    state: '/navigate/manager/network',
    lock: false,
  },
  // 电源控制
  {
    show: hasQuery,
    title: 'HOME_POWER_CONTROL',
    id: 'PowerControl',
    imgClass: 'home-style-icon-icon4',
    state: '/navigate/system/power',
    lock: false,
  },
  // 固件升级
  {
    show: hasBaseConfig,
    title: 'HOME_FIRMWARE_UPGRADES',
    id: 'Upgrade',
    imgClass: 'home-style-icon-icon5',
    state: '/navigate/manager/upgrade',
    lock: false,
  },
  // 一键收集
  {
    show: showCollection(),
    title: 'HOME_ONE_CLICK_COLLECTION',
    id: 'Collection',
    imgClass: 'home-style-icon-icon',
    onKeySelect: true,
    lock: false,
  },
  // 恢复配置
  {
    show: hasUserConfig,
    title: 'HOME_RESTORE_CONFIGURATION',
    id: 'ConfigureUser',
    imgClass: 'home-style-icon-icon1',
    restoreSet: true,
    lock: true,
  },
  {
    show: hardShow && hasBaseConfig,
    title: 'HOME_HARD_PARTITION_SETTINGS',
    id: 'HardPart',
    imgClass: 'home-icon-hard',
    state: '/navigate/system/fusion-par',
    disable: !hasQuery,
    lock: false,
  },
  {
    show: props.fusionPartition === SystemModel.DualSystem,
    title: 'HOME_NODE_JUMP',
    id: 'NodeJump',
    imgClass: 'home-icon-node',
    disable: !hasQuery,
    nodeChange: true,
    nodeIp: '',
    lock: false,
  },
  {
    show:remoteControl && WEBVNC_PAGE_ENABLED,
    title: 'HOME_WEB_VNC',
    id: 'WebVNC',
    imgClass: 'home-style-icon-HTML',
    state: '/vnc_h5',
    lock: false,
    disable: false,
  },
]);

const browserType = getBrowserType();
init();
function init() {
  const collectProgressURL = sessionStorage.getItem('collectProgressURL');
  if (collectProgressURL) {
    collectVisible.value = true;
    collectState.value = 'init';
  }
  accesses.value = accesses.value.filter((accesse: any) => {
    return accesse.show;
  });
}

function continuedSearchVncStatus() {
  if (!WEBVNC_PAGE_ENABLED) {
    return;
  }
  searchVncActiveStatus();

  vncCheckTimer = setInterval(() => {
    searchVncActiveStatus();
  }, 10000);

  if (getStoreData('glob', 'isTimeOut')) {
    clearInterval(vncCheckTimer);
  }
}

function listenVncConnected() {
  if (localStorage.getItem('vncConnected')) {
    searchVncActiveStatus();
  }
}

function searchVncActiveStatus(): void {
  if (!WEBVNC_PAGE_ENABLED) {
    return;
  }
  Promise.all([
    kvmSupported.value ? getKvmData() : Promise.resolve(null),
    vncSupported.value ? getVncData() : Promise.resolve(null),
    getPortInfo(),
  ]).then(resArr => {
    const kvmData = resArr[0]?.data;
    const vncData = resArr[1] as any;
    const portInfoList = resArr[2] as any;
    const webVncPortInfo = portInfoList?.find((item: any) => item.name === 'WEBVNC');
    const webVncEnabled = webVncPortInfo?.enabled ?? true;
    const activeStatus1 = vncData?.ActivatedSessionsType || kvmData?.GraphicalConsole[0]?.ActivatedSessionsType || [];
    const allDisabled1 = vncData?.VNCSettings[0]?.MaximumNumberOfSessions === vncData?.VNCSettings[0]?.NumberOfActiveSessions ||
      !vncData?.Enabled ||
      (kvmData && kvmData?.GraphicalConsole[0]?.MaximumNumberOfSessions === kvmData?.GraphicalConsole[0]?.NumberOfActiveSessions);
    const activeStatus2 = vncData?.ActivatedSessionsType || kvmData?.GraphicalConsole[1]?.ActivatedSessionsType || [];
    const allDisabled2 = vncData?.VNCSettings[1]?.MaximumNumberOfSessions === vncData?.VNCSettings[1]?.NumberOfActiveSessions ||
      !vncData?.Enabled ||
      (kvmData && kvmData?.GraphicalConsole[1]?.MaximumNumberOfSessions === kvmData?.GraphicalConsole[1]?.NumberOfActiveSessions);
    const webVncAccess = accesses.value.find((access: any) => access.id === 'WebVNC');
    let shouldDisable = !webVncEnabled || allDisabled1 || activeStatus1.indexOf('Private') > -1;
    if (kvmData?.GraphicalConsole?.length === 2) {
      shouldDisable = shouldDisable || allDisabled2 || activeStatus2.indexOf('Private') > -1;
    }
    webVncAccess.disable = shouldDisable;
  }).catch(() => {
  });
}

function dialogClose(reason: boolean) {
  dialogRef.value.hide();
  if (reason) {
    if (currentId.value === 'restoreModel' && !nopwd) {
      secondRef.value.show();
    } else if (currentId.value === 'restoreModel' && nopwd) {
      reset({}).then(() => {
        resetMsg();
      });
    } else if (currentId.value === 'oneKeyConfirm') {
      collectVisible.value = true;
      collectState.value = 'click';
    } else if (currentId.value === 'restoreMessage') {
      clearCurrentLoginInfo();
      router.push('/login');
    }
  }
}

function confirmReset(param: { reason: boolean; password: string }) {
  if (param.reason) {
    const params = {
      ReauthKey: window.btoa(param.password),
    };
    reset(params).then(
      () => {
        resetMsg();
        secondRef.value.hide();
      },
      error => {
        const errorCode = error?.data?.error?.[0]?.code || '';
        if (
          errorCode === SecondAuthorityFail.REAUTHFAILED ||
          errorCode === SecondAuthorityFail.AUTHORIZATIONFAILED
        ) {
          secondRef.value.setErrorId();
          secondRef.value.clearPassword();
        }
        showFailedMessage(getErrorTranslate(errorCode));
      },
    );
  } else {
    secondRef.value.hide();
  }
}

function resetMsg() {
  currentId.value = 'restoreMessage';
  dialogConfig.id = 'restoreMessage';
  dialogConfig.title = traduction('COMMON_INFORMATION');
  dialogConfig.content = traduction('HOME_RESTORE_CONFIGURATION_SUCCESS');
  dialogRef.value.show();
}
function progressClose() {
  collectVisible.value = false;
}
function clickFn(access: any) {
  // 按钮禁用
  if (access.disable || (access.lock && systemLockDownEnabled.value)) {
    return;
  }
  if (access.state) {
    if (access.state === '/navigate/system/power') {
      if (multihost.value) {
        router.push({ path: access.state + '/multi-control' });
      } else {
        router.push({ path: access.state + '/control' });
      }
    } else if (access.state === '/vnc_h5') {
      const toURL = '#/vnc_h5';
      const win = window.open(toURL, '_blank');
      if (win) {
        win.opener = null;
      }
    } else {
      router.push({ path: access.state });
    }
  }
  if (access.onKeySelect) {
    showConfirmMsg();
  }
  if (access.restoreSet) {
    restoreSet();
  }
  if (access.nodeChange) {
    nodeChange(access);
  }
}

function nodeChange(access: any) {
  if (access.nodeIp) {
    const url = urlReplace('https://{nodeIp}', { nodeIp: access.nodeIp });
    const win = window.open(url, '_blank');
    if (win) {
      win.opener = null;
    }
  }
}
function restoreSet() {
  if (systemLockDownEnabled.value) {
    return;
  }
  currentId.value = 'restoreModel';
  dialogConfig.id = 'restoreModel';
  dialogConfig.title = traduction('HOME_RESTORE_CONFIGURATION');
  dialogConfig.content = '';
  dialogRef.value.show();
}

function showConfirmMsg() {
  currentId.value = 'oneKeyConfirm';
  dialogConfig.id = 'oneKeyConfirm';
  dialogConfig.title = traduction('HOME_ONE_CLICK_COLLECTION');
  dialogConfig.content = traduction('HOME_CONFIRM_ONE_KEY_SELECT');
  dialogRef.value.show();
}

onMounted(() => {
  if (WEBVNC_PAGE_ENABLED) {
    continuedSearchVncStatus();
    window.addEventListener('storage', listenVncConnected);
    webVncStorageListened = true;
  }
});
onUnmounted(() => {
  if (vncCheckTimer) {
    clearInterval(vncCheckTimer);
  }
  if (webVncStorageListened) {
    window.removeEventListener('storage', listenVncConnected);
  }
});
</script>

<template>
  <template v-if="!webStyle || webStyle === WebStyleType.DEFAULT">
    <div class="quick-access background" :class="{'is-safari': browserType.browser === 'safari'}">
      <span v-t="'HOME_QUICKACCESS'" class="title"></span>
      <div class="operation-content">
        <div
          v-for="access in accesses"
          v-show="access.show"
          :key="access.id"
          class="operation-content-demo"
          :style="
            'width:calc((100% - ' + (accesses.length - 1) * 16 + 'px) / ' + accesses.length + ')'
          "
        >
          <div
            :id="'homeQuickAccess' + access.id"
            :class="{ 
              'icon-disabled': (access.lock && systemLockDownEnabled) || access.disable,
              'home-quick-access-small': resolution === Resolution.SMALL,
              'home-quick-access': resolution !== Resolution.SMALL
            }"
            @click="clickFn(access)"
          >
            <el-icon :size="24" class="quick-access-icon">
              <IconUser v-if="access.id === 'LocalUser'" />
              <i v-else :class="access.imgClass" />
            </el-icon>
            <span v-t="access.title" :title="$t(access.title)"></span>
          </div>
        </div>
      </div>
    </div>
  </template>
  <template v-if="webStyle === WebStyleType.STANDARD">
    <div class="standard-style quick-access background">
      <span v-t="'HOME_QUICKACCESS'" class="title"></span>
      <div class="operation-content">
        <div
          v-for="access in accesses"
          v-show="access.show"
          :key="access.id"
          class="operation-content-demo"
        >
          <div
            :id="'homeQuickAccess' + access.id"
            :class="{ 
              'icon-disabled': (access.lock && systemLockDownEnabled) || access.disable,
              'home-quick-access-small': resolution === Resolution.SMALL,
              'home-quick-access': resolution !== Resolution.SMALL
            }"
            @click="clickFn(access)"
          >
            <el-icon :size="24" class="quick-access-icon">
              <IconUser v-if="access.id === 'LocalUser'" class="standard-style" />
              <i v-else :class="access.imgClass" class="standard-style" />
            </el-icon>
            <span v-t="access.title" :title="$t(access.title)"></span>
          </div>
        </div>
      </div>
    </div>
  </template>
  <template v-if="webStyle === WebStyleType.IBMA">
    <div class="ibma-style quick-access background">
      <span v-t="'HOME_QUICKACCESS'" class="title"></span>
      <div class="operation-content">
        <div
          v-for="access in accesses"
          v-show="access.show"
          :key="access.id"
          class="operation-content-demo"
          :style="
            'width:calc((100% - ' + (accesses.length - 1) * 16 + 'px) / ' + accesses.length + ')'
          "
        >
          <div
            :id="'homeQuickAccess' + access.id"
            :class="{
              'icon-disabled': (access.lock && systemLockDownEnabled) || access.disable,
              'home-quick-access-small': resolution === Resolution.SMALL,
              'home-quick-access': resolution !== Resolution.SMALL
            }"
            @click="clickFn(access)"
          >
            <el-icon :size="24" class="quick-access-icon">
              <IconUser v-if="access.id === 'LocalUser'" class="ibma-style" />
              <i v-else :class="access.imgClass" class="ibma-style" />
            </el-icon>
            <span v-t="access.title" :title="$t(access.title)"></span>
          </div>
        </div>
      </div>
    </div>
  </template>
  <template v-if="webStyle === WebStyleType.SIMPLE">
    <div class="simple-style quick-access background">
      <span v-t="'HOME_QUICKACCESS'" class="title"></span>
      <div class="operation-content">
        <div
          v-for="access in accesses"
          v-show="access.show"
          :key="access.id"
          class="operation-content-demo"
          :style="
            'width:calc((100% - ' + (accesses.length - 1) * 16 + 'px) / ' + accesses.length + ')'
          "
        >
          <div
            :id="'homeQuickAccess' + access.id"
            :class="{ 
              'icon-disabled': (access.lock && systemLockDownEnabled) || access.disable,
              'home-quick-access-small': resolution === Resolution.SMALL,
              'home-quick-access': resolution !== Resolution.SMALL 
            }"
            @click="clickFn(access)"
          >
            <el-icon :size="24" class="quick-access-icon">
              <IconUser v-if="access.id === 'LocalUser'" class="simple-style" />
              <i v-else :class="access.imgClass" class="simple-style" />
            </el-icon>
            <span v-t="access.title" :title="$t(access.title)"></span>
          </div>
        </div>
      </div>
    </div>
  </template>
  <template v-if="webStyle === WebStyleType.BEAUTIFUL">
    <div
      :class="{
        'beautiful-sm-style': resolution === Resolution.SMALL,
        'beautiful-mid-style': resolution !== Resolution.SMALL
      }"
      class="quick-access background"
    >
      <span v-t="'HOME_QUICKACCESS'" class="title"></span>
      <div class="operation-content">
        <div
          v-for="access in accesses"
          v-show="access.show"
          :key="access.id"
          class="operation-content-demo"
        >
          <div
            :id="'homeQuickAccess' + access.id"
            :class="{
              'icon-disabled': (access.lock && systemLockDownEnabled) || access.disable,
              'home-quick-access-small': resolution === Resolution.SMALL,
              'home-quick-access': resolution !== Resolution.SMALL 
            }"
            @click="clickFn(access)"
          >
            <el-icon :size="24" class="quick-access-icon">
              <IconUser v-if="access.id === 'LocalUser'" class="beautiful-style" />
              <i v-else :class="access.imgClass" class="beautiful-style" />
            </el-icon>
            <span v-t="access.title" :title="$t(access.title)"></span>
          </div>
        </div>
      </div>
    </div>
  </template>

  <Dialog ref="dialogRef" :config="dialogConfig" @close="dialogClose">
    <template v-if="dialogConfig.id === 'restoreModel'" #other>
      <div class="reset-dialog">
        <el-icon :size="24">
          <IconAlarm />
        </el-icon>
        <div class="reset-content">
          <p class="accessResetModal" id='accessResetModal'>
            {{ traduction('HOME_CONFIRM_UPGRADE2', { softwareName: productLabel }) }}
          </p>
          <p id='restoreDefaults'>{{ traduction('HOME_RESTOREDDEFAULTS') }}</p>
          <p 
            v-if="props.ipAdress.ipVersion !== IPVersionType.IPV6_ONLY" 
            id='IPv4Address'
          >
            {{ props.ipAdress.addressIPv4 }}
          </p>
          <p 
            v-if="props.ipAdress.ipVersion !== IPVersionType.IPV4_ONLY"
            id='IPv6Address'
          >
            {{ props.ipAdress.addressIPv6 }}
          </p>
        </div>
      </div>
    </template>
  </Dialog>
  <SecondPassword ref="secondRef" @close="confirmReset" />
  <CollectProgress
    v-if="collectVisible"
    :state="collectState"
    @progress-close="progressClose"
  ></CollectProgress>
</template>

<style lang="scss" scoped>
.quick-access {
  margin: 16px 24px 0 24px;
  padding: 24px;

  &.is-safari {
    height: 200px;
    flex: 0 0 auto;
  }
}
.operation-content {
  margin-top: 21px;
  display: flex;
}

.operation-content-demo {
  display: inline-block;
  min-height: 56px;
  margin-right: 16px;
  border: 1px solid var(--o-border-color-lighter);
  border-radius: 4px;
  cursor: pointer;
  .el-icon {
    color: var(--o-text-color-tertiary);
  }
  &:hover {
    border: 1px solid var(--o-color-primary-secondary);
    .el-icon {
      color: var(--o-color-primary-secondary);
    }
    span {
      color: var(--o-color-primary-secondary);
    }
  }
  &:last-child {
    margin-right: 0;
  }
}
.beautiful-style {
  color: #485cc7;
}
.simple-style {
  color: var(--o-text-color-tertiary);
}
.ibma-style {
  color: #163a94;
}
.standard-style {
  color: #1d7ddf;
}
.quick-access-icon {
  margin-right: 24px;
  margin-left: 32px;
}

.home-quick-access {
  display: flex;
  min-height: 56px;
  font-size: 16px;
  color: var(--o-text-color-secondary);
  letter-spacing: 0;
  align-items: center;
  line-height: 24px;
}
.home-quick-access-small {
  display: flex;
  align-items: flex-start;
  min-height: 56px;
  font-size: 16px;
  color: var(--o-text-color-secondary);
  letter-spacing: 0;
  line-height: 24px;
  padding: 16px 16px 16px 0;
  .quick-access-icon {
    margin-left: 16px;
    margin-right: 8px;
    font-size: 24px !important;
  }
}

.icon-disabled {
  cursor: not-allowed;
}

.reset-content {
  margin-left: 16px;
}

.reset-dialog {
  display: flex;
}

.standard-style {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;

  .operation-content {
    display: flex;
    flex-wrap: wrap;
    margin-top: 0px;
    .operation-content-demo {
      flex-basis: 31.69%;
      margin-top: 16px;
      margin-right: 16px;
      &:nth-child(3n) {
        margin-right: 0px;
      }
      .quick-access-icon {
        margin-right: 16px;
      }
    }
  }
}

.ibma-style {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
  .operation-content-demo {
    border-radius: 4px;
    border: none;
    background: var(--o-bg-color-light);
  }
  .operation-content{
    display: flex;
    height: calc(100% - 51px);
    .operation-content-demo{
      height: 100%;
    }
  }
}

.simple-style {
  padding: 0;
  margin: 0;
  width: 100%;
}

.beautiful-mid-style {
  padding: 0;
  margin: 0;
  width: 100%;
  .operation-content {
    display: flex;
    flex-wrap: wrap;
    margin-top: 0px;
    .operation-content-demo {
      flex-basis: 44.7%;
      margin-top: 16px;
      margin-right: 16px;
      background: var(--o-bg-color-light);
      border: none;

      .home-quick-access {
        flex-direction: column;
        border-radius: 4px;
        font-size: 12px;
        .quick-access-icon {
          margin: 16px 0px 7px 0px;
        }
        span {
          margin-bottom: 15px;
          text-align: center;
        }
      }
    }
  }
}

.beautiful-sm-style {
  padding: 0;
  margin: 0;
  width: 100%;
  .quick-access-icon {
    margin-right: 8px;
    margin-left: 16px;
  }
  .operation-content{
    height: calc(100% - 47px);
  }
  .operation-content-demo {
    height: 100%;
    display: inline-flex;
    width: calc((100% - 100px) / 6);
    background: var(--o-bg-color-light);
    border: none;
  }
}
</style>
