const system = require("../../../system");
const ServiceBase = require("../../svems.base")
const settings = require("../../../../config/settings")
class InvoiceService extends ServiceBase {
  constructor() {
    super();
    this.status = {
      "0090": {
        "status": "0090",
        "name": "未付款",
        "next": "1000",
        "cstatus": "0090", //客户
        "dstatus": "", //交付商
      },
      "1000": {
        "status": "1000",
        "name": "待审核",
        "next": "1020",
        "cstatus": "0090", //客户
        "dstatus": "", //交付商
      },
      "1010": {
        "status": "1010",
        "name": "审核不通过",
        "next": "",
        "cstatus": "1010",
        "dstatus": "",
      },
      "1020": {
        "status": "1020",
        "name": "待分配",
        "next": "1030",
        "cstatus": "1030",
        "dstatus": "",
      },
      "1030": {
        "status": "1030",
        "name": "待处理",
        "next": "1050",
        "cstatus": "1030",
        "dstatus": "1030",
      },
      "1040": {
        "status": "1040",
        "name": "交付商关闭",
        "next": "1020",
        "cstatus": "1030",
        "dstatus": "1040",
      },
      "1050": {
        "status": "1050",
        "name": "已开具",
        "next": "1060",
        "cstatus": "1050",
        "dstatus": "1050",
      },
      "1060": {
        "status": "1060",
        "name": "待审核",
        "next": "1070",
        "cstatus": "1050",
        "dstatus": "1070",
      },
      "1070": {
        "status": "1070",
        "name": "审核通过",
        "next": "1080",
        "cstatus": "1050",
        "dstatus": "1070",
      },
      "1080": {
        "status": "1080",
        "name": "已邮寄",
        "next": "1090",
        "cstatus": "1050",
        "dstatus": "1080",
      },
      "1090": {
        "status": "1090",
        "name": "完成",
        "next": "1100",
        "cstatus": "1090",
        "dstatus": "1080",
      },
      "1100": {
        "status": "1090",
        "name": "发票撤回",
        "next": "1100",
        "cstatus": "1090",
        "dstatus": "1080",
      },
      "1200": {
        "status": "1200",
        "name": "红冲",
        "next": "",
        "cstatus": "1200",
        "dstatus": "",
      },
      "1300": {
        "status": "1300",
        "name": "审核失败(平台第二次审核)",
        "next": "1060",
        "cstatus": "1050",
        "dstatus": "1060",
      }
    };

    this.invoiceConfig = {
      498781: {
          uploadPeriod: "201910",
          companyId: "102",
          customerId: "498781",
          userId: 43,
      },
      498782: {
          uploadPeriod: "201910",
          companyId: "102",
          customerId: "498782",
          userId: 43,
      },
    }
  }

