//  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 { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { kvmParamInit } from '@/utils/kvm-init.ts';

// Mock 依赖模块
vi.mock('./language', () => ({
  langOptions: [
    { id: 'en', label: 'English' },
    { id: 'zh', label: '简体中文' },
    { id: 'ja', label: '日本語' },
    { id: 'fr', label: 'Français' },
    { id: 'ru', label: 'Русский' },
  ],
}));

vi.mock('@/utils/utils.ts', () => ({
  getLocationSearch: vi.fn(search => {
    const params = {};
    if (search) {
      search
        .replace('?', '')
        .split('&')
        .forEach(pair => {
          const [key, value] = pair.split('=');
          if (key) {
            params[key] = value;
          }
        });
    }
    return params;
  }),
  urlStandardization: vi.fn(),
}));

describe('KVM 参数初始化', () => {
  let sessionStorageMock;
  let localStorageMock;

  beforeEach(() => {
    // Mock sessionStorage
    sessionStorageMock = {
      store: {},
      getItem: vi.fn(key => sessionStorageMock.store[key] || null),
      setItem: vi.fn((key, value) => {
        sessionStorageMock.store[key] = value.toString();
      }),
      removeItem: vi.fn(key => {
        delete sessionStorageMock.store[key];
      }),
      clear: vi.fn(() => {
        sessionStorageMock.store = {};
      }),
    };

    // Mock localStorage
    localStorageMock = {
      store: {},
      getItem: vi.fn(key => {
        const value = localStorageMock.store[key];
        return value !== undefined ? value : null;
      }),
      setItem: vi.fn((key, value) => {
        localStorageMock.store[key] = value.toString();
      }),
      removeItem: vi.fn(key => {
        delete localStorageMock.store[key];
      }),
      clear: vi.fn(() => {
        localStorageMock.store = {};
      }),
    };
    vi.stubGlobal('sessionStorage', sessionStorageMock);
    vi.stubGlobal('localStorage', localStorageMock);

    // 设置全局对象, 将sessionStorage, localStorage绑定到self对象上
    vi.stubGlobal('self', {
      sessionStorage,
      localStorage,
      location: {
        search: '',
        pathname: '',
      },
    });

    Object.defineProperty(global, 'location', {
      value: {
        search: '',
        pathname: '',
      },
      writable: true,
      configurable: true,
    });
  });

  afterEach(() => {
    vi.unstubAllGlobals();
    vi.clearAllMocks();
  });

  describe('setKvmSearch', () => {
    it('应该处理 kvmvmm.asp 路径的 Java 模式', () => {
      global.location.pathname = '/kvmvmm.asp';
      global.location.search = '?param=value';
      self.location.pathname = '/kvmvmm.asp';
      self.location.search = '?param=value';
      kvmParamInit();
      expect(sessionStorageMock.setItem).toHaveBeenCalledWith('kvmConnect', '1');
      expect(sessionStorageMock.setItem).toHaveBeenCalledWith('kvmSearch', '?param=value');
      expect(localStorageMock.setItem).toHaveBeenCalledWith('kvmJava', '1');
    });

    it('应该处理 remoteconsole 路径的 HTML5 模式', () => {
      global.location.pathname = '/remoteconsole';
      global.location.search = '?openWay=html5';
      self.location.pathname = '/remoteconsole';
      self.location.search = '?openWay=html5';
      kvmParamInit();
      expect(sessionStorageMock.setItem).toHaveBeenCalledWith('kvmConnect', '1');
      expect(localStorageMock.removeItem).toHaveBeenCalledWith('kvmJava');
    });
  });

  describe('setKvmLanguage', () => {
    it('应该从 localStorage kvmHtml5Info 获取语言', () => {
      // 设置有效的 JSON 数据
      localStorageMock.store.kvmHtml5Info = JSON.stringify({ lp: 'cn', lang: 'zh' });
      localStorageMock.getItem.mockImplementation(key => {
        if (key === 'kvmHtml5Info') {
          return JSON.stringify({ lp: 'cn', lang: 'zh' });
        }
        return null;
      });
      kvmParamInit();
      expect(localStorageMock.setItem).toHaveBeenCalledWith('kvmLocale', 'zh');
    });

    it('应该处理 localStorage 中不存在 kvmHtml5Info 的情况', () => {
      localStorageMock.getItem.mockReturnValue(null);
      kvmParamInit();
      // 不应该设置 kvmLocale
      expect(localStorageMock.setItem).not.toHaveBeenCalledWith('kvmLocale', expect.any(String));
    });

    it('应该从 URL 参数获取语言', async () => {
      global.location.search = '?lp=fr';
      self.location.search = '?lp=fr';
      // Mock getLocationSearch 返回正确的参数
      const module = await import('@/utils/utils.ts');
      module.getLocationSearch.mockReturnValue({ lp: 'fr' });
      kvmParamInit();
      expect(localStorageMock.setItem).toHaveBeenCalledWith('kvmLocale', 'fr');
    });

    it('应该转换 cn 为 zh', async () => {
      global.location.search = '?lp=cn';
      self.location.search = '?lp=cn';
      const module = await import('@/utils/utils.ts');
      module.getLocationSearch.mockReturnValue({ lp: 'cn' });
      kvmParamInit();
      expect(localStorageMock.setItem).toHaveBeenCalledWith('kvmLocale', 'zh');
    });

    it('应该从 SSO 登录信息获取语言', () => {
      localStorageMock.getItem.mockImplementation(key => {
        if (key === 'ssoLoginInfo') {
          return JSON.stringify({});
        }
        if (key === 'locale') {
          return 'zh-CN';
        }
        return null;
      });
      kvmParamInit();
      expect(localStorageMock.setItem).toHaveBeenCalledWith('kvmLocale', 'zh');
      expect(localStorageMock.removeItem).toHaveBeenCalledWith('locale');
    });
  });
});
