const system = require("../../../system");
const ServiceBase = require("../../svems.base")
const settings = require("../../../../config/settings")
const axios = require("axios");
class SaasinvoiceService extends ServiceBase {
  constructor() {
    super();
    this.DEFAULT_BUSINESSMEN_TYPE = "10";   //默认的 销售方类型  个体工商户
    this.DEFAULT_CHANNEL_ID = "2";          //默认的 渠道类型
    this.tradeSve = system.getObject("service.trade.tradeSve");
  }

  async platforminvoicePage(params) {
    let rs = await this.callms("invoice", "platforminvoicePage", params);
    if (rs && rs.data && rs.data.rows) {
      this.transField(rs.data.rows);
    }
    return rs;
  }


  async platforminvoiceapplyPage(params) {
    let rs = await this.callms("invoice", "platforminvoiceapplyPage", params);
    if (rs && rs.data && rs.data.rows) {
      this.transField(rs.data.rows);
    }
    return rs;
  }

  async audit(params) {
    let rs = await this.callms("invoice", "invoiceapplyAudit", params);
    return rs;
  }

  async makeout(params) {
    let rs = await this.callms("invoice", "invoiceapplyMakeOut", params);
    return rs;
  }

  async invoiceapplyById(params) {
    let rs = await this.callms("invoice", "invoiceapplyById", params);
    return rs;
  }

  async applyBulkSave(params) {
    let rs = await this.callms("invoice", "invoiceapplyBulkSave", params);
    return rs;
  }

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

