const system = require("../../../system");
const ServiceBase = require("../../svems.base")
const settings = require("../../../../config/settings")
const axios = require("axios");

class OrderService extends ServiceBase {
  constructor() {
    super();
  }

  async microAdd(params) {
    var rs = await this.callms("order", "saasOrderMicroAdd", params);
    return rs;
  }

  async info(params) {
    var rs = await this.callms("order", "saasOrderInfo", params);
    return rs;
  }

  async platformInfo(params) {
    var rs = await this.callms("order", "saasOrderPlatformOrderInfo", params);
    return rs;
  }

  async page(params) {
    var rs = await this.callms("order", "saasOrderPage", params);
    if (rs && rs.data && rs.data.rows) {
      this.transOrderField(rs.data.rows);
    }
    return rs;
  }
  async audit(params) {
    var rs = await this.callms("order", "saasOrderBulkAudit", params);

    if(params.audit_status == "20" && rs.status === 0 && params.ids && params.ids.length > 0) {
      for(let id of params.ids) {
        this.pushOrderToDeliver(id);
      }
    }
    return rs;
  }

  async pushOrderToDeliver(id) {
    let order = await this.callms("order", "saasOrderInfo", {id: id}) || {};
    order = order.data;
    if (!order) {
      return;
    }
    let notifyApi = settings.outApi().deliverNotifyApi;
    let data = {
      product_id: order.product_id,
      source_id: 1002,
      source_no: order.id,
      customer_name: order.bminfo.legal_name,
      contact_mobile: order.bminfo.legal_mobile,
      desc: "saas个体户注册",
      saas_deliver_api: notifyApi,
      bminfo: order.bminfo,
    };

    // 推送订单到交付平台
    let url = settings.deliverSysApi().orderPushApi;
    let res = await axios({
      method: 'post',
      url: url,
      data: data
    });
    console.log(res.data);
    if(res.status == 200 && res.data && res.data.status == 0 && res.data.data) {
      await this.updateOrder({id: id, deliver_order_id: res.data.data.id});
    }
  }

  async updateOrder(params) {
    let rs = await this.callms("order", "saasOrderUpdate", params);
    return rs;
  }

  // 服务交付
  async sveDeliver(params) {
    let rs = await this.callms("order", "saasOrderSveDeliver", params);
    return rs;
  }

  // 服务交付
  async sveBusinessmen(params) {
    let rs = await this.callms("order", "saasOrderBusinessmen", params);
    return rs;
  }
  // 交付信息 map by 信用代码
  async mapByCreditCodes(params) {
    let rs = await this.callms("order", "saasBusinessmenMapByCreditCodes", params);
    return rs;
  }

  async deliver(params) {
    var rs = await this.callms("order", "saasOrderBulkDeliver", params);
    return rs;
  }

  transOrderField(rows) {
    if (!rows || rows.length == 0) {
      return;
    }

    for (let row of rows) {
      row.price = system.f2y(row.price);
    }
  }
}
module.exports = OrderService;