const { v4 } =require('uuid');
const moment = require("moment");
const iconvLite = require('iconv-lite');
const querystring = require('querystring');

/**
 * 将一个秒数值转换为  天:时:分:秒 格式
 * @param {*} time 表示秒数
 */
function calcParkingDuration(time) {
  var result = {
    Days: 0,
    Hours: 0,
    Minutes: 0,
    Seconds: 0,
  };
  if (!time) {
    return result;
  }

  var res = '';
  result.Days = Math.floor(time / (24 * 3600));
  time = time % (24 * 3600);

  result.Hours = Math.floor(time / 3600);
  time = time % 3600;

  result.Minutes = Math.floor(time / 60);
  time = Math.floor(time % 60);

  result.Seconds = time;
  return result;
}
/**
 * 将最小单位的金额转换成相应国家的基本单位。
 * @param {*} money
 */
function convertMoney(money, precision, defaultValue) {
  precision = parseInt(precision);
  if (isNaN(precision)) {
    precision = 2;
  }
  if (defaultValue == undefined) {
    defaultValue = 0;
  }
  money = parseFloat(money);
  if (isNaN(money) || money == null) {
    return defaultValue.toFixed(precision);
  }
  return (money / 100).toFixed(precision);
}
/**
 * 序列化JSON对象,并格式化
 * @param {*} jsonObj
 */
function formatJson(jsonObj) {
  return JSON.stringify(jsonObj, ' ', 4);
}
/**
 * 将JSON对象转换为key1=value&key2=value&key3=value形式
 * @param {*} obj
 */
function jsonToQueryString(obj) {
  var toString = Object.prototype.toString;
  if (toString.call(obj) != '[object Object]') {
    return '';
  }
  // var keyValues = [];
  // for (var prop in obj) {
  //     keyValues.push(prop + "=" + obj[prop]);
  // }
  // return keyValues.join("&");

  return querystring.stringify(obj);
}
/**
 * 生成Guid
 * @param {*} style style: 表示Guid表示形式 1:小写字母+- 2:大写字母+- 3:纯小写字母 4:纯大写字母
 */
function guid(style) {
  if (style == undefined || style == null || isNaN(style)) {
    style = 1;
  }
  var strGuid = v4();
  if (style == 1) {
    return strGuid;
  } else if (style == 2) {
    return strGuid.toUpperCase();
  } else if (style == 3) {
    return strGuid.replace(/-/g, '');
  } else if (style == 4) {
    return strGuid.toUpperCase().replace(/-/g, '');
  } else {
    return strGuid;
  }
}
/**
 * 将Buffer转换为相应的字符串
 * @param {*} 字符编码(UTF-8、GBK、GB2312、GB18030)
 */
function bufferToString(bufferData, encoding) {
  if (
    !Buffer.isBuffer(bufferData) &&
    !Object.toString.call(bufferData) == '[object Array]'
  ) {
    return '';
  }
  if (!Buffer.isBuffer(bufferData)) {
    bufferData = Buffer.from(bufferData);
  }
  if (encoding.toUpperCase() == 'UTF-8') {
    return bufferData.toString();
  } else if (
    encoding.toUpperCase() == 'GBK' ||
    encoding.toUpperCase() == 'GB2312' ||
    encoding.toUpperCase() == 'GB18030'
  ) {
    return iconvLite.decode(bufferData, encoding);
  }
  if (iconvLite.encodingExists(encoding)) {
    return iconvLite.decode(bufferData, encoding);
  } else {
    throw new error(`解码失败,不支持解码:${encoding}数据`);
  }
}
/**
 * 将字符串内容转换为Buffer
 * @param {*} str 需要被转换为字符串的内容
 * @param {*} encoding 编码
 */
function stringToBuffer(str, encoding) {
  if (encoding == undefined || encoding == null) {
    encoding = 'UTF-8';
  }
  if (encoding == 'UTF-8') {
    return Buffer.from(str, encoding);
  } else {
    if (iconvLite.encodingExists(encoding)) {
      return iconvLite.encode(str, encoding);
    }
    else {
        throw new error(`编码失败,不支持的编码:${encoding}`);
    }
  }
}
/**
 * 将数据转换为base64字符串
 * @param {*} obj
 */
function bufferToBase64(obj) {
  var toString = Object.prototype.toString;
  if (
    Buffer.isBuffer(obj) ||
    Array.isArray(obj) ||
    toString.call(obj) == '[object Array]' ||
    toString.call(obj) == '[object String]'
  ) {
    return Buffer.from(obj).toString('base64');
  } else {
    return null;
  }
}
/**
 * 获取当前系统时间
 */
function currentTime() {
  return moment();
}
/**
 * 获取当前系统IP地址
 */
function getIP() {
  var os = require('os');
  var ifaces = os.networkInterfaces();
  for (var prop in ifaces) {
    for (var j = 0; j < ifaces[prop].length; j++) {
      var iface = ifaces[prop][j];
      if ('IPv4' !== iface.family || iface.internal !== false) {
        continue;
      }
      return iface.address;
    }
  }
  // Object.keys(ifaces).forEach(function (ifname) {
  //     var alias = 0;
  //     ifaces[ifname].forEach(function (iface) {
  //         if ('IPv4' !== iface.family || iface.internal !== false) {
  //             // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
  //             return;
  //         }
  //         if (alias >= 1) {
  //             // this single interface has multiple ipv4 addresses
  //             console.log(ifname + ':' + alias, iface.address);
  //         } else {
  //             // this interface has only one ipv4 adress
  //             console.log(ifname, iface.address);
  //         }
  //         ++alias;
  //     });
  // });
}
/**
 * 获取指定范围内的随机数
 * @param {*} min 最小数
 * @param {*} max 最大数
 */
function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
/**
 * 从指定Url下载文件,并保存
 * @param {*} url 文件http地址
 * @param {*} savePath 保存位置
 */
async function downloadFile(url, savePath) {
  return new Promise(function (resolve) {
    let result = {
      success: false,
      message: '',
    };
    let fs = require('fs');
    if (url.startsWith('https')) {
      let https = require('https');
      let req = https.request(
        url,
        {
          rejectUnauthorized: false,
        },
        function (resp) {
          let stream = fs.createWriteStream(`${savePath}`);
          resp.pipe(stream);
          stream.on('finish', function () {
            result.success = true;
            stream.close();
            resolve(result);
          });
        }
      );
      req.on('error', function (error) {
        result.success = false;
        result.message = error.message;
        resolve(result);
      });
      req.end();
    } else if (url.startsWith('http')) {
      let http = require('http');
      let req = http.request(url, {}, function (resp) {
        let stream = fs.createWriteStream(`${savePath}`);
        resp.pipe(stream);
        stream.on('finish', function () {
          result.success = true;
          stream.close();
          resolve(result);
        });
      });
      req.on('error', function (error) {
        result.success = false;
        result.message = error.message;
        resolve(result);
      });
      req.end();
    } else {
      result.message = `下载失败,URL格式错误(仅支持http和https)`;
      resolve(result);
    }
  });
}
module.exports = {
  calcParkingDuration,
  convertMoney,
  formatJson,
  jsonToQueryString,
  guid,
  bufferToString,
  stringToBuffer,
  currentTime,
  getIP,
  bufferToBase64,
  getRandom,
  downloadFile,
};