  async apiCalcInvoice(pobj) {
    var merchantId = pobj.merchant_id || pobj.merchantId;
    var invoiceList = pobj.invoiceList;
    if (!invoiceList || invoiceList.length == 0) {
      return system.getResult(null, "请传入试算开票信息");
    }
    var creditCodes = [];
    for (var invoice of invoiceList) {
      creditCodes.push(invoice.businessmenCreditCode);
    }

    // 查询个体户签约信息
    var mapRs = await this.callms("order", "businessmenCompleteMapByCreditCodes", {
      creditCodes: creditCodes
    });
    var map = mapRs.data;
    var result = [];
    for (var invoice of invoiceList) {

      var calc = {
        creditCode: invoice.businessmenCreditCode,
        incomeTax: 0,
        addedValueTax: 0,
        serviceTax: 0,
        specialTax: 0,
        warning: "",
        monthAmt: 0,
      };

      var signInfo = map[invoice.businessmenCreditCode];
      if (!signInfo) {
        calc.code = -1;
        calc.msg = "个体工商户【" + invoice.businessmenCreditCode + "】不存在";
        result.push(calc);
        continue;
      }

      invoice.invoiceAmount = Number(invoice.invoiceAmt);
      invoice.invoiceTime = this.trim(invoice.invoiceTime);
      invoice.businessmenCreditCode = this.trim(invoice.businessmenCreditCode);
      invoice.businessmenType = this.trim(invoice.businessmenType) || "10";
      invoice.ruleCode = this.trim(invoice.ruleCode) || "10";
      invoice.perCalWay = signInfo.taxUpType; // TODO 确定值
      invoice.valCalWay = signInfo.addValueUpType; // TODO 确定值

      invoice.businessmenId = signInfo.id;
      invoice.serviceRate = system.f2y(signInfo.serviceRate);
      invoice.taxCostPriRat = system.f2y(signInfo.costRate);
      invoice.taxIncPriRat = system.f2y(signInfo.taxRate);
      if (invoice.type == 1) {
        invoice.perIncTaxRange = JSON.parse(signInfo.specialTaxLadder);
        invoice.valAddTaxRange = JSON.parse(signInfo.specialOtherLadder);
      } else {
        invoice.perIncTaxRange = JSON.parse(signInfo.commonTaxLadder);
        invoice.valAddTaxRange = JSON.parse(signInfo.commonOtherLadder);
      }

      try {
        console.log(JSON.stringify(invoice));
        var rs = await this.callms("invoice", "verificationAndCalculation", invoice);
        if (rs.status == 0 && rs.data) {
          var calcRs = rs.data;
          calc.code = 1;
          calc.incomeTax = Number(calcRs.personalIncomeTax || 0).toFixed(0);
          calc.addedValueTax = Number(calcRs.valueAddedTax || 0).toFixed(0);
          calc.serviceTax = Number(calcRs.serviceCharge || 0).toFixed(0);
          calc.specialTax = Number(calcRs.additionalTax || 0).toFixed(0);
          calc.warning = this.trim(calcRs.warning);
          calc.monthAmt = 0;
          calc.msg = "success";
        } else {
          calc.code = -1;
          calc.msg = rs.msg || "发票服务异常";
        }
        console.log(rs);
      } catch (error) {
        calc.code = -1;
        calc.msg = "发票服务异常，请联系公司宝";
        console.log(error);
      }
      result.push(calc);
    }
    return system.getResultSuccess(result);
  }

  async apiVerificationAndCalculation(pobj) {
    pobj.serviceRate = Number(pobj.serviceRate) * 100;
    pobj.taxIncPriRat = Number(pobj.taxIncPriRat) * 100;
    pobj.taxCostPriRat = Number(pobj.taxCostPriRat) * 100;
    pobj.invoiceAmount = system.y2f(pobj.invoiceAmount);

    var rs = await this.callms("invoice", "verificationAndCalculation", pobj);
    if (rs.status == 0) {
      return rs
    } else {
      return system.getResult(null, rs.msg);
    }
  }

