import { Inject, Provide } from '@midwayjs/decorator';
import * as ipdb from 'ipip-ipdb';
import * as _ from 'lodash';
import { Context } from 'egg';

/**
 * 帮助类
 */
@Provide()
export class Utils {
  @Inject()
  baseDir;

  /**
   * 获得请求IP
   */
  async getReqIP(ctx: Context) {
    const req = ctx.req;
    return (
      req.headers['x-forwarded-for'] ||
      req.socket.remoteAddress.replace('::ffff:', '')
    );
  }

  /**
   * 根据IP获得请求地址
   * @param ip 为空时则为当前请求的IP地址
   */
  async getIpAddr(ctx: Context, ip?: string | string[]) {
    try {
      if (!ip) {
        ip = await this.getReqIP(ctx);
      }
      const bst = new ipdb.BaseStation(
        `${this.baseDir}/app/comm/ipipfree.ipdb`
      );
      const result = bst.findInfo(ip, 'CN');
      const addArr: any = [];
      if (result) {
        addArr.push(result.countryName);
        addArr.push(result.regionName);
        addArr.push(result.cityName);
        return _.uniq(addArr).join('');
      }
    } catch (err) {
      return '无法获取地址信息';
    }
  }

  /**
   * 去除对象的空值属性
   * @param obj
   */
  async removeEmptyP(obj) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '' || obj[key] === 'undefined') {
        delete obj[key];
      }
    });
  }

  /**
   * 线程阻塞毫秒数
   * @param ms
   */
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  /**
   * 获取指定格式日期YYYY-MM-DD
   * @param {*} date
   * @return {*}
   * @memberof Utils
   */
  formatDate(date) {
    //三目运算符
    const Dates = new Date(date);

    //年份
    const Year: number = Dates.getFullYear();

    //月份下标是0-11
    const Months: any =
      Dates.getMonth() + 1 < 10
        ? '0' + (Dates.getMonth() + 1)
        : Dates.getMonth() + 1;

    //具体的天数
    const Day: any =
      Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate();

    //小时
    //  const Hours = Dates.getHours() < 10 ? '0' + Dates.getHours() : Dates.getHours();

    //  //分钟
    //  const Minutes = Dates.getMinutes() < 10 ? '0' + Dates.getMinutes() : Dates.getMinutes();

    //  //秒
    //  const Seconds = Dates.getSeconds() < 10 ? '0' + Dates.getSeconds() : Dates.getSeconds();

    //返回数据格式
    //  return Year + '-' + Months + '-' + Day + '-' + Hours + ':' + Minutes + ':' + Seconds;
    return Year + '-' + Months + '-' + Day;
  }
  /**
   * 获取指定格式时间
   * @param {*} date
   * @return {*}
   * @memberof Utils
   */
  formatDateTime(date) {
    //三目运算符
    const Dates = new Date(date);

    //年份
    const Year: number = Dates.getFullYear();

    //月份下标是0-11
    const Months: any =
      Dates.getMonth() + 1 < 10
        ? '0' + (Dates.getMonth() + 1)
        : Dates.getMonth() + 1;

    //具体的天数
    const Day: any =
      Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate();

    //小时
    const Hours =
      Dates.getHours() < 10 ? '0' + Dates.getHours() : Dates.getHours();

    //  //分钟
    const Minutes =
      Dates.getMinutes() < 10 ? '0' + Dates.getMinutes() : Dates.getMinutes();

    //  //秒
    const Seconds =
      Dates.getSeconds() < 10 ? '0' + Dates.getSeconds() : Dates.getSeconds();

    //返回数据格式
    //  return Year + '-' + Months + '-' + Day + '-' + Hours + ':' + Minutes + ':' + Seconds;
    return (
      Year +
      '-' +
      Months +
      '-' +
      Day +
      ' ' +
      Hours +
      ':' +
      Minutes +
      ':' +
      Seconds
    );
  }
  /**
   * 两个时间相差天数
   * sDate1和sDate2是2006-12-18格式
   * @param {*} sDate1
   * @param {*} sDate2
   * @return {*}
   * @memberof Utils
   */
  dateDiff(sDate1, sDate2) {
    var dateSpan, iDays;
    sDate1 = Date.parse(sDate1);
    sDate2 = Date.parse(sDate2);
    dateSpan = sDate2 - sDate1;
    dateSpan = Math.abs(dateSpan);
    iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
    return parseInt(iDays);
  }

  /**
   * 计算时间差（秒）
   * @param {Date} time1
   * @param {Date} time2
   * @return {*}
   * @memberof Utils
   */
  timeDiff(time1: Date, time2: Date) {
    var seconds = 0;
    time1 = new Date(time1);
    seconds = (time1.getTime() - time2.getTime()) / 1000;
    return seconds;
  }
  /**
   *
   * 获取几天前几天后的日期
   * @param {*} date
   * @param {*} day
   * @memberof Utils
   */
  getNextDate(date, day) {
    var dd = new Date(date);
    dd.setDate(dd.getDate() + day);
    var y = dd.getFullYear();
    var m =
      dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1;
    var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate();
    return y + '-' + m + '-' + d;
  }
  // 转换excle中导入的日期格式
  excelFormatDate(numb, format) {
    const time = new Date((numb - 1) * 24 * 3600000 + 1);
    time.setFullYear(time.getFullYear() - 70);
    const year = time.getFullYear() + '';
    const month = time.getMonth() + 1 + '';
    const date = time.getDate() + '';
    if (format && format.length === 1) {
      return year + format + month + format + date;
    }
    return (
      year +
      (parseInt(month) < 10 ? '0' + month : month) +
      (parseInt(date) < 10 ? '0' + date : date)
    );
  }
}
