import { Inject, Logger, Provide } from '@midwayjs/decorator';
import { BaseService } from 'midwayjs-cool-core';
import { ILogger } from '@midwayjs/logger';
import { Utils } from '../../../comm/utils';
import * as _ from 'lodash';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { ShuyouAbnormalRateEntity } from '../../shuyou/entity/data_abnormal_rate';
import { ShuyouUtilsService } from '../../shuyou/service/utils';

/**
 * 描述
 */
@Provide()
export class XjfLogTaskService extends BaseService {
  @Logger()
  logger: ILogger;

  @Inject()
  utils: Utils;

  @InjectEntityModel(ShuyouAbnormalRateEntity)
  ShuyouAbnormalRateEntity: Repository<ShuyouAbnormalRateEntity>;

  @Inject()
  shuyouUtilsService: ShuyouUtilsService;

  async syncAbnormalRate() {
    let new_date = this.utils.formatDate(new Date());
    let hour = new Date().getHours();
    // console.log(hour)
    let updateTime = new Date();
    this.logger.info('syncAbnormalRate>>>' + updateTime);

    const sql = `
      SELECT
        a.task_id,
        a.task_name,
        a.new_date,
        a.directorId,
        b.login_modeId,
        b.xjf_id
      from 
        shuyou_game_target a
        LEFT JOIN shuyou_game_task b ON a.task_id = b.id
      where 1 = 1 
      ${this.setSql(new_date, 'and a.new_date = ? ORDER BY a.task_id', [
        new_date,
      ])}
    `;
    // console.log(sql)
    const targetList = await this.nativeQuery(sql);
    if (_.isEmpty(targetList)) {
      return (
        'syncAbnormalRate >>> shuyou_game_target is null >>> ' + updateTime
      );
    }
    const logs = [
      { action: '教程主线', action_result: '冻结' },
      { action: '拉取账号', action_result: '成功' },
      { action: '启动模拟器', action_result: '成功' },
      { action: '启动游戏', action_result: '查询IP' },
      { action: '脚本启动', action_result: '成功' },
      { action: '启动游戏', action_result: '成功' },
      { action: '登陆', action_result: '成功' },
      { action: '教程主线', action_result: '进入游戏' },
      { action: '教程主线', action_result: '新增成功' },
      { action: '教程主线', action_result: '留存成功' },
      { action: '付费充值', action_result: '付费成功' },
      { action: '教程主线', action_result: '可以付费' },
      { action: '留存账号总数', action_result: '留存账号总数' },
      { action: '询问付费', action_result: '付费' },
    ];

    let data3 = await queryNewComputerRoom(new_date);
    let newComputerRoomData = [];
    if (_.isEmpty(data3) || data3 == -1) {
      // this.logger.warn('新机房后台数据错误')
      newComputerRoomData = [];
    } else {
      newComputerRoomData = JSON.parse(data3 + '');
    }

    await ykhForeach(targetList, async (item, index) => {
      let task_id = item.task_id;
      let task_name = item.task_name;
      let directorId = item.directorId;
      let login_modeId = item.login_modeId;
      let xjf_id = item.xjf_id;
      // console.log(xjf_id)
      let useXjf = false;
      let game_id = xjf_id;
      let xjfData;

      if (xjf_id != 0) {
        let queryXjf;
        queryXjf = await queryXjfId(xjf_id);
        // console.log(queryXjf)
        if (_.isEmpty(queryXjf) || queryXjf == -1) {
          xjfData = {
            IdDong: 0,
            IdYang: 0,
          };
        } else {
          xjfData = JSON.parse(queryXjf + '');
        }
        // console.log(xjfData)
        // console.log(xjfData.IdYang)
        if (xjfData.IdYang == task_id) {
          useXjf = true;
        } else {
          // return 'syncAbnormalRate  Fail>>>gameid is null' + updateTime;
        }
        let num_arr = [];
        if (useXjf == true) {
          await ykhForeach(logs, async (e, i) => {
            let action = e.action;
            const action_result = e.action_result;
            let num_xjfLog;
            if (i == 6) {
              if (login_modeId == 1) {
                //小绵羊登录 小绵羊登陆
                let xmy1 = await queryXjfLog(
                  new_date,
                  '小绵羊登录',
                  action_result,
                  game_id
                );
                let xmy2 = await queryXjfLog(
                  new_date,
                  '小绵羊登陆',
                  action_result,
                  game_id
                );
                num_xjfLog = parseInt(xmy1 + '') + parseInt(xmy2 + '');
              } else if (login_modeId == 2) {
                //魅族登录 魅族登陆
                let mz1 = await queryXjfLog(
                  new_date,
                  '魅族登录',
                  action_result,
                  game_id
                );
                let mz2 = await queryXjfLog(
                  new_date,
                  '魅族登陆',
                  action_result,
                  game_id
                );
                num_xjfLog = parseInt(mz1 + '') + parseInt(mz2 + '');
              } else if (
                login_modeId == 3 ||
                login_modeId == 5 ||
                login_modeId == 6
              ) {
                //QQ登录 QQ登陆 微信登录 微信登陆
                let num_xjfLog1 = await queryXjfLog(
                  new_date,
                  'QQ登录',
                  action_result,
                  game_id
                );
                let num_xjfLog2 = await queryXjfLog(
                  new_date,
                  '微信登录',
                  action_result,
                  game_id
                );
                let num_xjfLog3 = await queryXjfLog(
                  new_date,
                  'QQ登陆',
                  action_result,
                  game_id
                );
                let num_xjfLog4 = await queryXjfLog(
                  new_date,
                  '微信登陆',
                  action_result,
                  game_id
                );
                num_xjfLog =
                  parseInt(num_xjfLog1 + '') +
                  parseInt(num_xjfLog2 + '') +
                  parseInt(num_xjfLog3 + '') +
                  parseInt(num_xjfLog4 + '');
              } else if (login_modeId == 4) {
                //网易登录 网易登陆
                let wy1 = await queryXjfLog(
                  new_date,
                  '网易登录',
                  action_result,
                  game_id
                );
                let wy2 = await queryXjfLog(
                  new_date,
                  '网易登陆',
                  action_result,
                  game_id
                );
                num_xjfLog = parseInt(wy1 + '') + parseInt(wy2 + '');
              } else {
              }
            } else {
              num_xjfLog = await queryXjfLog(
                new_date,
                action,
                action_result,
                game_id
              );
            }
            num_arr.push(num_xjfLog);
          });
          // console.log(num_arr)
          let rate_all_step = 0;
          if (num_arr[7] != 0 && num_arr[5] != 0) {
            rate_all_step = parseFloat(num_arr[7]) / parseFloat(num_arr[5]);
          }
          let order_success_rate = '-/-/-%';
          //
          for (let newvalue of newComputerRoomData) {
            if (newvalue.game_id == xjf_id) {
              order_success_rate = newvalue.order_success_rate;
              break;
            }
          }
          //
          let rateObj = {
            task_id: task_id,
            task_name: task_name,
            directorId: directorId,
            new_date: new_date,
            hour: hour,
            num_frozen: num_arr[0],
            num_pull_account: num_arr[1],
            num_start_simulator: num_arr[2],
            num_ip: num_arr[3],
            num_start_script: num_arr[4],
            num_start_game: num_arr[5],
            num_login_success: num_arr[6],
            num_into_game: num_arr[7],
            num_new_success: num_arr[8],
            num_lc_success: num_arr[9],
            num_pay_success: num_arr[10],
            rate_all_step: rate_all_step,
            num_could_pay: num_arr[11], // 可以付费的账号
            num_account_lc: num_arr[12], //留存账号总数
            num_pull_pay: num_arr[13], // 下发付费账号
            order_success_rate: order_success_rate,
          };

          // console.log(rateObj)
          const AbnormalRateEntity =
            await this.ShuyouAbnormalRateEntity.findOne({
              new_date: new_date,
              hour: hour,
              task_id: task_id,
            });
          if (AbnormalRateEntity) {
            await this.ShuyouAbnormalRateEntity.createQueryBuilder()
              .update()
              .set(rateObj)
              .where(
                'new_date = :new_date and hour = :hour and task_id = :task_id',
                {
                  new_date: new_date,
                  hour: hour,
                  task_id: task_id,
                }
              )
              .execute();
          } else {
            await this.ShuyouAbnormalRateEntity.createQueryBuilder()
              .insert()
              .into(ShuyouAbnormalRateEntity)
              .values(rateObj)
              .execute();
          }
        } else {
          // return 'syncAbnormalRate  Fail>>> 2' + updateTime;
        }
      }
    });

    // ====================================

    return 'syncAbnormalRate  SUCCESS>>>' + updateTime;
  }

