import baseX from 'base-x';

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

export function Base16Encode(value) {
  let is_open_base14 = sessionStorage.getItem('is_open_base16')
    ? JSON.parse(sessionStorage.getItem('is_open_base16'))
    : false;
  if (is_open_base14) return value ? bs16.encode(new Buffer(value)) : null;
  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'],
  },
  {
    api: 'DataColumnApi/getSqlOptions',
    key: ['allValues'],
  },
  {
    api: 'DataColumnApi/getSqlLabels',
    key: ['allValues'],
  },
  {
    api: 'DataColumnApi/getSqlData',
    key: ['allValues', 'sqlKey'],
  },
  {
    api: 'DataRightApi/add',
    key: ['filterSql'],
  },
  {
    api: 'DataRightApi/addBatch',
    key: ['filterSql'],
  },
  {
    api: 'DataObjApi/add',
    key: ['sqlScript'],
  },
  {
    api: 'DataObjApi/getFormDataList',
    key: ['custom'],
  },
  {
    api: 'DataObjApi/getFormDataPage',
    key: ['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'],
  },
]

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

  return datas;
}