  async apiSaveInvoice(pobj) {
    var merchantId = pobj.merchant_id || pobj.merchantId;
    var invoiceList = pobj.invoiceList;
    if (!invoiceList || invoiceList.length == 0) {
      return system.getResult(null, "请传入试算开票信息");
    }
    var creditCodes = [];
    for (var invoice of invoiceList) {
      creditCodes.push(invoice.businessmenCreditCode);
    }

    // 查商户titile
    var merchantRs = await this.callms("merchant", "getById", {
      id: merchantId
    });
    var merchant = merchantRs.data || {};

    var title = await this.callms("merchant", "getMerchantTitleDefault", {
      merchantId: merchantId
    });

    title = title.data;
    var address = await this.callms("merchant", "getMerchantAddressDefault", {
      merchantId: merchantId
    });
    var address = address.data || {};

    // 查询个体户签约信息
    var mapRs = await this.callms("order", "businessmenCompleteMapByCreditCodes", {
      creditCodes: creditCodes
    });
    var map = mapRs.data;
    var result = [];
    for (var invoice of invoiceList) {
      var data = {
        creditCode: invoice.businessmenCreditCode,
        code: 1,
        msg: "success",
        applyNo: invoice.applyNo,
      };

      var signInfo = map[invoice.businessmenCreditCode];
      if (!signInfo) {
        data.code = -1;
        data.msg = "个体工商户【" + invoice.businessmenCreditCode + "】不存在";
        result.push(data);
        continue;
      }
      // 发票类型：10 普通发票 20 增值税专用发票 30 电子发票
      if (invoice.type === 0) {
        invoice.type == "10";
      } else if (invoice.type === 1) {
        invoice.type == "20";
      } else {
        invoice.type == "30";
      }
      // 购买方
      invoice.merchantId = merchantId;
      invoice.merchantName = merchant.name;
      invoice.merchantCreditCode = title.taxNo;
      invoice.merchantAddr = title.invoiceAddr;
      invoice.merchantMobile = title.invoiceMobile;
      invoice.merchantBank = title.accountName;
      invoice.merchantAccount = title.accountPublic;

      // 申请方联系电话
      invoice.applyPhone = merchant.contactMobile;

      // 邮寄地址
      invoice.mailAddr = address.mailAddr;
      invoice.mailMobile = address.mailMobile;
      invoice.mailTo = address.mailTo;

      invoice.invoiceAmount = Number(invoice.invoiceAmt);
      invoice.invoiceTime = this.trim(invoice.invoiceTime);
      invoice.businessmenCreditCode = this.trim(invoice.businessmenCreditCode);


      // 开票内容
      if (signInfo.invoicecontents && signInfo.invoicecontents.length > 0) {
        invoice.invoiceContent = signInfo.invoicecontents[0].invoicecontentName;
      } else {
        invoice.invoiceContent = "服务费";
      }

      invoice.settleImg = "";
      invoice.statements = invoice.settleImg;
      invoice.contract = "";

      invoice.applyNo = invoice.applyNo;
      invoice.perCalWay = signInfo.taxUpType;
      invoice.valCalWay = signInfo.addValueUpType;

      // 销售方信息
      invoice.businessmenType = this.trim(invoice.businessmenType) || "10";
      invoice.ruleCode = this.trim(invoice.ruleCode) || "10";
      invoice.businessmenId = signInfo.id;
      invoice.businessName = signInfo.name;
      invoice.isBank = signInfo.isBank;
      invoice.taxAuthorities = signInfo.taxOrg;

      // invoice.taxCostPriRat = signInfo.costRate;
      // invoice.taxIncPriRat = signInfo.taxRate;

      invoice.serviceRate = system.f2y(signInfo.serviceRate);
      invoice.taxCostPriRat = system.f2y(signInfo.costRate);
      invoice.taxIncPriRat = system.f2y(signInfo.taxRate);

      if (invoice.type == 1) {
        invoice.perIncTaxRange = JSON.parse(signInfo.specialTaxLadder);
        invoice.valAddTaxRange = JSON.parse(signInfo.specialOtherLadder);
      } else {
        invoice.perIncTaxRange = JSON.parse(signInfo.commonTaxLadder);
        invoice.valAddTaxRange = JSON.parse(signInfo.commonOtherLadder);
      }

      try {
        var rs = await this.callms("invoice", "saveInvoice", invoice);
        if (rs.status != 0) {
          data.code = -1;
          data.msg = rs.msg || "发票服务异常";
        }
        console.log(rs);
      } catch (error) {
        data.code = -1;
        data.msg = "发票服务异常，请联系公司宝";
        console.log(error);
      }
      result.push(data);
    }

    return system.getResultSuccess(result);
  }

  async apiCancelInvoice(pobj) {
    var params = {
      applyNo: pobj.applyNo,
      merchantId: pobj.merchantId || pobj.merchant_id
    }

    var rs = await this.callms("invoice", "apiCancelInvoice", params);
    if (rs.data) {
      rs.data = null;
    }
    return rs;
  }

  async apiQueryInvoice(pobj) {
    var params = {
      applyNo: pobj.applyNo,
      merchantId: pobj.merchantId || pobj.merchant_id
    }
    // queryInvoices
    var rs = await this.callms("invoice", "queryInvoice", params);
    if (rs.status != 0 || !rs.data) {
      return system.getResult(null, "发票不存在");
    }
    var invoiceApply = rs.data || {};

    var invoice = invoiceApply.invoice || {};

    var result = {
      "merchantId": this.trim(invoiceApply.merchantId),
      "applyNo": this.trim(invoiceApply.applyNo),
      "status": this.trim(invoiceApply.customerStatus),
      "auditRemark": this.trim(invoiceApply.remark),
      "invoiceNo": this.trim(invoiceApply.id),
      "payVoucher": this.trim(invoiceApply.statements),

      "courierImg": "",

      "courierNo": this.trim(invoice.mailNo),
      "invoiceTime": this.trim(invoice.invoiceTime),
      "invoiceImg": this.trim(invoice.invoiceImg),
      "complateTax": this.trim(invoice.complateTax),
      "taxNo": this.trim(invoice.taxNo),
      "taxTime": this.trim(invoice.taxTime),
      "taxVoucher": this.trim(invoice.taxVoucher),
    }
    return system.getResultSuccess(result);
  }

