//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { createApp } from 'vue';
import App from './App.vue';
import { setColors } from './model/colors';
import router from './apps/app-bmc/router';
import { clearDirective } from '@/directive/inputDirective';
import { addIdDirective } from '@/directive/addIdDirective';
import { mouseEventDirective } from '@/directive/mouseEventDirective';
import { reqKeepAliveDerective } from '@/directive/reqKeepAlive';
import { createPinia } from 'pinia';

import './assets/common/style/common/common.scss';
import './assets/common/style/common/layout.scss';
import './assets/common/style/custom/zh-CN.scss';
import './assets/common/style/custom/en-US.scss';
import './assets/common/style/custom/ja-JA.scss';
import './assets/common/style/custom/fr-FR.scss';
import './assets/common/style/custom/ru-RU.scss';

// element-plus 部分组件需要单独引入样式（Loading、Message、 Notification）
import 'element-plus/es/components/message/style/css';
import 'element-plus/es/components/message-box/style/css';
import 'element-plus/es/components/notification/style/css';
import '@computing/opendesign2/themes/css/index.css';
// 导入图标字体
import './static/style/icon-font.css';
import './static/style/html5-font.css';
import './static/style/icon-alarm.css';
import './static/style/home-font.css';
import './static/style/style.css';
import './static/style/keyboard-virtual-font.css';
import './static/style/icon-caps-lock.css';
// 自定义 全局样式
import '@/assets/common/style/common/custom-global-style.scss';

import i18nInstance from './utils/i18n-init';
import $http from './utils/http-service';
import * as echarts from 'echarts/core';
import { getLoginInfo, getStyleConfig, getStyleInfo, changeColor } from './utils/common-api';
import { saveI18nInstance, setLangData } from './utils/language';
import { WarningFilled, Close } from '@element-plus/icons-vue';
import { getStoreData, setStoreData, setThemeStoreData } from './utils/composition';
import { privilDirective } from './directive/privilDirective';
import { kvmParamInit } from './utils/kvm-init';
import CustomizeService from './services/customize/customize.service';
import { setCircles } from './model/echartsCircles';
import { getThemeMode } from './utils/utils';

/**
 * ElementUI-plus兼容性支持
 * Edge>=79, FireFox>=78, Chrome>=64, Safari>=12
 */

/**
 * 1. 国际化的用法，template里面请使用  v-t="IBMC_COMMON_OK" 或者 {{$t('IBMC_COMMON_OK')}}
 * 2. TS代码里，若在setUp函数中(这里不能使用this)，先导入 import { useI18n } from 'vue-i18n'; 然后可以使用 useI18n()方法来获取国际化对象信息，
 *    再使用useI18n().t('COMMON_OK')
 * 3. 如果写在method方法里面，则可以使用 this.$t 来获取国际化对象信息, 使用 this.$t('IBMC_COMMON_OK')来获取国际化字段信息
 */
document.cookie = `tiny_language=0;expires=${new Date(1970, 0, 1)}`;
kvmParamInit();

async function getLogin() {
  const result = await getLoginInfo();
  setStoreData('loct', 'sn', result.data.SoftwareName);
  document.title = `${result.data.SoftwareName} ${window.location.hostname}`;
  return result;
}

async function getWebStyle() {
  return await getStyleInfo();
}

const app = createApp(App);
const pinia = createPinia();
app.use(pinia);

if (getStoreData('loct', 'rn')) {
  $http.keepAlive('Activate');
}

// 初始化localstorage中的主题
setStoreData('loct', 'systemTheme', getThemeMode());

function bindingApp() {
  // 绑定全局自定义指令
  clearDirective(app);
  addIdDirective(app);
  privilDirective(app);
  mouseEventDirective(app);
  reqKeepAliveDerective(app);

  i18nInstance.global.locale.value = getStoreData('loct', 'locale');
  saveI18nInstance(i18nInstance);
  app.component('WarningFilled', WarningFilled);
  app.component('CloseIcon', Close);
  app.use(router).use(i18nInstance).mount('#app');
}

Promise.all([getLogin(), getWebStyle(), getStyleConfig()]).then(resArr => {
  const res = resArr[0];
  const webStyle = resArr[1];
  let styleConfig = resArr[2];
  const customService = new CustomizeService();
  let isCustomizeToolConfig = false;

  let useLocal =
    (styleConfig === null ||
    (Object.prototype.toString.call(styleConfig) === '[object Object]' &&
      Object.keys(styleConfig).length === 0)) &&
    webStyle?.pageStyle === 'default';
  if (useLocal) {
    const customConfig = localStorage.getItem('customizeStyle');
    if (customConfig) {
      styleConfig = JSON.parse(customConfig);
      isCustomizeToolConfig = true;
    }
  }

  // 定制化配置相关, 由于刷新后document会恢复，所以只要文件存在，都需要设置一把
  if (styleConfig || webStyle) {
    customService.initCustomize(webStyle, styleConfig, isCustomizeToolConfig);
    if (styleConfig && (Object.prototype.toString.call(styleConfig) === '[object Object]' &&
    Object.keys(styleConfig).length !== 0)) {
      setThemeStoreData(styleConfig);
    } else if (webStyle.pageStyle === undefined || webStyle.pageStyle === 'default') {
      setThemeStoreData(webStyle);
    } else {
      setThemeStoreData(webStyle);
      changeColor(webStyle.pageStyle);
    }
  }

  // 根据主题颜色初始化图表颜色
  setColors();

  // 根据主题设置图表的使用图片
  setCircles();

  // 计算使用的语言和语言列表
  setLangData(res.data.LanguageSet);
  setStoreData('glob', 'webStyle', webStyle.pageStyle || 'default');

  bindingApp();
});

// window.resize的时候如果盒子有被压缩或者拉长，echarts图表resize
window.addEventListener('resize', () => {
  const divList = document.querySelectorAll('div[_echarts_instance_]');
  if (divList.length) {
    divList.forEach((item: any) => {
      const instance = item.getAttribute('_echarts_instance_');
      const chart = echarts.getInstanceById(instance);
      chart?.resize();
    });
  }
});
