import baseX from 'base-x';
import { apiRequest } from '../utils/request';
import { isJSON } from '@/webPublic/zyd_public/utils/utils';
import { uploadFile } from '@/webPublic/one_stop_public/libs/PictureSignature/ShowItem';
import { queryApiActionPath, queryIsSafe } from '@/webPublic/one_stop_public/utils/queryConfig';
import { getToken, getUserInfo } from '@/webPublic/one_stop_public/utils/token';

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

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 encryptApiList = [
  {
    api: 'DataColumnApi/getOptions',
    key: ['filterSql'],
  },
  {
    api: 'UnifiedServicePatternApi/updateForm',
  },
  {
    api: 'DataColumnApi/getLabels',
    key: ['allValues'],
    filterEmpty: ['allValues'],
    setNull: true, // 置空这个字段
  },
  {
    api: 'DataColumnApi/getSqlOptions',
    key: ['allValues', 'sqlKey'],
    filterEmpty: ['allValues'],
    query: true, // 调另外一个接口查询这个的替换值
  },
  {
    api: 'DataColumnApi/getSqlLabels',
    key: ['allValues'],
    filterEmpty: ['allValues'],
    query: true,
  },
  {
    api: 'DataColumnApi/getSqlData',
    key: ['allValues', 'sqlKey'],
    filterEmpty: ['sqlKey'],
    query: true,
  },
  {
    api: 'DataColumnApi/getSqlColumn',
    key: ['json'],
  },
  {
    api: 'DataRightApi/add',
    key: ['filterSql'],
    // filterEmpty: ['filterSql'],
  },
  {
    api: 'DataRightApi/addBatch',
    key: ['filterSql'],
  },
  {
    api: 'DataObjApi/add',
    key: ['sqlScript'],
  },
  {
    api: 'DataObjApi/getFormDataList',
    key: ['custom'],
  },
  {
    api: 'DataObjApi/exportWord',
    key: ['params'],
  },
  {
    api: 'DataObjApi/getFormDataPage',
    key: ['sql', 'custom'],
    filterEmpty: ['sql', 'custom'],
    yinShe: {
      sql: 's',
      query: 'chaxun',
      querys: 'chaxuns',
      sorter: 'paixu',
      orders: 'paixus',
    },
  },
  {
    api: 'UserApi/getPage',
    key: ['addSignSql'],
  },
  {
    api: 'UnifiedAppFormApi/examineProcess',
    key: ['taskForm'],
  },
  {
    api: 'UnifiedAppFormApi/saveDraft',
    key: ['content'],
  },
  {
    api: 'UnifiedAppFormApi/startProcess',
    key: ['content'],
  },
  {
    api: 'UnifiedAppFormApi/startProcessByService',
    key: ['content'],
  },
  {
    api: 'UnifiedAppFormApi/getHandleUser',
    key: ['content'],
  },
  {
    api: 'SqlManageEntityApi/findParamsKey',
    key: ['sqlKey'],
  },
  {
    api: 'UnifiedServiceApi/config', // 禅道 25034 宿舍管理/宿舍维修审核，2021030576L 加个字段 做个字段排序
    key: ['config'],
  },
];

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 function requestFileInfo(url, datas){
  const formData = new FormData();
  if(getToken()){
    datas.token = getToken();
  }
  for(let key in datas){
    formData.append(key, datas[key]);
  }
  return fetch(queryApiActionPath() + url, {
    headers: {
      Accept: 'application/json',
      // Authorization: `bearer ${getToken()}`,
    },
    method: 'POST',
    credentials: 'omit',
    mode: 'cors',
    body: formData,
  }).then((res) => {
    return res.json();
  }).then((res) => {
    // console.log(res);
    return res;
  });
}


function giveFilePostData(datas, url){
  url = url.replaceAll('\/\/', '\/');
  if (url && typeof url === 'string') {
    // const roleGroup = getUserInfo().groupsId;
    // url = url.replace(url, `/safe/${roleGroup}/` + url);
    // url = url.replaceAll('//', '/');
    // console.table({datas, url});
    // let file = new File([JSON.stringify(datas)], "fileParams.txt", {
    //   type: "text/plain",
    // });
    // datas = {
    //   fileParams: file,
    // }
    // return new Promise((resolve, reject) => {
    //   resolve({
    //     datas,
    //     url,
    //   });
    // });
    for (let item of encryptApiList) {
      if (url.indexOf(item.api) > -1) {
        const roleGroup = getUserInfo().groupsId;
        url = url.replace(url, `/safe/${roleGroup}/` + url);
        url = url.replaceAll('//', '/');

        console.table(datas);
        let file = new File([JSON.stringify(datas)], "fileParams.jpg", {
          type: "text/plain",
        });
        // uploadFile(file);
        datas = {
          fileParams: file,
        }
        return new Promise((resolve, reject) => {
          resolve({
            datas,
            url,
          });
        });

      }
    }
  }
  return new Promise((resolve, reject) => {
    resolve(datas);
    return datas;
  });
}


export async function giveBase16EnCode(datas, url) { // 全局加解密函数.
  if(queryIsSafe()){
    return giveFilePostData(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 (datas[g] && item.filterEmpty && item.filterEmpty.includes(g)) {
            // 压缩代码功能暂时屏蔽
            /***
             // console.log(datas[g]);
             // console.log('%c加密数据压缩前字段' +  g + '= ', 'color: red;');
             // console.log('%c'+ datas[g] , 'color: red;');
             // datas[g] = datas[g].replace(/\r/g, ' ').replace(/\t/g, ' ').replace(/\n/g, ' ').replace(/\s\s+/g, ' ');
             // console.log('%c加密数据压缩后字段' +  g + '= ', 'color: orange;');
             // console.log('%c'+ datas[g] , 'color: orange;');
             ***/
          }

          if (g === 'allValues' && typeof datas[g] !== 'undefined') {
            datas = await countAllValues(datas, item); // 循环中 不要写await
            datas = giveKey('allValues', datas);
          } else {
            // console.log(g, datas);
            datas = giveKey(g, datas);
          }
        }

        if (item.yinShe) { // 映射参数字段.
          datas.isBase = true;
          for (let oldKey in item.yinShe) {
            let newKey = item.yinShe[oldKey];
            // if(typeof datas[oldKey] !== 'undefined'){
            datas[newKey] = datas[oldKey];
            delete datas[oldKey];
            // }
          }
        }
        return datas;
      }
    }
  }
  return datas;
}


