/** @module utils/post */
/* eslint-disable no-param-reassign */
import _ from 'lodash';
import { fetch } from './polyfill';
import { encrypt } from './helper';
import { checkStatus, normParams, parseObject } from './http-helper';
import { getToken } from './auth';
import { errors } from './error';

const defaultOptions = {
  timeout: 30 * 1000,
  headers: {
    Accept: 'application/json',
  },
};

/**
 * post方法
 * @param {string} url 地址
 * @param {Object} data body中的数据
 * @param {Object} params
 * @param {Object} options
 * @param {boolean} auth
 * @returns {Promise.<*>}
 */
export default async function post(url, data, params = {}, options = {}, auth = true) {
  if (!data) {
    data = {};
  }
  if (auth) {
    const token = await getToken();
    if (!token) {
      return Promise.reject(errors.tokenMissing());
    }
    data.token = encrypt(token);
  }
  let queryParams = normParams(params);
  queryParams = queryParams.map(([k, v]) => (_.isNil(v) ? k : `${k}=${encodeURIComponent(v)}`));
  queryParams = queryParams.join('&');
  let realUrl = url;
  if (queryParams) {
    realUrl = `${url}?${queryParams}`;
  }
  const realOptions = _.defaults(options, defaultOptions);
  if (!realOptions.headers) {
    realOptions.headers = {
      Accept: 'application/json',
    };
  }
  realOptions.headers['Content-Type'] = 'application/json';
  realOptions.method = 'POST';
  realOptions.body = JSON.stringify(data);
  return fetch(realUrl, realOptions)
    .then(checkStatus)
    .then(parseObject);
}
