/**
 * 1 算法文件命名规则 ： calInvoice + 销售方编码
 * 2 如果算法中途出现异常 则需直接return 
 * 3 如果算法顺利执行 返回参数中除包含必须的四个税值外，还需要包含一个累计不含税价字段 字段名称为 "x1" 
 * 4 此文件必须提供 calcInvoice 和 formatParams 方法
 */

const system = require("../../../system");
const applySve = system.getObject("service.invoice.applySve");
const Decimal = require('decimal.js');
const PER_TAX = 1; //个税
const VAL_TAX = 2; //增值税
/**
 * 试算接口
 * 注意：1 由于销售方类型不同 所以算法不同 需要对参数验证单独处理
 * 
 * 税率的格式   传去除 %号的数值  比如：
 *   96%,  则这个值就传 "taxCostPriRat"=96 
 */
module.exports.calcInvoice = async (params) => {
  try {
    // 服务费率
    let serviceRate = Number(params.serviceRate || 0);
    let serviceCharge = Number((params.invoiceAmount * serviceRate) / 100).toFixed(0) || 0;

    //计算累计不含税价 businessmenId,businessmenCreditCode,taxIncPriRat,invoiceAmount,type,valCalWay,perCalWay,invoiceTime
    let x1 = await applySve.calAccumulatedPriceExcludingTax(params.businessmenId, params.businessmenType, params.businessmenCreditCode, params.taxIncPriRat, params.invoiceAmount, PER_TAX, null, params.perCalWay, params.invoiceTime);
    console.log("个税 累计不含税价总额：" + x1);

    //计算累计利润
    let x2 = calAccumulatedProfit(x1, params.taxCostPriRat);
    //根据 cumulativeProfit 查找对应梯度的个税税率和速算扣除数
    let calRateRangeResForPer = calRateRange(x2, params.perIncTaxRange, PER_TAX);

    let { taxPer, quiCalDed } = calRateRangeResForPer;
    //计算年累计的个税
    let cumulativeProfit = await applySve.calCumulativeProfit(params.businessmenId,params.businessmenType, PER_TAX, params.valCalWay);
    //计算个税
    let personalIncomeTax = calTaxPersonal(x2, taxPer, quiCalDed, cumulativeProfit);

    /*计算增值税*/

    //计算累计不含税价
    let x3 = await applySve.calAccumulatedPriceExcludingTax(params.businessmenId,params.businessmenType, params.businessmenCreditCode, params.taxIncPriRat, params.invoiceAmount, VAL_TAX, params.valCalWay, null, params.invoiceTime);
    console.log("增值税 累计不含税价总额：" + x3);
    //根据 cumulativeProfitOfvalTax 查找对应梯度的个税税率
    let calRateRangeResForVal = calRateRange(x3, params.valAddTaxRange, VAL_TAX);

    let {valAddTaxRat,addTaxRat} = calRateRangeResForVal;
    //计算年累计的增值税
    let cumulativeProfitOfvalTax = await applySve.calCumulativeProfit(params.businessmenId,params.businessmenType, VAL_TAX, params.valCalWay);
    //计算增值税
    let valueAddedTax = calValTax(x3, valAddTaxRat, cumulativeProfitOfvalTax);

    //附加税
    let additionalTax = calAddTax(valueAddedTax, addTaxRat);

    let res = {
      x1: x1,                        //累计不含税价
      serviceCharge: serviceCharge, //服务费
      personalIncomeTax: personalIncomeTax, //个税
      valueAddedTax: valueAddedTax, //附加税
      additionalTax: additionalTax, //附加税
    }
    console.log("计算的各种税额：" + JSON.stringify(res));
    return res;
  } catch (error) {
    return system.getResult(-1,`系统错误 错误信息 ${error}`);
  }
}

/**
 * 计算累计利润
 * @param {*} x1             年累计金额 
 * @param {*} taxCostPriRat  核定成本费用率
 */
let calAccumulatedProfit = (x1, taxCostPriRat) => {
  if (taxCostPriRat == 0) {
    return 0;
  } else {
    return new Decimal(x1).mul(Decimal.sub(1, taxCostPriRat)).toFixed(2);
  }
}

/**
 * 计算税率值
 * @param {*} amount    金额
 * @param {*} taxRange  税率范围
 * @param {*} type      类型  1：个税  2 增值税
 */
let calRateRange = (amount, taxRange, type) => {
  let res = {};
  if (type === PER_TAX) {
    for (let item of taxRange) {
      if (item.minValue <= amount && amount <= item.maxValue) {
        res.taxPer = item.rate;
        res.quiCalDed = item.quiCalDed;
        break;
      }
    }
  } else {
    for (let item of taxRange) {
      if (item.minValue <= amount && amount <= item.maxValue) {
        res.valAddTaxRat = item.zengzhiRate;
        res.addTaxRat = item.fujiaRate;
        break;
      }
    }
  }
  return res;
}

/**
 * 计算个税  
 * @param {*} x2                 //累计利润
 * @param {*} taxPer             //个税税率
 * @param {*} quiCalDed          //速算扣除数
 * @param {*} cumulativeProfit   //累计缴纳的个税
 */
let calTaxPersonal=(x2, taxPer, quiCalDed, cumulativeProfit)=>{
  x2 = x2 || 0;
  quiCalDed = quiCalDed || 0;
  taxPer = taxPer || 0;
  cumulativeProfit = cumulativeProfit || 0;
  if (taxPer == 0) {
    return 0;
  }
  return (new Decimal(x2).mul(taxPer).div(100).sub(quiCalDed).sub(cumulativeProfit)).toFixed(2);
}


/**
 * 计算增值税
 * @param {*} x3                          //累计不含说价
 * @param {*} valAddTaxRat                //增值税率
 * @param {*} cumulativeProfitOfvalTax    //累计缴纳的增值税
 */
let calValTax=(x3, valAddTaxRat, cumulativeProfitOfvalTax)=>{
  if (valAddTaxRat == 0) {
    return 0;
  }
  let res = new Decimal(x3).mul(valAddTaxRat).div(100).sub(cumulativeProfitOfvalTax).toFixed(2);
  return res;
}

/**
 * 计算附加税 
 * @param {*} valueAddedTax 
 * @param {*} addTaxRat 
 */
let calAddTax=(valueAddedTax, addTaxRat)=>{
  if (addTaxRat == 0) {
    return 0
  } else {
    return new Decimal(valueAddedTax).mul(addTaxRat).div(100).toFixed(2);
  }
}

/**
 * 格式化参数
 */
module.exports.formatParams=(params)=>{
  //后期添加格式化参数信息
  params=verificationParams(params);
  return params;
}

/**
 * 校验各种费率 的合法性
 * @param {*} params 
 * params
 */
let verificationParams = (params) => {
  if (params.taxIncPriRat > 100 || params.serviceRate > 100 || params.taxCostPriRat > 100) {
    return system.getResult(-1,`参数错误 费率不合法`);
  } else {
    params.taxIncPriRat = new Decimal(params.taxIncPriRat).div(100).toFixed(4);
    params.taxCostPriRat = new Decimal(params.taxCostPriRat).div(100).toFixed(4);
    params.serviceRate = new Decimal(params.serviceRate).div(100).toFixed(4);
  }
  return params;
}