const $ = require('jquery');
/**
 * 发送JSON请求
 * @param {*} url 请求地址
 * @param {*} body 请求体
 * @param {*} headers 请求头
 * @param {*} encoding 编码
 */
function postJson(url, body, headers, encoding) {
  let headersObj = {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    body: body,
    encoding: encoding,
  };
  if (Object.prototype.toString.call(headers) === '[object Object]') {
    $.extend(headersObj.headers, headers);
  }
  return request(url, headersObj);
}
function request(url, options) {
  let result = {
    success: false,
    data: '',
    message: '',
  };
  if (Object.prototype.toString.call(options) !== '[object Object]') {
    options = {};
  }
  if (!options.encoding) {
    options.encoding = 'UTF-8';
  }
  return new Promise(function (resolve) {
    if (url.startsWith('https')) {
      const https = require('https');
      let req = https.request(url, options, function (resp) {
        let rawData = '';
        resp.on('data', function (chunk) {
          rawData += chunk; //resp.headers 是否需要根据响应头中的content-type来决定对数据的处理方式?
        });
        //数据接收完成.
        resp.on('end', function () {
          //console.log(`请求地址:${url} 返回:${rawData}`);
          result.success = true;
          result.data = rawData;
          resolve(result);
        });
        //响应错误
        resp.on('error', function (e) {
          result.success = false;
          result.message = e.message;
          resolve(result);
        });
      });
      //请求错误
      req.on('error', function (e) {
        result.success = false;
        result.message = e.message;
        resolve(result);
      });
      //请求超时
      req.on('timeout', function () {
        result.success = false;
        result.message = '请求超时';
      });
      if (options.body) {
        let body = options.body;
        if (
          options.headers &&
          options.headers['content-type'] &&
          options.headers['content-type'].indexOf(
            'application/x-www-form-urlencoded'
          ) >= 0 &&
          Object.prototype.toString(body) == '[object Object]'
        ) {
          body = require('querystring').stringify(body);
        }
        if (
          options.headers &&
          options.headers['content-type'] &&
          options.headers['content-type'].indexOf(
            'application/json'
          ) >= 0 &&
          Object.prototype.toString(body) == '[object Object]'
        ) {
          body = JSON.stringify(body);
        }
        req.write(body, options.encoding);
      }
      req.end();
    } else if (url.startsWith('http')) {
      const http = require('http');
      let req = http.request(url, options, function (resp) {
        let rawData = '';
        resp.on('data', function (chunk) {
          rawData += chunk;
        });
        //数据接收完成.
        resp.on('end', function () {
          //console.log(`请求地址:${url} 返回:${rawData}`);
          result.success = true;
          result.data = rawData;
          resolve(result);
        });
        //响应错误
        resp.on('error', function (e) {
          result.success = false;
          result.message = e.message;
          resolve(result);
        });
      });
      //请求错误
      req.on('error', function (e) {
        result.success = false;
        result.message = e.message;
        resolve(result);
      });
      //请求超时
      req.on('timeout', function () {
        result.success = false;
        result.message = '请求超时';
        resolve(result);
      });
      if (options.body) {
        let body = options.body;
        if (
          options.headers &&
          options.headers['content-type'] &&
          options.headers['content-type'].indexOf(
            'application/x-www-form-urlencoded'
          ) >= 0 &&
          Object.prototype.toString(body) == '[object Object]'
        ) {
          body = require('querystring').stringify(body);
        }
        if (
          options.headers &&
          options.headers['content-type'] &&
          options.headers['content-type'].indexOf(
            'application/json'
          ) >= 0 &&
          Object.prototype.toString(body) == '[object Object]'
        ) {
          body = JSON.stringify(body);
        }
        req.write(body, options.encoding);
      }
      req.end();
    }
  });
}
export { postJson, request };
