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

  async pageByCondition(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var where = {};

    var merchantIds ;
    // 商户名称
    if (params.merchantName) {
      merchantIds = await this.merchantDao.idsLikeName(params.merchantName);
      if (!merchantIds || merchantIds.length == 0) {
        return {count : 0, rows: []};
      }
    }
    if(params.merchantId) {
      var mid = Number(params.merchantId);
      if(merchantIds) {
        if(merchantIds.indexOf(mid) == -1) {
          return {count : 0, rows: []};
        } else {
          merchantIds = [mid];
        }
      } else {
        merchantIds = [mid];
      }
    }
    if(merchantIds && merchantIds.length > 0) {
      where.merchant_id = {
        [this.db.Op.in]: merchantIds
      };
    }

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

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

    if (params.status == 'number') {
      where.status = params.status;
    }
    // 创建时间
    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd, true);

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

    var attributes = ["id", "merchant_id", "invoice_id", "invoiceNo", "invoiceApplyNo", "recharge_id", 
    "outTradeNo", "amt", "balance", "type", "businessType", "created_at"];

    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      var busiType = await this.dao.getBusinessTypes();

      var merchantMap = await this.getMerchantMap(page.rows, "id, name");

      for (var row of page.rows) {
        row.businessTypeName = busiType[row.businessType];
        row.merchantName = (merchantMap[row.merchant_id] || {}).name || "";

        this.handleDate(row, ["created_at"], null, -8);
      }

      system.f2y4list(page.rows, ["amt"]);
    }
    return page;
  }

  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=MerchanttradeService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
