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

class StOrderItemService extends ServiceBase {
  constructor() {
    super("trade", ServiceBase.getDaoName(StOrderItemService));
    this.storderDao = system.getObject("db.trade.storderDao");
    this.dictionary = system.getObject("util.dictionary");
  }

  async pageByCondition(params) {
    let page = {count: 0, rows: []};
    params.currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);
    params.startRow = (params.currentPage - 1) * params.pageSize;

    page.count = await this.dao.countByCondition(params);
    if (page.count == 0) {
      return system.getResultSuccess(page);
    }

    page.rows = await this.dao.listByCondition(params);
    if (page.rows) {
      for (var row of page.rows) {
        this.handleDate(row, ["created_at"], null);
      }
      this.dictionary.setRowsName("ORDER_ITEM", page.rows, ["trade_status"]);
    }
    return system.getResultSuccess(page);
  }

  async tradeOfflineCB(params) {
    let item_ids = params.item_ids || [];
    if (item_ids.length == 0) {
      return system.getResultSuccess();
    }

    let trade_time = params.trade_time;
    if(!trade_time) {
      return system.getResult(null, "请填写交易时间");
    }

    let order = await this.storderDao.findById(params.order_id);
    if (order.check_status != "05") {
      return system.getResult(null, "批次未审核");
    }
    if(order.trade_mode == "00") {
      return system.getResult(null, "批次未触发打款");
    }

    let itemParams = {ids: item_ids, trade_desc: params.trade_desc, trade_time: params.trade_time};
    let countParams = {order_id: order.id, trade_status: "00"};
    let orderParams = {id: order.id};

    let self = this;
    await this.db.transaction(async t => {
      await self.dao.updateTrade(itemParams, t);
      let count = await self.dao.countItems(countParams, t);
      if(count == order.item_count) {}
      orderParams.trade_status = count == order.item_count ? "00" : "03";
      await self.storderDao.update(orderParams, t);
      return order;
    });
    return system.getResultSuccess();
  }
  async tradeOnlineCB(params) {
  }
}

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