import { isJSON } from '../authority';

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 encryptApiList = [
  {
    api: 'DataColumnApi/getOptions',
    key: ['filterSql'],
  },
  {
    api: 'DataColumnApi/getLabels',
    key: ['allValues'],
    filterEmpty: ['allValues'],
    setNull: true,
  },
  {
    api: 'DataColumnApi/getSqlOptions',
    key: ['allValues'],
    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/getFormDataPage',
    key: ['sql', 'custom'],
    filterEmpty: ['sql', 'custom'],
  },
  {
    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'],
  },
];

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);
            // 循环中 不要写await 为什么?
            // https://www.bilibili.com/video/BV1G5411o73g
            datas = giveKey('allValues', datas);
          } else {

            datas = giveKey(g, datas);
          }

        }
        return datas;
      }
    }
  }
  return datas;
}
