const system = require("../../../system");
const ServiceBase = require("../../svems.base")

class AuthService extends ServiceBase {
  constructor() {
    // 1000000 报文参数问题  1001001 签名错误  1002001费用不足  1002002 订单未设置该产品
    super();

    this.feeSve = system.getObject("service.fee.feeSve");
    this.orderSve = system.getObject("service.order.orderSve");
    this.tradelogDao = system.getObject("db.common.tradelogDao");
  }
  async nameTwo(params) {
    try {
      // 通过应用id查询商户订单信息，确定产品认证接口
      let app = params.app;
      let merchantId = app.merchant_id;

      // 获取订单产品
      let orderProduct = await this.orderSve.getMerchantOrderProduct(merchantId, "nameTwo");
      if (orderProduct.status !== 0) {
        return orderProduct;
      }
      params.orderProduct = orderProduct.data;
      return this.doAuth(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }
  async bankThree(params) {
    try {
      return this.doAuth(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }
  async bankFour(params) {
    try {
      return this.doAuth(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async doAuth(params) {
    let orderProduct = params.orderProduct;
    // 扣费
    let tres = await this.trade(orderProduct);
    if (tres.status !== 0) {
      return tres;
    }
    let tradeLog = tres.data.tradeLog;
    let trade = tres.data.trade;
    // 2. 调用认证引擎

    // 3. 异步调用订单消费逻辑

    // 4. 返回认证结果

  }

  // 交易
  async trade(orderProduct) {
    let tradeLog = await this.tradelogDao.create({
      requestid: params.requestid,
      merchant_id: orderProduct.merchant_id,
      product_id: orderProduct.product_id,
      product_specifications: orderProduct.product_specifications,
      result: 0,
    });

    let tradeRes = await this.feeSve.trade({
      account_id: orderProduct.engine_account_id,
      trade_amt: orderProduct.product_specifications,
      trade_no: tradeLog.id,
      trade_desc: "二要素验证",
    });
    if (tradeRes.status !== 0) {
      tradeLog.result = 2;
      tradeLog.fee = 0;
      tradeLog.fee_remark = "扣费失败，" + tradeRes.msg;
      await tradeLog.save();
      return system.getResult(1002001, "扣费失败，" + tradeRes.msg);
    } else {
      tradeLog.result = 1;
      tradeLog.fee = 1
      tradeLog.fee_remark = "扣费成功";
      await tradeLog.save();
    }
    return system.getResultSuccess({
      tradeLog: tradeLog,
      trade: tradeRes.data
    })
  }
}

module.exports = AuthService;