const system = require("../../../system");
const ServiceBase = require("../../svems.base")
const settings = require("../../../../config/settings")
class MerchantService extends ServiceBase {
  constructor() {
    super();
    this.channelSve = system.getObject("service.saas.channelSve");
    this.mainSve = system.getObject("service.saas.mainSve");
  }

  async mapByIds(params) {
    var rs = await this.callms("merchant", "mchtMapByIds", params || {});
    return rs;
  }

  async dics(params) {
    var rs = await this.callms("merchant", "mchtDics", params);
    return rs;
  }

  async info(params) {
    var rs = await this.callms("merchant", "mchtInfo", params);
    if(rs.data && rs.data.sign) {
      this.transSignFields([rs.data.sign]);
      await this.setChannel([rs.data]);
    }
    return rs;
  }

  async save(params) {
    var rs = await this.callms("merchant", "mchtSave", params);
    return rs;
  }

  async page(params) {
    var rs = await this.callms("merchant", "mchtPage", params);
    if(rs.data && rs.data.rows) {
      this.transSignFields(rs.data.rows);
      await this.setChannel(rs.data.rows);
      await this.setMain(rs.data.rows);
    }
    return rs;
  }

  async sign(params) {
    var rs = await this.callms("merchant", "mchtSign", params);
    return rs;
  }

  async signInfo(params) {
    var rs = await this.callms("merchant", "mchtSignInfo", params);
    if(rs.data) {
      this.transSignFields([rs.data]);
    }
    return rs;
  }

  async setChannel(rows) {
    if(!rows) {
      return;
    }

    let channelIds = [];
    for(let row of rows) {
      if(row.channel_id) {
        channelIds.push(row.channel_id);
      }
    }
    if(channelIds.length == 0) {
      return;
    }
    let map = await this.channelSve.mapByIds({ids: channelIds}) || {};
    map = map.data || {};
    for(let row of rows) {
      row.channel = map[row.channel_id] || {};
    }
  }

  async setMain(rows) {
    if(!rows) {
      return;
    }

    let mainIds = [];
    for(let row of rows) {
      if(row.main_id) {
        mainIds.push(row.main_id);
      }
    }
    if(mainIds.length == 0) {
      return;
    }
    let map = await this.mainSve.mapByIds({ids: mainIds}) || {};
    map = map.data || {};
    for(let row of rows) {
      row.main = map[row.main_id] || {};
    }
  }

  transSignFields(rows) {
    if (!rows) {
      return;
    }
    for (var item of rows) {
      if (!item) {
        continue;
      }
      item.bm_reg_price = system.f2y(item.bm_reg_price);
      item.invoice_service_rate = system.f2y(item.invoice_service_rate);
      item.trans_service_rate = system.f2y(item.trans_service_rate);
    }
  }

}
module.exports = MerchantService;