
const invoiceConfig = require("./invoiceConfig");
const system = require("../../system");
const common = require("./common");
const applySve = system.getObject("service.invoice.applySve");
const Decimal = require('decimal.js');

/**
 * 开票验证
 * 注意：验证和测试高度耦合（需要传入测试计算方法）
 * @businessmenType  用户类别
 * @businessmenId    销售方ID
 * @businessmenCreditCode  非必添   销售方统一社会信用代码
 * @invoiceAmount    开票金额
 * @fn               试算方法
 */
module.exports.validate=async (params,fn,formate)=>{
  let businessmenType = common.trim(params.businessmenType);
  let businessmenId = common.trim(params.businessmenId);
  let businessmenCreditCode = common.trim(params.businessmenCreditCode);
  let invoiceAmount = Number(common.trim(params.invoiceAmount));

  if(!businessmenType || !invoiceAmount || !businessmenId){
    return system.getResult(-1,`参数错误 销售方信息参数有误 请核对参数`);
  }
  //获取配置文件信息
  let busCon = invoiceConfig[businessmenType];
  if(!busCon){
    return system.getResult(-1,`参数错误 销售方类型不能为空`);
  }
  if(busCon.MAX_AMOUNT<params.invoiceAmount){
    return system.getResult(-1,`开票金额超出最大范围`);
  }
  //试算获取累计含税价
  let calAmount = await fn(formate);
  if(calAmount.hasOwnProperty("status")){
    return system.getResult(-1,`计算参数错误 请核对税率、金额以及销售方信息`);
  }
  _totalAmount = Decimal(calAmount.x1).plus(invoiceAmount).toNumber();
  if(busCon.MAX_AMOUNT<_totalAmount){
    return system.getResult(-1,`累计开票金额超出本年度最大金额`);
  }
  let warning = "";
  if(busCon.WARNING_AMOUNT<_totalAmount){
    warning=`累计开票金额达到${_totalAmount}`;
  }
  //查询发票状态  只有在状态为 '1000','0090' 或者信息不存在的情况下 验证成功 参考 applySve.verificationByBusinessmenCreditCode接口
  let isLegal = await applySve.verificationInvoiceStatus(businessmenType,businessmenId,businessmenCreditCode);
  if(!isLegal){
    return system.getResult(-1,`验证失败 此用户存在未完成的发票`);
  }
  //移除累计税价
  delete calAmount.x1;
  if(warning){
    calAmount.warning=warning;
  }
  return system.getResult(calAmount);
}