import encryptApiList, {
  resBinaryApiList,
} from '@/webPublic/one_stop_public/Base16/encryptApiList';
import { getToken, getUserInfo } from '@/webPublic/one_stop_public/utils/token';
import { queryApiActionPath } from '@/webPublic/one_stop_public/utils/queryConfig';
import { qqCw } from '@/webPublic/one_stop_public/utils/request';
import { getHeaders, isJSON } from '@/webPublic/zyd_public/utils/utils';
import { deepCopy } from '@/webPublic/one_stop_public/utils/myutils';
import { countAllValues } from '@/webPublic/one_stop_public/Base16/SplitBase16Index';
import { getUrlInfo } from '@/webPublic/one_stop_public/DetailForAudit/utils';
import { getTransformApi } from '@/webPublic/one_stop_public/2022beidianke/localstorageTransform';
import { strToBinary } from './strToBinary'; // 字符串转二进制 混淆代码
import { binaryToStr } from './binaryToStr';
import { getVisitorToken } from '@/webPublic/zyd_public/utils/getHeaders';
import { replaceAll } from '@/webPublic/one_stop_public/Base16/utils';


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;
  }
  let datasCode = JSON.stringify(datas);
  const openIsBinary = window.CONFIG?.IS_BINARY;

  // if (test) {
  // }

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

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

export async function giveFilePostData(datas, url) {
  const staticS = window.CONFIG.SAFE_TYPE === 2 ? 'safe' : 'safe';
  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/${staticS}/${roleGroup}/`);
          url = url.replace('/onestopapi/', `/onestopapi/${staticS}/${roleGroup}/`);
        } else {
          url = url.replace(url, `/${staticS}/${roleGroup}/` + url);
          url = replaceAll(url, '//', '/');
        }

        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;
  });
}

function testPromise(d) {
  return new Promise((resolve, reject) => {
    resolve(d);
  });
}

export async function requestFileInfo(url, datas) {
  const staticS = window.CONFIG.SAFE_TYPE === 2 ? 'safe' : 'safe';
  // for (let i = 0; i < 100; i++) {
  //   datas = await testPromise(datas);
  // }
  const formData = new FormData();
  if (getVisitorToken()) {
    datas.token = getVisitorToken();
  } else {
    datas.token = getToken();
  }

  if (!url || typeof url !== 'string') {
    return false;
  }

  let trueUrl = url && url.indexOf('http') > -1 ? url : queryApiActionPath() + url;
  const { transformApi, headersApi } = await getTransformApi(trueUrl);
  let urlSafe2 = transformApi;
  if (window.CONFIG.SAFE_TYPE === 2) {
    urlSafe2 = transformApi.split('/');
    let findSafeIndex = urlSafe2.findIndex(g => g === staticS);
    if (findSafeIndex >= 1) {
      let path = urlSafe2.slice(findSafeIndex + 2).join('/');
      urlSafe2 = urlSafe2.slice(0, findSafeIndex + 2).join('/');
      datas.path = '/' + path;
    }
  }

  for (let key in datas) {
    formData.append(key, datas[key]);
  }
  return fetch(urlSafe2, {
    headers: {
      Accept: 'application/json',
      ...getHeaders(transformApi).headers,
      ContentType: 'multipart/form-data',
      // apis: headersApi,
      // axxx: `select * from user123 where id = 1`,
    },
    method: 'POST',
    credentials: 'include',
    // 2023年11月28日 顺哥说的 延职 要传成 include;
    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;
      }

      // if (test) {
      // 	console.log({
      // 		url,
      // 		res,
      // 	});
      // }

      return res;
    });
}

export function giveFilePostDataInfoForTrue(datas, url) {
  const staticS = window.CONFIG.SAFE_TYPE === 2 ? 'safe' : 'safe';
  if (!window.CONFIG?.IS_SAFE) {
    return {
      datas,
      url,
    };
  }
  datas = deepCopy(datas);
  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) {
    const roleGroup = getUserInfo().groupsId;
    if (url.indexOf('http') > -1) {
      url = url.replace('/onestop/', `/onestop/${staticS}/${roleGroup}/`);
      url = url.replace('/onestopapi/', `/onestopapi/${staticS}/${roleGroup}/`);
    } else {
      url = url.replace(url, `/${staticS}/${roleGroup}/` + url);
      url = replaceAll(url, '//', '/');
    }
    return {
      datas: formatDatas(datas, url),
      url,
    };
  }
}
