//  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 { getStoreData, resetLoctData, setStoreData } from './composition';
import $http from './http-service';
import { updateLocalLoginCount } from './utils';
import useStore from '@/stores';
import { UI_REST_GENERALDOWNLOAD } from '@/api/api';

export function downloadFileWithResponse(res: any, fileName: string) {
  const downloadUrl = window.URL.createObjectURL(res);
  const anchor = document.createElement('a');
  const body = document.getElementsByTagName('body')[0];
  body.appendChild(anchor);
  anchor.setAttribute('style', 'display:none');
  anchor.href = downloadUrl;
  anchor.download = fileName;
  anchor.click();
  window.URL.revokeObjectURL(downloadUrl);
}

export function restDownloadFile(url: string) {
  return new Promise<void>((resolve, reject) => {
    $http.get(url, { responseType: 'blob' }).then(
      response => {
        const fileName = response.headers['content-disposition'].split('=')[1];
        downloadFileWithResponse(response.data, fileName);
        resolve();
      },
      () => {
        reject(new Error());
      },
    );
  });
}

export function generalDownLoadFile(filePath: string) {
  const data = {
    Path: filePath,
    TransferProtocol: 'HTTPS',
  };
  return $http.post(UI_REST_GENERALDOWNLOAD, data, { responseType: 'blob' });
}

// 保存session信息
export function saveSessionData(info: any) {
  setStoreData('loct', 'ur', info.Role);
  setStoreData('loct', 'rn', info.SessionID);
  setStoreData('loct', 'uid', info.UserID);
  setStoreData('loct', 'un', info.UserName);
  setStoreData('loct', 'uip', info.IP);
  setStoreData(
    'loct',
    'utime',
    info.LoginTime ? info.LoginTime.substr(0, 19).replace('T', ' ') : '',
  );
  setStoreData('loct', 'isLogin', true);
  setStoreData('loct', 'isExited', false);
  saveStoreToLocal();
}

// 保存用户权限到 store
export function saveUserPermission(userRole: string[], serverRoleList: any[]) {
  const permissions: any = [];
  serverRoleList.forEach(item => {
    if (userRole.includes(item.Name)) {
      Object.keys(item).forEach(key => {
        if (item[key] && typeof item[key] === 'boolean' && !permissions.includes(key)) {
          permissions.push(key);
        }
      });
    }
  });
  setStoreData('loct', 'privil', permissions);
  saveStoreToLocal();
}

// 超时、退出登录、无权限用户跳转受限路由时，清除相关的登录信息
export function clearCurrentLoginInfo() {
  resetLoctData();
  saveStoreToLocal();
  updateLocalLoginCount('delete');
}

// 将store的数据保存到localStorage
export function saveStoreToLocal() {
  const storeData = useStore().state as any;
  if (storeData) {
    localStorage.setItem('loct', JSON.stringify(storeData.loct.$state)); 
  }
}

// 获取背景图
export function getBackgroundImage() {
  const ptcInfo = localStorage.getItem('ptc');
  const ptcInfoJson = JSON.parse(ptcInfo as string);
  const webStyle = getStoreData('glob', 'webStyle');
  let imgUrl = '';
  if (ptcInfoJson?.login !== undefined) {
    imgUrl = ptcInfoJson.login;
  } else {
    imgUrl = '/extern/custom/login.png';
  }
  return imgUrl;
}

// 获取Logo
export function getLogoImage(postion: string = 'login') {
  const ptcInfo = localStorage.getItem('ptc');
  const ptcInfoJson = JSON.parse(ptcInfo as string);
  const webStyle = getStoreData('glob', 'webStyle');
  let imgUrl = '';
  if (ptcInfoJson?.logo !== undefined) {
    imgUrl = ptcInfoJson.logo;
  } else {
    imgUrl = '/extern/custom/login_logo.png';
  }
  return imgUrl;
}
