/**
 * 2022年7月19日
 * 钟是志
 * 一站式接口为了应付北电科的鉴权 按欢哥搞的 把接口地址进行一次转换
 * 禅道 28321 一站式接口越权处理
 * */

import { getToken } from '@/webPublic/one_stop_public/utils/getToken';
import { isJSON } from '@/webPublic/one_stop_public/2022beidianke/isJSON';
import { strToBinary } from '@/webPublic/one_stop_public/Base16/strToBinary';
import { binaryToStr } from '@/webPublic/one_stop_public/Base16/binaryToStr';
import { getUrlInfo } from '@/webPublic/one_stop_public/DetailForAudit/utils';
import md5 from 'js-md5';

const urlInfo = getUrlInfo();
if(!!urlInfo.visitor){
  sessionStorage.setItem('visitor_client', JSON.stringify(true));
}
const isTest = urlInfo.test;
const visitor_client = sessionStorage.getItem('visitor_client') === 'true';


function getApi(apiUrl) {
  const token = getToken();
  const data = {
    url: apiUrl,
  };
  if((!token || token.length < 11) && visitor_client){
    data.client = 'client_' + md5(navigator.appVersion); // 访客模式
  }else{
    data.token = token;
  }

  const datasCode = strToBinary(JSON.stringify(data));
  let file = new File([datasCode], 'fileParams.jpeg', {
    type: 'image/jpeg',
  });

  let datasTrue = {
    fileParams: file,
    bin: true,
    rbin: true,
    // token: getToken(),
  };
  const formData = new FormData();
  for (let key in datasTrue) {
    formData.append(key, datasTrue[key]);
  }
  return fetch(window.CONFIG.API_ACTION_PATH + '/safe/pub/getApis', {
    headers: {
      Accept: 'application/json',
    },
    method: 'POST',
    credentials: 'omit',
    mode: 'cors',
    body: formData,
  })
    .then((res) => {
      return res.json();
    }).then((res) => {
      if (res.rbin && isJSON(binaryToStr(res.rbin))) {
        const u = JSON.parse(binaryToStr(res.rbin)).url;
        const newUrl = window.CONFIG.API_ACTION_PATH + '/apis/' + md5(u);
        setLocalStorageTransformApi(apiUrl, u); // 存入缓存
        return {
          transformApi: newUrl,
          headersApi: u,
        };
      } else {
        return false;
      }
    });
}


function getLocalStorageTransformApi(api = '') {
  const storage = localStorage.getItem('oneStopTransformApi');
  if (storage && isJSON(storage)) {
    let d = JSON.parse(storage);
    return d;
  } else {
    return {};
  }
}

function setLocalStorageTransformApi(api = '', transformApi = '') {
  let t = getToken();
  // if((!t || t.length < 11) &&  visitor_client){
  //   t = md5(navigator.appVersion);
  // }
  let old = getLocalStorageTransformApi();
  if (old[t]) {
    old[t][api] = transformApi;
  } else {
    old = {};
    old[t] = {};
    old[t][api] = transformApi;
  }
  localStorage.setItem('oneStopTransformApi', JSON.stringify(old));
}


export async function getTransformApi(url) { //
  let apiUrl = '';
  let needTransform = true;
  const t = getToken();
  const TRANSFORM_BIN = window.CONFIG?.TRANSFORM_BIN;
  if(!TRANSFORM_BIN){
    needTransform = false;
  }
  if (needTransform && url && typeof url === 'string' && url.indexOf('/onestop') > -1 && url.includes(window.CONFIG.API_ACTION_PATH)) {
    apiUrl = url.replace(window.CONFIG.API_ACTION_PATH, '');
  } else {
    return new Promise((resolve, reject) => {
      resolve({
        transformApi: url,
        headersApi: undefined,
      });
    });
  }
  if (!visitor_client && (!t || t.length < 11 || !needTransform)) { // 没有token 或者没有开启二进制加密 且不是访客模式 直接返回
    return new Promise((resolve, reject) => {
      resolve({
        transformApi: url,
        headersApi: undefined,
      });
    });
  } else {
    const storage = getLocalStorageTransformApi();
    if(storage && storage[t] && storage[t][apiUrl]){
      return new Promise((resolve) => {
        const apis = storage[t][apiUrl];
        resolve({
          transformApi: window.CONFIG.API_ACTION_PATH + '/apis/' + md5(apis),
          headersApi: apis,
        })
      });
    }
    return new Promise((resolve) => {
        return getApi(apiUrl).then((g) => {
          resolve({
            transformApi: g.transformApi,
            headersApi: g.headersApi,
          });
        });
    });
  }
}