  async apiQueryTaxInvoice(pobj) {

    var params = {
      applyNo: pobj.applyNo,
      merchantId: pobj.merchantId || pobj.merchant_id,
      id: pobj.id
    }
    // queryInvoices
    var rs = await this.callms("invoice", "getByApplyNo", params);
    if (rs.status != 0 || !rs.data) {
      return system.getResult(null, "发票不存在");
    }
    var invoice = rs.data || {};
    var paytaxes = invoice.paytaxes || {};
    this.handleDate(paytaxes, ["payTaxesTime"], "YYYY-MM-DD", -8);
    var result = {
      "merchantId": this.trim(invoice.merchantId),
      "applyNo": this.trim(invoice.applyNo),
      "taxNo": this.trim(paytaxes.payTaxesNo),
      "taxTime": this.trim(paytaxes.payTaxesTime),
      "taxVoucher": this.trim(paytaxes.payTaxesImg),
    }
    return system.getResultSuccess(result);
  }

  /**
   * 发票明细（平台）
   * @param {*} pobj
   * @param {string} id
   * @param {string} applyNo
   * @param {string} merchant_id
   */
  async apiQueryInvoiceAdmin(pobj) {
    var params = {
      applyNo: pobj.applyNo,
      merchantId: pobj.merchantId || pobj.merchant_id,
      id: pobj.id || null
    }
    var res = await this.callms("invoice", "queryInvoice", params);
    if (res.status != 0 || !res.data) {
      return system.getResult(null, "发票不存在");
    }
    res.data.invoiceAmount = system.f2y(res.data.invoiceAmount);
    res.data.personalIncomeTax = system.f2y(res.data.personalIncomeTax);
    res.data.additionalTax = system.f2y(res.data.additionalTax);
    res.data.valueAddedTax = system.f2y(res.data.valueAddedTax);
    res.data.serviceCharge = system.f2y(res.data.serviceCharge);
    res.data.isBank = res.data.isBank == 1 ? "已开户" : "未开户";
    if (res.data.type == 10) {
      res.data.type = "普通发票";
    } else if (res.data.type == 20) {
      res.data.type = "增值税专用发票";
    } else {
      res.data.type = "电子发票"
    }
    res.data.payWay = res.data.payWay == "20" ? "线上支付" : "系统账户扣款";
    res.data.isPay = res.data.isPay == 1 ? "已支付" : "未付款";
    res.data.isInvalid = res.data.isInvalid === 2 ? '未红冲' : '已红冲';
    res.data.deliverer.delivererAmount = system.f2y(res.data.deliverer.delivererAmount);
    res.data.invoice.complateTax = res.data.invoice.complateTax == "1" ? "已完税" : "未完税";

    this.handleDate(res.data, ["invoiceTime"], "YYYY-MM-DD", -8);
    this.handleDate(res.data, ["createdAt"], "YYYY-MM-DD", -8);
    this.handleDate(res.data['deliverer'], ["createdAt"], "YYYY-MM-DD", -8);
    this.handleDate(res.data['deliverer'], ["updatedAt"], "YYYY-MM-DD", -8);
    this.handleDate(res.data['invoice'], ["invoiceTime"], "YYYY-MM-DD", -8);
    this.handleDate(res.data['invoice'], ["taxTime"], "YYYY-MM-DD", -8);
    this.handleDate(res.data["invoice"], ["createdAt"], "YYYY-MM-DD", -8);
    this.handleDate(res.data["invoice"], ["updatedAt"], "YYYY-MM-DD", -8);
    return res;
  }
  /**
   * 发票明细（交付商）
   * @param {*} pobj
   * @param {string} id
   * @param {string} applyNo
   * @param {string} merchant_id
   */
  async apiQueryInvoiceDeliverer(pobj) {
    var params = {
      applyNo: pobj.applyNo,
      merchantId: pobj.merchantId || pobj.merchant_id,
      id: pobj.id || null
    }
    var rs = await this.callms("invoice", "queryInvoiceDeliverer", params);
    if (rs.status != 0 || !rs.data) {
      return system.getResult(null, "发票不存在");
    }

    rs.data.invoiceAmount = system.f2y(rs.data.invoiceAmount);
    rs.data.personalIncomeTax = system.f2y(rs.data.personalIncomeTax);
    rs.data.additionalTax = system.f2y(rs.data.additionalTax);
    rs.data.valueAddedTax = system.f2y(rs.data.valueAddedTax);
    rs.data.serviceCharge = system.f2y(rs.data.serviceCharge);

    return rs;
  }
  /**
   * 校验审核
   * @param {*} pobj 
   */
  async apiVerification(pobj) {
    var params = {
      businessmenCreditCode: pobj.businessmenCreditCode
    }
    var rs = await this.callms("invoice", "verification", params);
    if (rs.status != 0) {
      return system.getResult(null, "发票不存在");
    }
    return rs;
  }
  /**
   * 试算
   * @param {*} pobj 
   */
  async apiCalcInvoice2(pobj) {

    pobj.serviceRate = Number(pobj.serviceRate || 0) * 100;
    pobj.taxIncPriRat = Number(pobj.taxIncPriRat || 0) * 100;
    pobj.taxCostPriRat = Number(pobj.taxCostPriRat || 0) * 100;
    pobj.invoiceAmount = system.y2f(pobj.invoiceAmount || 0);

    var rs = await this.callms("invoice", "verificationAndCalculation", pobj);
    if (rs.status == 0) {
      return rs
    } else {
      return system.getResult(null, rs.msg);
    }

  }

