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

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

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

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

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

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

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

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


  async getDefault(params) {
    var merchantId = params.merchantId || params.merchant_id;
    var obj = await this.dao.getDefaultByMerchantId(merchantId);
    return system.getResultSuccess(obj);
  }

  async info(params) {
    var title = await this.dao.getById(params.id);

    if(title) {
      this.handleDate(title, ["created_at"], null, -8);
      await this.setMerchantName([title]);
    }
    return system.getResultSuccess(title);
  }

  async saveTitle(params) {
    var id = params.id;
    var merchantId = params.merchantId;
    var title;
    if (id) {
      title = await this.findById(id);
    } else {
      title = {
        merchant_id: merchantId
      };
    }
    title.taxNo = this.trim(params.taxNo);
    title.invoiceAddr = this.trim(params.invoiceAddr);
    title.invoiceMobile = this.trim(params.invoiceMobile);
    title.accountName = this.trim(params.accountName);
    title.accountPublic = this.trim(params.accountPublic);

    if (id) {
      title = await title.save();
    } else {
      title = await this.create(title);
    }

    if (params.isDefault) {
      await this.dao.updDefaultByMerchantId(title.merchant_id, false);
      await this.dao.updDefaultById(title.id, true);
    }

    return system.getResultSuccess(title);
  }

  async setDefault(id) {
    var title = await this.dao.findById(id);
    if (!title) {
      return system.getResult(null, "抬头不存在");
    }

    await this.dao.updDefaultByMerchantId(title.merchant_id, false);
    await this.dao.updDefaultById(title.id, true);
    return system.getResultSuccess();
  }

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

    var where = {};

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

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

    var attributes = ["id", "merchant_id", "taxNo", "invoiceAddr", "invoiceMobile", "accountName", "accountPublic", "isDefault", "created_at"];

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

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

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

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