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_status: params.trade_status,
      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) {}
  async updateInvoice(params) {
    let rs = await this.dao.updateInvoice(params);
    return system.getResult(rs);
  }
  async cancelInvoice(params) {
    let rs = await this.dao.cancelInvoice(params);
    return system.getResult(rs);
  }

  async byIds(params) {
    let list = await this.dao.byIds(params);
    return system.getResultSuccess(list);
  }

  async bySaasInvoiceId(params) {
    let rs = await this.dao.bySaasInvoiceId(params);
    return system.getResultSuccess(rs);
  }


  /**
   * 根据 invoice_id 和 order_type  查询交易流水
   * @param {*} params 
   */
  async invoiceTrade(params){
    if(!params.id){
      return system.getResult(null, `参数错误 ID不能为空`);
    }
    if(!params.order_type){
      return system.getResult(null,`订单类型不能为空`);
    }
    try {
      let tparam = {order_type:this.trim(params.order_type)};
      if (params.data_ids && params.data_ids.length > 0) {
        tparam.data_ids = params.data_ids;
      } else if (params.id) {
        tparam.saas_invoice_id = params.id;
      } else {
        return system.getResult([]);
      }
      let res = await this.dao.invoiceTrade(tparam) || [];
      for(let item of res){
        this.handleDate(item, ['updated_at', 'created_at'], 'YYYY-MM-DD HH:mm:ss');
      }          
      return system.getResult(res);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误`);
    }
  }

  /**
   * 根据统一社会信用代码获取所有的订单流水
   * @param params
   * @returns {Promise<void>}
   */
  async tradeItemBycreditCode(params){
    if(!(params.credit_code_array instanceof  Array) && params.credit_code_array.length <0){
      return system.getResult(null, `参数格式错误`);
    }

    try{
      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.invoiceTrade(params);
      if(page.rows){
        for (let item of  page.rows) {
          this.handleDate(item, ["created_at","trade_time"], null);
          item.amt = system.f2y(item.amt);
          item.actual_amt = system.f2y(item.actual_amt);
          item.deduct_amt = system.f2y(item.deduct_amt);
          item.service_tax = system.f2y(item.service_tax);
          if(item.order_type == "10"){//00未设置 10平台交易 20商户交易
            item.order_type_name = "平台交易";
          }else if(item.order_type=="20"){
            item.order_type_name = "商户交易";
          }else{
            item.order_type_name = "未设置";
          }
          if(item.trade_status=="00"){//交易状态 00 成功 01 待处理 02 失败
            item.trade_status_name = "成功";
          }else if(item.trade_status=="01"){
            item.trade_status_name = "待处理";
          }else if(item.trade_status=="02"){
            item.trade_status_name = "失败";
          }else{
            item.trade_status_name = "";
          }
        }
      }

      return system.getResult(page);
    }catch (e) {
      console.log(e);
      return system.getResult(null, `系统错误`);
    }
  }

  /***
   * fn:根据ID取消发票关联
   * @param params
   * @returns {Promise<void>}
   */
  async cancelInvoiceByDataIds(params){
    if(!params.data_ids ||  params.data_ids.length==0) {
      return system.getResult(null, `参数错误 DATA_IDS 不能为空`);
    }
    try{
      let res = await this.dao.cancelInvoiceByDataIds(params);
      return res;
    }catch (e) {
      console.log(e);
      return system.getResult(null, `系统错误`);
    }
  }
}
module.exports = StOrderItemService;