  /**
   * 保存发票申请(提供管理)
   * @param {*} pobj 
   */
  async apiSaveInvoiceAdm(pobj) {

    pobj.serviceRate = Number(pobj.serviceRate) * 100;
    pobj.taxIncPriRat = Number(pobj.taxIncPriRat) * 100;
    pobj.taxCostPriRat = Number(pobj.taxCostPriRat) * 100;
    pobj.invoiceAmount = system.y2f(pobj.invoiceAmount);

    var rs = await this.callms("invoice", "saveInvoice", pobj);
    if (rs.status == 0) {
      return rs
    } else {
      return system.getResult(null, rs.msg);
    }
  }

  /**
   * 平台审批
   * @param {*} pobj 
   */
  async apiPlatformAssignment(pobj) {
    if (!pobj.nextStatus) {
      return system.getResult(null, `参数错误`);
    }
    var rs = await this.callms("invoice", "platformAssignment", pobj);
    if (rs.status == 0) {
      // this.pushDeliver(pobj);
      console.log(pobj);
      this.sendInvoiceToDz(pobj);
      return rs;
    } else {
      return system.getResult(null, rs.msg);
    }
  }

  async sendInvoiceToDz(obj) {
    console.log(obj, "1111111111111111111111111111111111111111obj");

    // 查发票
    let invoiceApply = await this.callms("invoice", "queryInvoice", {
      id: obj.id
    });
    console.log(invoiceApply, "00000000000000000000000000000000000000000000000000000000000");

    let invoice = invoiceApply.data.invoice || {};
    let params = this.invoiceConfig[invoice.merchantId];
    if (!params) {
      return;
    }

    params.file = [
      invoice.invoiceImg,
    ];
    let apiurl = "https://nga-api.gongsibao.com/nga-sass//billInfo/uploadFileForAliyun";
    console.log(apiurl, params);
    let rs = await this.restClient.execPost(params, apiurl);
    console.log(rs, "11111111111111111111111111111111111111111111111");
    return rs;
  }