    for (let row of rows) {
      row.invoice_amount = system.f2y(row.invoice_amount);
      row.personal_invoice_tax = system.f2y(row.personal_invoice_tax);
      row.additional_tax = system.f2y(row.additional_tax);
      row.value_added_tax = system.f2y(row.value_added_tax);
      row.service_tax = system.f2y(row.service_tax);
    }
  }

  async invoiceapplyStatus(params) {
    let rs = await this.callms("invoice", "invoiceapplyStatus", params);
    return rs;
  }

  async platformHandle(params) {
    let apply = await this.invoiceapplyById(params);
    apply = apply.data;
    if (!apply) {
      return system.getResult(null, "发票申请不存在");
    }
    if (apply.status != "1010") {
      return system.getResult(null, "发票状态错误，请刷新重试");
    }
    // TODO 总统 推送发票信息 begin
    let res = await this.pushInvoiceToDeliver(apply);
    // TODO 总统 推送发票信息 end
    if(!res || !res.data || res.status!=0){
      return system.getResult(null  ,`发票推送失败`);
    }else{
      let updateStatus = {
        id: apply.id,
        preStatus: "1010",
        status: "1050",
      };
      let rs = await this.invoiceapplyStatus(updateStatus);
      return rs;
    }
  }

  /**
   * fn：发票推送
   * @param {*} params 
   */
  async saveSaasInvoice(params) {
    var rs = await this.callms("invoice", "saveSaasInvoice", params);
    return rs;
  }

  /**
   * fn:发票申请推送到交付系统
   * @param {*} invoice   发票实体对象
   * 
   *  1. 开票方类型  不存在 （目前默认是个体工商户）
   *  2. 开票内容    不存在
   *  3. 核对channel ID 是不是SAAS_ID
   *  4. 申请时间    不存在
   */
  async pushInvoiceToDeliver(invoice) {
    let params = {
      "businessmen_type": this.DEFAULT_BUSINESSMEN_TYPE,
      "businessmen_id": invoice.from_id || "",
      "businessmen_credit_code": invoice.from_credit_code,
      "businessmen_name": invoice.from_name,
      "businessmen_addr": invoice.from_addr,
      "businessmen_mobile": invoice.from_mobile,
      "businessmen_bank": invoice.from_bank || "",
      "businessmen_account": invoice.from_account || "",
      "mail_to": invoice.mail_to,
      "mail_mobile": invoice.mail_mobile,
      "mail_addr": invoice.mail_addr,
      "merchant_id": invoice.to_id || "",
      "merchant_name": invoice.to_name,
      "merchant_credit_code": invoice.to_credit_code,
      "merchant_addr": invoice.to_addr,
      "merchant_mobile": invoice.to_mobile,
      "merchant_bank": invoice.to_bank,
      "merchant_account": invoice.to_account,
      "apply_no": invoice.id,
      "invoice_type": invoice.invoice_type,
      "apply_time": invoice.created_at,
      "invoice_amount": invoice.invoice_amount,
      "invoice_content": invoice.invoice_content || "",
      "personal_invoice_tax": invoice.personal_invoice_tax || 0,
      "additional_tax": invoice.additional_tax || 0,
      "value_added_tax": invoice.value_added_tax || 0,
      "channel_id": this.DEFAULT_CHANNEL_ID,
      "saas_deliver_api": settings.outApi().deliverNotifyApi,
      "product_id":"50010000",
      "unit": invoice.unit || 0,
      "quantity": invoice.quantity || 0,
      "price": invoice.price || 0,
      "remark":invoice.remark || ""
  }

    let url = settings.deliverSysApi().pushInvoiceToDeliver;
    let res = await axios({
      method: 'post',
      url: url,
      data: params
    });
    console.log("invoice handle push result：", res.data);
    return res.data;
  }

  /**
   * fn:查询发票(saas_invoice,saas_invoice_apply,st_order_item)详细信息
   * @param params
   * @returns {Promise<void>}
   */
  async queryInvoiceStOrderItem(params){
    try{
      //将saas_invoice 和saas_invoice_apply的信息查出来
      let res = await this.callms("invoice", "saasInvoiceInfo", params);
      if(res.status!=0 || !res.data){
        return system.getResult(null,'网络请求超时');
      }
      let saasInvoice = res.data;
      //将对应的交易流水也查出来 st_order_item
      let invoiceOrderRes = await this.callms("order", "saasOrderPage", { saas_invoice_id: this.trim(params.id) ,currentPage:1,pageSize:99999});
      if (invoiceOrderRes.status == 0) {
        invoiceOrderRes = invoiceOrderRes.data.rows || [];
      }
      saasInvoice.service_tax=system.f2y(saasInvoice.service_tax);
      saasInvoice.invoiceOrder = invoiceOrderRes;
      return system.getResult(saasInvoice);
    }catch (e) {
      console.log(e);
      return system.getResult(null,`系统错误`);
    }
  }
  /**
   * 查询发票(saas_invoice,saas_invoice_apply,st_order_item)详细信息
   * @param {*} params
   */
  async queryInvoiceTrad(params) {
    try {
      let saasInvoiceApply = await this.callms("invoice", "saasInvoiceInfo", params);

      if (saasInvoiceApply.status != 0 || !saasInvoiceApply.data) {
        return system.getResult(null, `系统错误`);
      }
      saasInvoiceApply = saasInvoiceApply.data;
      let tradOrder = [];
      if (saasInvoiceApply.fee_type == "00") { //个体户注册订单
        tradOrder = [];
      } else { //查询流水
        if(saasInvoiceApply.data_ids ){
          saasInvoiceApply.data_ids = saasInvoiceApply.data_ids.split(',');
        }
        let tradOrderRes =await this.callms("trade", "invoiceTrade", {
          id: saasInvoiceApply.id,
          order_type: saasInvoiceApply.fee_type,
          data_ids:saasInvoiceApply.data_ids || []
        }) || {};
        if (tradOrderRes.status == 0) {
          tradOrder = tradOrderRes.data;
        }
      }
      saasInvoiceApply.tradOrder = tradOrder;
      return system.getResult(saasInvoiceApply);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误`);
    }
  }


  /**
   * 发票详情
   * @param {*} params
   */
  async invoiceOrder(params) {
    try {
      let saasInvoiceApply = await this.callms("invoice", "saasInvoiceInfo", params);

      if (saasInvoiceApply.status != 0 || !saasInvoiceApply.data) {
        return system.getResult(null, `系统错误`);
      }
      saasInvoiceApply = saasInvoiceApply.data;
      let tradOrder = [];
      if (saasInvoiceApply.fee_type == "00") { //个体户注册订单
        let invoiceOrderRes = await this.callms("order", "saasOrderPage", { saas_invoice_id: this.trim(params.id) ,currentPage:1,pageSize:99999});
        if (invoiceOrderRes.status == 0) {
          tradOrder = invoiceOrderRes.data.rows || [];
        }
      } else { //查询流水
        let tradOrderRes = await this.tradeSve.invoiceTrade({
          id: saasInvoiceApply.id,
          order_type: saasInvoiceApply.fee_type
        });
        if (tradOrderRes.status == 0) {
          tradOrder = tradOrderRes.data;
        };
        saasInvoiceApply.service_tax=system.f2y(saasInvoiceApply.service_tax);
      }
      saasInvoiceApply.tradOrder = tradOrder;
      return system.getResult(saasInvoiceApply);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误`);
    }
  }

  /**
   * fn:根据ID 查询详情
   * @param params
   * @returns {Promise<{msg: *, data, bizmsg: *|string, status: number}|any|undefined>}
   */
  async getSaasInvoiceById(params){
    let rs = await this.callms("invoice", "getSaasInvoiceById", params);
    return rs;
  }
}
module.exports = SaasinvoiceService;