  /**
   *
   * 快速批量查询游戏异常率
   * @return {*}
   * @memberof XjfLogTaskService
   */
  async syncAbnormalRateByBatch() {
    let new_date = this.utils.formatDate(new Date());
    let hour = new Date().getHours();
    // console.log(hour)
    let updateTime = new Date();
    this.logger.info('syncAbnormalRateByBatch>>>' + updateTime);

    const sql = `
      SELECT
        a.task_id,
        a.task_name,
        a.new_date,
        a.directorId,
        b.login_modeId,
        b.xjf_id
      from 
        shuyou_game_target a
        LEFT JOIN shuyou_game_task b ON a.task_id = b.id
      where 1 = 1 
      ${this.setSql(new_date, 'and a.new_date = ? ORDER BY a.task_id', [
        new_date,
      ])}
    `;
    // console.log(sql)
    const targetList = await this.nativeQuery(sql);
    if (_.isEmpty(targetList)) {
      return (
        'syncAbnormalRateByBatch >>> shuyou_game_target is null >>> ' +
        updateTime
      );
    }
    // this.logger.info(targetList)
    const logs = [
      { action: '教程主线', action_result: '冻结' },
      { action: '拉取账号', action_result: '成功' },
      { action: '启动模拟器', action_result: '成功' },
      { action: '启动游戏', action_result: '查询IP' },
      { action: '脚本启动', action_result: '成功' },
      { action: '启动游戏', action_result: '成功' },
      { action: '登陆', action_result: '成功' },
      { action: '教程主线', action_result: '进入游戏' },
      { action: '教程主线', action_result: '新增成功' },
      { action: '教程主线', action_result: '留存成功' },
      { action: '付费充值', action_result: '付费成功' },
      { action: '教程主线', action_result: '可以付费' },
      { action: '留存账号总数', action_result: '留存账号总数' },
      { action: '询问付费', action_result: '付费' },
    ];

    let data3 = await queryNewComputerRoom(new_date);
    let newComputerRoomData = [];
    if (_.isEmpty(data3) || data3 == -1) {
      // this.logger.warn('新机房后台数据错误')
      newComputerRoomData = [];
    } else {
      newComputerRoomData = JSON.parse(data3 + '');
    }

    let num_arr0 = [];
    let num_arr1 = [];
    let num_arr2 = [];
    let num_arr3 = [];
    let num_arr4 = [];
    let num_arr5 = [];
    let num_arr6 = [];
    let num_arr7 = [];
    let num_arr8 = [];
    let num_arr9 = [];
    let num_arr10 = [];
    let num_arr11 = [];
    let num_arr12 = [];
    let num_arr13 = [];
    //查询所有日志结果start===============
    await ykhForeach(logs, async (e, i) => {
      const action = e.action;
      const action_result = e.action_result;
      // console.log(i);
      let arr_i;
      if (i == 6) {
        //小绵羊登录 小绵羊登陆
        arr_i = await queryXjfLogByBatch(new_date, '小绵羊登录', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
        arr_i = await queryXjfLogByBatch(new_date, '小绵羊登陆', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
        //魅族登录 魅族登陆
        arr_i = await queryXjfLogByBatch(new_date, '魅族登录', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
        arr_i = await queryXjfLogByBatch(new_date, '魅族登陆', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
        //QQ登录 QQ登陆 微信登录 微信登陆
        arr_i = await queryXjfLogByBatch(new_date, 'QQ登录', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }

        arr_i = await queryXjfLogByBatch(new_date, '微信登录', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
        arr_i = await queryXjfLogByBatch(new_date, 'QQ登陆', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
        arr_i = await queryXjfLogByBatch(new_date, '微信登陆', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
        //网易登录 网易登陆
        arr_i = await queryXjfLogByBatch(new_date, '网易登录', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
        arr_i = await queryXjfLogByBatch(new_date, '网易登陆', action_result);
        if (arr_i != 'null') {
          num_arr6.push(...JSON.parse(arr_i + ''));
        }
      } else {
        arr_i = await queryXjfLogByBatch(new_date, action, action_result);
      }
      if (arr_i != 'null') {
        switch (i) {
          case 0:
            num_arr0.push(arr_i);
            break;
          case 1:
            num_arr1.push(arr_i);
            break;
          case 2:
            num_arr2.push(arr_i);
            break;
          case 3:
            num_arr3.push(arr_i);
            break;
          case 4:
            num_arr4.push(arr_i);
            break;
          case 5:
            num_arr5.push(arr_i);
            break;
          case 7:
            num_arr7.push(arr_i);
            break;
          case 8:
            num_arr8.push(arr_i);
            break;
          case 9:
            num_arr9.push(arr_i);
            break;
          case 10:
            num_arr10.push(arr_i);
            break;
          case 11:
            num_arr11.push(arr_i);
            break;
          case 12:
            num_arr12.push(arr_i);
            break;
          case 13:
            num_arr13.push(arr_i);
            break;
        }
      }
    });

    if (!_.isEmpty(num_arr0)) {
      num_arr0 = JSON.parse(num_arr0 + '');
    }
    if (!_.isEmpty(num_arr1)) {
      num_arr1 = JSON.parse(num_arr1 + '');
    }
    if (!_.isEmpty(num_arr2)) {
      num_arr2 = JSON.parse(num_arr2 + '');
    }
    if (!_.isEmpty(num_arr3)) {
      num_arr3 = JSON.parse(num_arr3 + '');
    }
    if (!_.isEmpty(num_arr4)) {
      num_arr4 = JSON.parse(num_arr4 + '');
    }
    if (!_.isEmpty(num_arr5)) {
      num_arr5 = JSON.parse(num_arr5 + '');
    }
    if (!_.isEmpty(num_arr7)) {
      num_arr7 = JSON.parse(num_arr7 + '');
    }
    if (!_.isEmpty(num_arr8)) {
      num_arr8 = JSON.parse(num_arr8 + '');
    }
    if (!_.isEmpty(num_arr9)) {
      num_arr9 = JSON.parse(num_arr9 + '');
    }
    if (!_.isEmpty(num_arr10)) {
      num_arr10 = JSON.parse(num_arr10 + '');
    }
    if (!_.isEmpty(num_arr11)) {
      num_arr11 = JSON.parse(num_arr11 + '');
    }
    if (!_.isEmpty(num_arr12)) {
      num_arr12 = JSON.parse(num_arr12 + '');
    }
    if (!_.isEmpty(num_arr13)) {
      num_arr13 = JSON.parse(num_arr13 + '');
    }

    //查询所有日志结果end ===============
    //遍历游戏表
    await ykhForeach(targetList, async target => {
      let task_id = target.task_id;
      let task_name = target.task_name;
      let directorId = target.directorId;
      // let login_modeId = target.login_modeId
      let xjf_id = target.xjf_id;
      // console.log(xjf_id)
      let num_frozen = 0;
      let num_pull_account = 0;
      let num_start_simulator = 0;
      let num_ip = 0;
      let num_start_script = 0;
      let num_start_game = 0;
      let num_login_success = 0;
      let num_into_game = 0;
      let num_new_success = 0;
      let num_lc_success = 0;
      let num_pay_success = 0;
      let rate_all_step = 0;
      let num_could_pay = 0; // 可以付费的账号
      let num_account_lc = 0; //留存账号总数
      let num_pull_pay = 0; // 下发付费账号
      let order_success_rate = '-/-/-%';

      for (let num of num_arr0) {
        if (xjf_id == num.game_id) {
          num_frozen = num.total;
          break;
        }
      }

      for (let num of num_arr1) {
        if (xjf_id == num.game_id) {
          // this.logger.info(num)
          num_pull_account = num.total;
          break;
        }
      }
      for (let num of num_arr2) {
        if (xjf_id == num.game_id) {
          num_start_simulator = num.total;
          break;
        }
      }
      for (let num of num_arr3) {
        if (xjf_id == num.game_id) {
          num_ip = num.total;
          break;
        }
      }
      for (let num of num_arr4) {
        if (xjf_id == num.game_id) {
          num_start_script = num.total;
          break;
        }
      }
      for (let num of num_arr5) {
        if (xjf_id == num.game_id) {
          num_start_game = num.total;
          break;
        }
      }
      for (let num of num_arr6) {
        if (xjf_id == num.game_id) {
          num_login_success = num_login_success + num.total;
        }
      }
      for (let num of num_arr7) {
        if (xjf_id == num.game_id) {
          num_into_game = num.total;
          break;
        }
      }
      for (let num of num_arr8) {
        if (xjf_id == num.game_id) {
          num_new_success = num.total;
          break;
        }
      }
      for (let num of num_arr9) {
        if (xjf_id == num.game_id) {
          num_lc_success = num.total;
          break;
        }
      }
      for (let num of num_arr10) {
        if (xjf_id == num.game_id) {
          num_pay_success = num.total;
          break;
        }
      }
      for (let num of num_arr11) {
        if (xjf_id == num.game_id) {
          num_could_pay = num.total;
          break;
        }
      }
      for (let num of num_arr12) {
        if (xjf_id == num.game_id) {
          num_account_lc = num.total;
          break;
        }
      }
      for (let num of num_arr13) {
        if (xjf_id == num.game_id) {
          num_pull_pay = num.total;
          break;
        }
      }

      if (num_into_game != 0 && num_start_game != 0) {
        rate_all_step =
          parseFloat(num_into_game + '') / parseFloat(num_start_game + '');
      }
      //
      for (let new_value of newComputerRoomData) {
        if (new_value.game_id == xjf_id) {
          order_success_rate = new_value.order_success_rate;
          break;
        }
      }

      let rateObj = {
        task_id: task_id,
        task_name: task_name,
        directorId: directorId,
        new_date: new_date,
        hour: hour,
        num_frozen: num_frozen,
        num_pull_account: num_pull_account,
        num_start_simulator: num_start_simulator,
        num_ip: num_ip,
        num_start_script: num_start_script,
        num_start_game: num_start_game,
        num_login_success: num_login_success,
        num_into_game: num_into_game,
        num_new_success: num_new_success,
        num_lc_success: num_lc_success,
        num_pay_success: num_pay_success,
        rate_all_step: rate_all_step,
        num_could_pay: num_could_pay, // 可以付费的账号
        num_account_lc: num_account_lc, //留存账号总数
        num_pull_pay: num_pull_pay, // 下发付费账号
        order_success_rate: order_success_rate,
      };
      // console.log(rateObj)
      const AbnormalRateEntity = await this.ShuyouAbnormalRateEntity.findOne({
        new_date: new_date,
        hour: hour,
        task_id: task_id,
      });
      if (AbnormalRateEntity) {
        await this.ShuyouAbnormalRateEntity.createQueryBuilder()
          .update()
          .set(rateObj)
          .where(
            'new_date = :new_date and hour = :hour and task_id = :task_id',
            {
              new_date: new_date,
              hour: hour,
              task_id: task_id,
            }
          )
          .execute();
      } else {
        await this.ShuyouAbnormalRateEntity.createQueryBuilder()
          .insert()
          .into(ShuyouAbnormalRateEntity)
          .values(rateObj)
          .execute();
      }
    });
    // ====================================
    this.logger.info('syncAbnormalRateByBatch SUCCESS>>>' + updateTime);
    return 'syncAbnormalRateByBatch  SUCCESS>>>' + updateTime;
  }

  /**
   * 定时查询QQ卡剩余张数，少于15张，则报警
   * @memberof XjfLogTaskService
   */
  async queryQQCardCount() {
    let updateTime = new Date();
    let data;
    data = await queryQQCardCount();
    // console.log('data:' + data)
    let text = '';
    if (parseInt(data + '') <= 15) {
      // console.log('QQ卡即将用尽')
      text = '>##### QQ卡即将用尽,请及时补充,当前剩余' + data + ' \n';
      await this.shuyouUtilsService.postRobotEnterpriseWeChat3(text);
    }
    data = await queryMzBalance();
    // console.log('data:' + data)
    if (parseInt(data + '') <= 500) {
      // console.log('QQ卡即将用尽')
      text = '>##### 魅族云点即将用尽,请及时补充,当前剩余' + data + ' \n';
      await this.shuyouUtilsService.postRobotEnterpriseWeChat3(text);
    }

    return 'queryQQCardCount  SUCCESS>>>' + updateTime;
  }
}

//==========================================================================================
// 根据gameid获取新机房信息
let queryXjfId = function (game_id) {
  var url =
    'http://xjf.lianyou.fun:8099/v1/task_statistics/get_data_id?game_id=' +
    game_id;
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 获取新机房游戏数据
let queryNewComputerRoom = function (new_date) {
  var url =
    'http://xjf.lianyou.fun:8099/v1/task_statistics?query=date:' +
    new_date +
    ',type:machine';
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 获取新机房日志
let queryXjfLog = function (new_date, action, action_result, game_id) {
  var url =
    'http://xjf.lianyou.fun:8099/v1/device/get_log?date=' +
    new_date +
    '&action=' +
    action +
    '&action_result=' +
    action_result +
    '&game_id=' +
    game_id;
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 批量获取新机房日志
let queryXjfLogByBatch = function (new_date, action, action_result) {
  var url =
    'http://xjf.lianyou.fun:8099/v1/device/get_log_by_game?date=' +
    new_date +
    '&action=' +
    action +
    '&action_result=' +
    action_result;
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 获取QQ卡剩余张数
let queryQQCardCount = function () {
  var url = 'http://xjf.lianyou.fun:8099/v1/device/qq_card_count';
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 获取魅族云点余额
let queryMzBalance = function () {
  var url =
    'http://xjf.lianyou.fun:8099/v1/device/setAccountLog?action=付费充值&action_result=查询魅族云点&account=meizu';
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};

// foreach加上async/await
const ykhForeach = async (arr, callback) => {
  const length = arr.length;
  const O = Object(arr);
  let k = 0;
  while (k < length) {
    if (k in O) {
      // console.log('doing foreach...');
      const kValue = O[k];
      await callback(kValue, k, O);
    }
    k++;
  }
};