  /**
   * 交付商审批
   * @param {*} pobj 
   */
  async apiDelivererAssignment(pobj) {
    if (!pobj.nextStatus) {
      return system.getResult(null, `参数错误`);
    }
    var rs = await this.callms("invoice", "delivererAssignment", pobj);
    if (rs.status == 0) {
      this.pushDeliver(pobj);
      return rs;
    } else {
      return system.getResult(null, rs.msg);
    }
  }

  /**
   * 完税证明
   * @param {*} pobj 
   */
  async apiTxPayment(pobj) {
    let params = {};
    params.id = this.trim(pobj.id);
    params.taxNo = this.trim(pobj.taxNo);
    params.complateTax = this.trim(pobj.complateTax);
    params.taxTime = this.trim(pobj.taxTime);
    params.taxVoucher = this.trim(pobj.taxVoucher);

    var rs = await this.callms("invoice", "txPayment", params);
    if (rs.status == 0) {
      return rs
    } else {
      return system.getResult(null, rs.msg);
    }
  }


  /**
   * 查看完税证明
   * @param {*} pobj 
   */
  async apiQueryTxPayment(pobj) {
    let params = {};
    params.id = this.trim(pobj.id);
    var rs = await this.callms("invoice", "queryTxPayment", params);
    if (rs.status == 0) {
      return rs
    } else {
      return system.getResult(null, rs.msg);
    }
  }

  /**
   * 发票列表(交付商)
   * @param {*} pobj 
   */
  async apiDelivererInvoices(pobj) {
    if (pobj.pageIndex) {
      pobj.pageIndex = Number(pobj.pageIndex) || 1;
    }
    if (pobj.pageSize) {
      pobj.pageSize = Number(pobj.pageSize) || 10;
    }
    let res = await this.callms("invoice", "delivererInvoices", pobj);
    for (let item of res.data.rows) {
      item.invoice_amount = system.f2y(item.invoice_amount);
    }
    if (res.status == 0) {
      return res;
    } else {
      return system.getResult(null, res.msg);
    }
  }


  /**
   * 发票申请列表(交付商)
   * @param {*} pobj 
   */
  async apiDelivererApplyInvoices(pobj) {
    if (pobj.pageIndex) {
      pobj.pageIndex = Number(pobj.pageIndex) || 1;
    }
    if (pobj.pageSize) {
      pobj.pageSize = Number(pobj.pageSize) || 10;
    }
    let res = await this.callms("invoice", "delivererApplyInvoices", pobj);
    for (let item of res.data.rows) {
      item.invoice_amount = system.f2y(item.invoice_amount);
    }
    if (res.status == 0) {
      return res;
    } else {
      return system.getResult(null, res.msg);
    }
  }
  /**
   * 发票列表(平台)
   * @param {*} pobj 
   */
  async apiQueryInvoices(pobj) {
    pobj.pageIndex = Number(pobj.pageIndex || 1);
    pobj.pageSize = Number(pobj.pageSize || 10);

    var complateTax = this.trim(pobj.complateTax);
    if (complateTax === "") {
      complateTax = "-1";
    }
    pobj.complateTax = complateTax;
    pobj.statuses = ['1070', '1080', '1090'];
    let res = await this.callms("invoice", "queryInvoices", pobj);
    for (let item of res.data.rows) {
      item.apply.invoice_amount = system.f2y(item.apply.invoice_amount);
    }
    if (res.status == 0) {
      return res;
    } else {
      return system.getResult(null, res.msg);
    }
  }

  /**
   * 发票申请列表(平台)
   * @param {*} pobj 
   */
  async apiQueryApplyInvoices(pobj) {
    pobj.pageIndex = Number(pobj.pageIndex || 1);
    pobj.pageSize = Number(pobj.pageSize || 10);
    let res = await this.callms("invoice", "queryApplyInvoices", pobj);
    for (let item of res.data.rows) {
      item.invoiceAmount = system.f2y(item.invoiceAmount);
      item.personalIncomeTax = system.f2y(item.personalIncomeTax);
      item.valueAddedTax = system.f2y(item.valueAddedTax);
      item.serviceCharge = system.f2y(item.serviceCharge);
      item.additionalTax = system.f2y(item.additionalTax);
    }
    if (res.status == 0) {
      return res;
    } else {
      return system.getResult(null, res.msg);
    }
  }

