const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class PushapiService extends ServiceBase {
  constructor() {
    super("push", ServiceBase.getDaoName(PushapiService));
    this.pushlogDao = system.getObject("db.push.pushlogDao");
  }

  /**
   * 
   * @param {} options  参数如下
   * @param merchantId  商户id
   * @param appKey      商户加密key
   * @param dataType    数据类型 
   * @param dataId      数据id
   * @param field       推送字段，通过字段去查找推送地址
   * @param params      推送参数
   */
  async push(options) {
    var api = await this.findById(options.merchantId);
    if (!api) {
      console.log("api不存在[" + JSON.stringify(options) + "]");
      return;
    }

    var apiurl = api[options.field];
    if (!apiurl) {
      console.log("api地址不存在[" + JSON.stringify(options) + "]");
      return;
    }
    var log;
    try {
      var params = options.params;
      params.times_tamp = new Date().getTime();
      var signData = await this.createSign(params, options.appKey);
      params.sign = signData.data;
      params.requestid = this.getUUID();

      log = await this.pushlogDao.create({
        dataType: Number(options.dataType),
        dataId: options.dataId,
        api: apiurl,
        params: JSON.stringify(options.params),
        rs: "",
        success: 0,
      });
      try {
        console.log(JSON.stringify(params));
        var rtn = await this.restS.execPost(params, apiurl);
        var returnValue = 0;
        if (rtn.stdout) {
          var result = JSON.parse(rtn.stdout);
          if (result.code == "success") {
            log.success = 1;
            log.rs = trn.stdout;
            await log.save();
          }
        }
      } catch (error) {
        log.success = 0;
        log.rs = error.message;
        await log.save();
      }
    } catch (error) {
      if (log) {
        log.success = 0;
        log.rs = error.message;
        await log.save();
      }
      console.log(error.stack, JSON.stringify(options), "--------------------------------- push exception ---------------------------------");
    }
  }
}
module.exports = PushapiService;