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");
    this.dictionary = system.getObject("util.dictionary");
  }

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

  // 打款列表页
  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", page.rows, ["order_type", "acc_type", "trade_mode", "trade_status", "check_status"]);
    }
    return system.getResultSuccess(page);
  }

  async info(params) {
    let order = await this.dao.getById(params.id);
    if (!order) {
      return system.getResult(null, "批次不存在");
    }
    this.handleDate(order, ["created_at"], null);
    this.dictionary.setRowName("ORDER", order, ["order_type", "acc_type", "trade_mode", "trade_status", "check_status"]);
    return system.getResultSuccess(order);
  }

  // 保存打款信息
  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.autoIncrement = true;
        item.order_id = order.id;
        item.order_type = order.order_type;
        item.saas_merchant_id = order.saas_merchant_id;
        item.out_trade_no = order.out_trade_no;
        item.saas_id = order.saas_id;
      }
      await self.storderitemDao.bulkCreate(itemList, t);
      await self.storderitemDao.genTradeNo(order.id, t);
      return order;
    });

    return system.getResultSuccess(order);
  }

  async pay(params) {
    let type = this.trim(params.type);
    let rs;
    if (type === "offline") {
      rs = await this.offlinePay(params);
    } else {
      return system.getResult(null, "暂不支持在线付款");
    }
    return rs;
  }

  async offlinePay(params) {
    let id = this.trim(params.id);
    let order = await this.dao.findById(id);
    if (!order) {
      return system.getResult(null, "批次不存在");
    }
    if (order.pay_voucher) {
      // 防止重复更新
      return system.getResultSuccess();
    }
    if (!params.pay_voucher) {
      return system.getResult(null, "请上传凭证");
    }
    order.pay_voucher = this.trim(params.pay_voucher);

    let pay_bank_account = this.trim(params.pay_bank_account);
    if (pay_bank_account) {
      order.pay_bank_account = pay_bank_account;
    }
    let pay_bank_name = this.trim(params.pay_bank_name);
    if (pay_bank_name) {
      order.pay_bank_name = pay_bank_name;
    }
    let pay_bank_no = this.trim(params.pay_bank_no);
    if (pay_bank_no) {
      order.pay_bank_no = pay_bank_no;
    }
    // 一审
    order.check_status = "01";
    await order.save();
    return system.getResultSuccess();
  }

  // 一审
  async audit1(params) {
    let _params = {
      id: this.trim(params.id),
      pre: "01",
      status: Number(params.status || 0) == 1 ? "03" : "02",
      remark: params.remark,
      auditType: 1
    }
    return await this.doAudit(_params);
  }

  // 二审
  async audit2(params) {
    let _params = {
      id: this.trim(params.id),
      pre: "03",
      status: Number(params.status || 0) == 1 ? "05" : "04",
      remark: params.remark,
      auditType: 2
    }
    return await this.doAudit(_params);
  }

  async doAudit(params) {
    let id = this.trim(params.id);
    let pre = this.trim(params.pre);
    let status = params.status;
    let remark = this.trim(params.remark);
    let auditType = params.auditType;

    let auditName = auditType === 1 ? "一审" : "二审";
    remark = this.trim(remark);
    if (!remark) {
      return system.getResult(null, `请填写${auditName}备注`);
    }

    let order = await this.dao.findById(id);
    this.dictionary.setRowName("ORDER", order, ["check_status"]);
    if (!order) {
      return system.getResult(null, "批次不存在");
    }
    if (order.check_status !== pre) {
      return system.getResult(null, `${auditName}失败，当前状态为[${order.check_status_name}]`);
    }

    order[`check${auditType}_remark`] = remark;
    order.check_status = status;
    await order.save();
    return system.getResultSuccess();
  }

  // 打款
  async trade(params) {
    // 打款模式 01系统打款 02手工打款
    let trade_mode = this.trim(params.trade_mode);
    if (!trade_mode || ["01", "02"].indexOf(trade_mode) == -1) {
      return system.getResult(null, "打款模式错误");
    }

    if (trade_mode == "01") {
      return system.getResult(null, "系统打款正在开发中，暂时只支持手工打款");
    }

    let order = await this.dao.findById(params.id);
    if (!order) {
      return system.getResult(null, "批次不存在");
    }
    if (order.check_status != "05") {
      return system.getResult(null, "批次未审核通过，请等待审核操作");
    }
    if (order.trade_mode != "00") {
      return system.getResult(null, "批次已经操作过打款，不要重复操作");
    }
    order.trade_mode = trade_mode;
    order.trade_status = "01";
    await order.save();
    return system.getResultSuccess(order);
  }
}

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