  /**
   * 更新邮寄单号(平台)
   * @param {*} pobj 
   */
  async apiUpEmNo(pobj) {
    if (pobj.id) {
      pobj.id = this.trim(pobj.id);
    }
    if (pobj.platformMailNo) {
      pobj.platformMailNo = this.trim(pobj.platformMailNo);
    }
    let res = await this.callms("invoice", "updateEmail", pobj);
    if (res.status == 0) {
      return res;
    } else {
      return system.getResult(null, res.msg);
    }
  }

  async pushDeliver(obj) {
    var status = obj.nextStatus;
    if (!status) {
      return;
    }
    var pushStatus = ["1010", "1030", "1050", "1090"];
    // 0090开票申请 1010审核驳回 1030审核通过 1050已开票 1090已完成
    if (pushStatus.indexOf(status) == -1) {
      return;
    }
    // 查发票
    var invoiceApply = await this.callms("invoice", "queryInvoice", {
      id: obj.id
    });
    invoiceApply = invoiceApply.data;
    if (!invoice) {
      console.log("推送信息失败[" + JSON.stringify(obj) + "]，发票不存在 ------------------------");
      return;
    }
    var invoice = invoiceApply.invoice || {};

    var merchant = await this.callms("merchant", "secretById", {
      id: order.merchant_id
    });

    merchant = merchant.data;
    if (!merchant) {
      console.log("推送信息失败[" + JSON.stringify(obj) + "]，商户不存在 ------------------------");
      return;
    }

    var options = {
      merchantId: merchant.id,
      appKey: merchant.appSecret,
      dataType: 3,
      dataId: invoiceApply.id,
      field: "invoiceStatus",
    };

    var params = {
      merchantId: merchant.id,
      status: status,
      applyNo: invoiceApply.applyNo,
    }
    // 0090开票申请  1030审核通过 1050已开票 1090已完成

    if (status == "1010") {
      // 1010审核驳回
      params.auditRemark = this.trim(invoiceApply.remark);
    } else if (status == "1030") {
      // 1030审核通过
      params.auditRemark = this.trim(invoiceApply.remark);
    } else if (status == "1050") {
      // invoiceNo           ：   String     ：发票编号
      params.invoiceNo = this.trim(invoiceApply.id);
      // invoiceTime         ：   String     ：开票时间
      params.invoiceTime = this.trim(invoice.invoiceTime);
      // invoiceImg          ：   String     ：发票照片
      params.invoiceImg = this.trim(invoice.invoiceImg);
      // payVoucher          ：   String     ：支付凭证
      params.payVoucher = this.trim(invoiceApply.statements);
    } else if (status == "1090") {
      // courierNo           ：   String     ：快递单号
      params.courierNo = this.trim(invoice.mailNo);
      // courierImg          ：   String     ：快递交接单图片
      params.courierImg = "";
    } else {
      return;
    }
    options.params = params;
    await this.pushapiSve.push(options);
  }

  async redrush(params) {
    try {
      return await this.callms("invoice", "redRushInvoice", params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }
  //交易数据 平台
  async statManageData(params) {
    try {
      return await this.callms("invoice", "statTransData", params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }
  //发票办理 平台
  async statBusinessData(params) {
    try {
      return await this.callms("invoice", "statBusinessData", params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息${error}`);
    }
  }
  /**
   * 交易数据（交付商）
   * @param {*} params 
   */
  async delStatManageData(params) {
    try {
      return await this.callms("invoice", "delStatTransData", params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }
  //发票办理（交付商）
  async delStatBusinessData(params) {
    try {
      return await this.callms("invoice", "delStatBusinessData", params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }
  //交付商列表（平台）
  async statDeliverData(params) {
    try {
      return await this.callms("invoice", "statDeliverData", params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }

  //计算发票增值税
  async calculationValueAddedTax(params) {
    try {
      return await this.callms("invoice", "calculationValueAddedTax", params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }

  //计算发票附加税
  async calculationAdditionalTax(params) {
    try {
      return await this.callms("invoice", "calculationAdditionalTax", params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }


}
module.exports = InvoiceService;