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

class StOrderService extends ServiceBase {
  constructor() {
    super("trade", ServiceBase.getDaoName(StOrderService));
    this.storderitemDao = system.getObject("db.trade.storderitemDao");
  }

  async test(params) {
    return system.getResultSuccess("test");
  }

  // 打款列表页
  async orderPage(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, -8);
      }

      await this.setBminfo(page.rows);
      await this.setOrderStatus(page.rows);
    }
    return system.getResultSuccess(page);
  }

  // 保存打款信息
  async saveOrder(order) {
    if (!order) {
      return system.getResult(null, "订单不存在");
    }
    let itemList = order.itemList || [];

    if (itemList.length == 0) {
      return system.getResult(null, "订单明细不存在");
    }

    let self = this;
    order = await this.db.transaction(async t => {
      order = await self.dao.create(order, t);

      for (let item of itemList) {
        item.order_id = order.id;
        item.saas_merchant_id = order.saas_merchant_id;
        item.out_trade_no = order.out_trade_no;
        item.saas_id = order.saas_id;
        item.trade_status = "01";
      }
      await self.storderitemDao.bulkCreate(itemList, t);
      return order;
    });

    return system.getResultSuccess(order);
  }


  // 详情

  // 保存打款信息

  // 付款申请提交

  // 一审

  // 二审

  // 打款

  // 结果反馈-批量

  // 交易列表页


  async page(params) {
    let currentPage = Number(params.currentPage || 1);
    let pageSize = Number(params.pageSize || 10);

    let where = {};
    if (params.id) {
      where.id = this.trim(params.id);
    }
    if (params.name) {
      where.name = this.trim(params.name);
    }
    let orderby = [
      ["id", 'desc']
    ];

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

}

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