/**
 * Created by baoyinghai on 10/18/16.
 */
import Qs from 'qs';
import { trimStart, trimStartAndEnd } from '../utils/StringUtils';
import { getMenuItemByFunc } from '../utils/MenuHelper';
import { getMenu } from '../service/CacheService';
import MxFetch from '../utils/MxFetch';
import Config from '../../config';
import { getRecMenuId, saveEnterMenuId, saveProcessMenuCode } from '../service/SessionStorage';
import { getMenuClobal } from '../service/LocalStorage';

const getHeader = (url, isUpload) => {
  const queryStr = location.href.split('?p=', 2)[1];
  const query = queryStr && Qs.parse(atob(queryStr));
  const menuIds = Object.assign({}, getRecMenuId(), query);
  const menuItem = getMenuItemByFunc(item => (item.actionLink || item.domainLink) === '/' + url, getMenuClobal());
  if (menuItem && menuItem.menuCode) {
    menuIds.enterMenuId = menuItem.menuCode;
    saveEnterMenuId(menuItem.menuCode);
    if (!menuIds.processMenuId && (menuItem.actionLink.indexOf('ApplyList/render') !== -1 || menuItem.actionLink.indexOf('ReviewList/render') !== -1)) {
      saveProcessMenuCode(menuItem.actionLink.indexOf('ApplyList/render') !== -1 ? 'BPMApply.QueryToDo' : 'BPMReview.QueryToDo');
    }
  }
  if (isUpload) {
    return {
      'Accept': 'application/json',
      // 'Authorization': 'Basic  ' + getToken(),
      'MX-MainMenuId': menuIds.enterMenuId,
      'MX-ProcessSubMenuId': menuIds.processMenuId,
    };
  }
  return {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    // 'Authorization': 'Basic  ' + getToken(),
    'MX-MainMenuId': menuIds.enterMenuId,
    'MX-ProcessSubMenuId': menuIds.processMenuId,
  };
};

/* eslint-disable */
const process = _promise => {
  return new Promise((resolve, reject) => {
    _promise.then((response) => response.text())
      .then((response) => {
        if (response === '') {
          resolve({});
        } else {
          let json = null;
          try {
            json = JSON.parse(response);
          } catch(e) {
            reject({ message: '系统异常' });
            console.error('不合法的JSON字符串:', response);
          }
          console.log('返回结果: ', json);
          if (json.msgContent || json.errMsg || json.message || json.code === 'version upgrade' || json.code == 404 || json.code == 500) {
            // ex === 5000 表示需要二次确认
            if (json.ex === 5000) {
              resolve({needConfirm: true, msgContent: json.msgContent});
            } else {
              reject(json);
            }
          } else {
            resolve(json);
          }
        }
      })
      .catch((errorData) => {
        reject(errorData);
      });
  });
};
const rawFetch = (url, param) => {
  /* eslint-disable no-console */
  console.log('=========> 数据请求 <=========');
  console.log('请求地址: ', url);
  console.log('请求参数: ', param);
  // if (url.indexOf('http') < 0) {
  //   url = CbaseProcessUrl + url;
  // };
  // return process(MxFetch.fetch(Config.Host + url, param, 6180));
  return process(MxFetch.fetch(trimStartAndEnd(Config.Host + url), param));
};
/* eslint-disable */
export const PFetch = (url, param) => {
  const headers = getHeader(url);
  return rawFetch(trimStart(url, '/'), {
    method: 'POST',
    headers,
    body: JSON.stringify(param)
  });
};
/* eslint-disable */
export const GFetch = (url, param) => {
  const headers = getHeader(url);
  return rawFetch(url + (param ? '?' + Qs.stringify(param) : ''), {
    method: 'GET',
    headers,
  });
};
// export const FFetch = (url, param) => {
//   const headers = getHeader(url, true);
//   return rawFetch(trimStart(url, '/'), {
//     method: 'POST',
//     headers,
//     body: param
//   });
// };

export const FFetch = options => {
  options.headers = getHeader(options.action, true);
  options.action = Config.Host + trimStart(options.action, '/');
  return process(MxFetch.upload(options));
};


/* eslint-disable */
export const PFetchNoContext = (url, param) => {
  const headers = getHeader(url);
  console.log('=========> 数据请求 <=========');
  console.log('请求地址: ', url);
  console.log('请求参数: ', param);
  // TODO: relative path
  return process(MxFetch.fetch('/' + trimStart(url, '/'), {
    method: 'POST',
    headers,
    body: JSON.stringify(param)
  }));
};

export default {
  PFetch,
  GFetch,
  FFetch,
  PFetchNoContext
  // Upload
};


