import { getToken, isJSON } from '../authority';
import request from '../request';
import { getHeaders } from '../2022new/getHeaders';
import { Toast } from 'antd-mobile';
import { binaryToStr } from './binaryToStr';
import { getUserInfo } from '../2022new/currentUser';
import { strToBinary } from './strToBinary';
import encryptApiList ,{ resBinaryApiList } from './encryptApiList';
const baseX = require('./basx-x');

var BASE16 = '0123456789abcdef';
var bs16 = baseX(BASE16);

export function apiRequest(url, params = {}) {
  return giveBase16EnCode(params, url).then((data) => {
    return request(window.location.origin + '/produce/v1/api/onestop' + url, {
      method: 'POST',
      body: data,
    }, { enableLoading: true, handle401Path: './CollegeYongthLeague/IndexPage' });
  })
}

function checkOpenBase16() {
  const is_open_base14 = sessionStorage.getItem('is_open_base16')
    ? JSON.parse(sessionStorage.getItem('is_open_base16'))
    : false;
  return is_open_base14;
}

export function Base16Encode(value) {
  const is_open_base14 = checkOpenBase16();
  if (is_open_base14) {
    if (!value) {
      return null;
    } else {
      let newV = new Buffer(value); // 快
      const r = bs16.encode(newV); // 慢
      return r;
    }
  }
  return value;
}

const giveKey = (key, datas) => {
  if (datas && datas[key]) {
    datas[key] = Base16Encode(datas[key]);
  }
  return datas;
};






const countAllValues = async (datas, item) => {
  if (item.setNull) {
    datas.allValues = JSON.stringify({});
  } else {
    if (item.query) {
      if (datas?.sqlKey.length < 13) {
        const response = await apiRequest('/SqlManageEntityApi/findParamsKey', { sqlKey: datas.sqlKey });
        if (!response || (Array.isArray(response) && response.length === 0)) {
          datas.allValues = JSON.stringify({});
        } else {
          const x = isJSON(datas.allValues) && JSON.parse(datas.allValues) || {};
          const y = {};
          for (let i of response) {
            if (x[i]) {
              y[i] = x[i];
            }
            datas.allValues = JSON.stringify(y);
          }
        }
      } else {
        datas.allValues = JSON.stringify({});
      }
    }
  }
  return datas;
};


export async function giveBase16EnCode(datas, url) { // 全局加解密函数.
  if (!checkOpenBase16()) {
    return datas;
  }
  if (url && typeof url === 'string') {
    for (let item of encryptApiList) {
      if (url.indexOf(item.api) > -1) {
        for (let g of item.key) {
          if (g === 'allValues' && typeof datas[g] !== 'undefined') {
            datas = await countAllValues(datas, item);
            datas = giveKey('allValues', datas);
          } else {

            datas = giveKey(g, datas);
          }

        }
        return datas;
      }
    }
  }
  return datas;
}
export async function giveFilePostData(datas, url) {
  for (let i in datas) {
    if (
      datas[i] === null ||
      (Array.isArray(datas[i]) && datas[i].length === 0) ||
      datas[i] === undefined
    ) {
      delete datas[i];
    }
  }
  if (url && typeof url === 'string') {
    for (let item of encryptApiList) {
      if ((window.CONFIG?.ALLBIN && url.indexOf('/onestop/') > -1) || url.indexOf(item.api) > -1) {
        const roleGroup = getUserInfo().groupsId;
        if (url.indexOf('http') > -1) {
          url = url.replace('/onestop/', `/onestop/safe/${roleGroup}/`);
        } else {
          url = url.replace(url, `/safe/${roleGroup}/` + url);
          url = url.replaceAll('//', '/');
        }
        datas = await countAllValues(datas, item);
        return new Promise((resolve, reject) => {
          resolve({
            datas: formatDatas(datas, url),
            url,
          });
        });
      }
    }
  }
  return new Promise((resolve, reject) => {
    resolve(datas);
    return datas;
  });
}

let time = new Date().getTime();

export const qqCw = ({
                       title = '请求错误',
                       msg = '',
                       customErrMsg = '',
                     }) => {
  let nowX = new Date().getTime() - time;
  if (nowX < 3000) {
    return false;
  }
  time = new Date().getTime();
  // 请求错误 增加自定义错误提示信息 customErrMsg 从发起 接口那里自定义
  // 禅道bug 11794
  Toast.info(title);

  return undefined;
};

export async function requestFileInfo(url, datas) {
  // for (let i = 0; i < 100; i++) {
  //   datas = await testPromise(datas);
  // }
  const formData = new FormData();
  // if (getVisitorToken()) {
  //   datas.token = getVisitorToken();
  // }
  datas.token = getToken();
  for (let key in datas) {
    formData.append(key, datas[key]);
  }
  if (!url || typeof url !== 'string') {
    return false;
  }

  return fetch(url, {
    headers: {
      Accept: 'application/json',
      ...getHeaders().headers,
    },
    method: 'POST',
    credentials: 'omit',
    mode: 'cors',
    body: formData,
  })
    .then((res) => {
      if (res.status === 401) {
        qqCw({
          title: '登录过期401',
          customErrMsg: '登录已过期，请重新登录',
        });
        return false;
      }
      if (res.status === 404) {
        qqCw({
          title: 'http404报错',
          customErrMsg: '请联系系统管理员',
        });
        return false;
      }
      return res.json();
    })
    .then((res) => {
      if (res && typeof res === 'object' && res.rbin) {
        res = binaryToStr(res.rbin);
        if (isJSON(res)) {
          res = JSON.parse(res);
        }
      }
      if (res && res.errCode) {
        qqCw({
          msg: res.errMsg || res.message,
          customErrMsg: res.customErrMsg,
        });
        return false;
      }
      return res;
    });
}


function formatDatas(datas, url = '') {
  if (url && url.indexOf('getSqlData') > -1 && window.smartFormGlobalProps?.data) {
    // 按欢哥的要求 getSqlData 接口要加上appId 参数
    // 解决北电科接口越权的问题.
    datas.appId = window.smartFormGlobalProps?.data.appId || window.smartFormGlobalProps?.data.id;
    console.log('getSqlData,AppId', datas.appId);
  }
  let datasCode = JSON.stringify(datas);
  const openIsBinary = window.CONFIG?.IS_BINARY;

  if (openIsBinary) {
    datasCode = strToBinary(datasCode);
  }
  let file = new File([datasCode], 'fileParams.jpeg', {
    type: 'image/jpeg',
  });

  let datasTrue = {
    fileParams: file,
  };
  if (openIsBinary) {
    datasTrue.bin = true;
    if (window.CONFIG?.ALL_R_BIN) {
      datasTrue.rbin = true;
    } else {
      let findIndexA = resBinaryApiList.findIndex((g) => {
        return url.includes(g.api);
      });
      if (findIndexA >= 0) {
        datasTrue.rbin = true;
      }
    }
  }
  return datasTrue;
}
