const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class MerchantrechargeService extends ServiceBase {
  constructor() {
    super("merchant", ServiceBase.getDaoName(MerchantrechargeService));

    this.merchantDao = system.getObject("db.merchant.merchantDao");
    this.merchantaccountDao = system.getObject("db.merchant.merchantaccountDao");
  }

  async apiAdd(params) {
    try {
      return await this.add(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiPage(params) {
    try {
      return await this.page(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiInfo(params) {
    try {
      return await this.info(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiAudit(params) {
    try {
      return await this.audit(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }


  // -----------------------以此间隔，上面为API，下面为service---------------------------------

  
  async add(params) {
    var recharge = {
      merchant_id: params.merchantId || params.merchant_id,
      outTradeNo: this.trim(params.outTradeNo),
      voucher: this.trim(params.voucher),
      amt: Number(params.amt),
      status: "00",
      remark: "",
    };

    if (!recharge.outTradeNo) {
      return system.getResult(null, "充值流水号不能为空");
    }

    if (!recharge.voucher) {
      return system.getResult(null, "充值凭证不能为空");
    }

    if (!/^\d+$/.test(recharge.amt) || Number(recharge.amt) <= 0) {
      return system.getResult(null, "充值金额只能为正整数");
    }

    var exists = await this.findOne({
      merchant_id: recharge.merchant_id,
      outTradeNo: recharge.outTradeNo,
    });
    if(exists) {
      return system.getResult(null, "充值流水号已存在");
    }
    recharge = await this.dao.create(recharge);

    return system.getResultSuccess();
  }

  async info(params) {
    var recharge = await this.dao.getById(params.id);
    if (recharge) {
      await this.dao.setRowCodeName(recharge, "status");
      this.handleDate(recharge, ["created_at", "updated_at"], null, -8);
      await this.setMerchantName([recharge], "id, name");
    }
    return system.getResultSuccess(recharge);
  }

  async audit(params) {
    var id = params.id;
    var auditStatus = this.trim(params.status);
    var remark = this.trim(params.remark);
    var opUser = params.opUser;
    var recharge = await this.dao.findById(id);
    if (!recharge) {
      return system.getResult(null, "充值申请不存在");
    }

    if(auditStatus != "10" && auditStatus != "20") {
      return system.getResult(null, "审核状态错误");
    }

    if (recharge.status != "00") {
      return system.getResult(null, "该申请已经被审核，不允许再次审核");
    }

    var self = this;
    await this.db.transaction(async function (t) {
      var updateParams = {
        status: auditStatus,
        remark: remark || "",
        auditTime: new Date(),
        auditUserName: opUser.ucname,
        auditUserId: opUser.ucid,
      }
      // 审核
      await self.dao.model.update(updateParams, {
        where: {
          id: recharge.id
        },
        transaction: t
      });

      if (auditStatus == "10") {
        await self.merchantaccountDao.inrBanlance(recharge.merchant_id, recharge.amt, t);
        var account = await self.merchantaccountDao.model.findOne({
          channel_id: 0,
          merchant_id: recharge.merchant_id
        }, t);
      }
    });
    return system.getResultSuccess();
  }
  
  async page(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var where = {};
    if (params.merchantId) {
      where.merchant_id = params.merchantId;
    }

    if (params.status) {
      where.status = params.status;
    }

    // 创建时间
    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd, true);

    var orderby = [
      ["id", 'desc']
    ];

    var page = await this.getPageList(currentPage, pageSize, where, orderby, null);
    if (page && page.rows) {
      for (var row of page.rows) {
        await this.dao.setRowCodeName(row, "status");
        this.handleDate(row, ["created_at", "updated_at", "auditTime"], null, -8);
      }
      await this.setMerchantName(page.rows, "id, name");
    }
    return system.getResultSuccess(page);
  }

  async setMerchantName(rows, attrs) {
    var map = await this.getMerchantMap(rows, attrs);
    for (var row of rows) {
      row.merchantName = (map[row.merchant_id] || {}).name || "";
    }
  }

  async setMerchant(rows, attrs) {
    var map = await this.getMerchantMap(rows, attrs);
    for (var row of rows) {
      row.merchant = map[row.merchant_id] || {};
    }
  }

  async getMerchantMap(rows, attrs) {
    if (!rows || rows.length == 0) {
      return {};
    }
    var ids = [];
    for (var row of rows) {
      ids.push(row.merchant_id);
    }
    return await this.merchantDao.findMapByIds(ids, attrs);
  }

}
module.exports = MerchantrechargeService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });