yxh
7 天以前 89bb0237ead5fb632fcc14c2c52276496e19843f
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceFunddetailServiceImpl.java
@@ -1,11 +1,29 @@
package com.ruoyi.project.service.impl;
import java.util.List;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import com.ruoyi.project.domain.ServiceFund;
import com.ruoyi.project.domain.ServiceReimbursement;
import com.ruoyi.project.domain.ServiceReimbursementdetail;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.tax.PerformanceTaxtUtils;
import com.ruoyi.common.tax.TaxtUtils;
import com.ruoyi.common.tax.VatTaxUtils;
import com.ruoyi.common.utils.bean.DtoConversionUtils;
import com.ruoyi.project.domain.*;
import com.ruoyi.project.domain.vo.*;
import com.ruoyi.project.mapper.ServiceFundMapper;
import com.ruoyi.project.mapper.SpStatBonusMapper;
import lombok.extern.flogger.Flogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
@@ -13,67 +31,187 @@
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.mapper.ServiceFunddetailMapper;
import com.ruoyi.project.domain.ServiceFunddetail;
import com.ruoyi.project.service.IServiceFunddetailService;
import org.springframework.transaction.annotation.Transactional;
/**
 * 费用申请明细Service业务层处理
 *
 *
 * @author ruoyi
 * @date 2022-01-25
 */
@Slf4j
@Service
public class ServiceFunddetailServiceImpl extends ServiceImpl<ServiceFunddetailMapper, ServiceFunddetail> implements IServiceFunddetailService
{
public class ServiceFunddetailServiceImpl extends ServiceImpl<ServiceFunddetailMapper, ServiceFunddetail> implements IServiceFunddetailService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    ServiceFunddetailMapper serviceFunddetailMapper;
    @Autowired
    ServiceFundMapper serviceFundMapper;
    @Autowired
    SpStatBonusMapper spStatBonusMapper;
    /**
     * 查询费用申请明细列表
     *
     *
     * @param serviceFunddetail 费用申请明细
     * @return 费用申请明细
     */
    @Override
    public List<ServiceFunddetail> queryList(ServiceFunddetail serviceFunddetail) {
        LambdaQueryWrapper<ServiceFunddetail> wrappers = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(serviceFunddetail.getBeneficiaryname())){
            wrappers.like(ServiceFunddetail::getBeneficiaryname ,serviceFunddetail.getBeneficiaryname());
        if (StringUtils.isNotBlank(serviceFunddetail.getBeneficiaryname())) {
            wrappers.like(ServiceFunddetail::getBeneficiaryname, serviceFunddetail.getBeneficiaryname());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getUnitname())){
            wrappers.like(ServiceFunddetail::getUnitname ,serviceFunddetail.getUnitname());
        if (StringUtils.isNotBlank(serviceFunddetail.getUnitname())) {
            wrappers.like(ServiceFunddetail::getUnitname, serviceFunddetail.getUnitname());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getApplytype())){
            wrappers.eq(ServiceFunddetail::getApplytype ,serviceFunddetail.getApplytype());
        if (StringUtils.isNotBlank(serviceFunddetail.getApplytype())) {
            wrappers.eq(ServiceFunddetail::getApplytype, serviceFunddetail.getApplytype());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getItemname())){
            wrappers.like(ServiceFunddetail::getItemname ,serviceFunddetail.getItemname());
        if (StringUtils.isNotBlank(serviceFunddetail.getItemname())) {
            wrappers.like(ServiceFunddetail::getItemname, serviceFunddetail.getItemname());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getItemtype())){
            wrappers.eq(ServiceFunddetail::getItemtype ,serviceFunddetail.getItemtype());
        if (StringUtils.isNotBlank(serviceFunddetail.getItemtype())) {
            wrappers.eq(ServiceFunddetail::getItemtype, serviceFunddetail.getItemtype());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getRecordstatus())){
            wrappers.eq(ServiceFunddetail::getRecordstatus ,serviceFunddetail.getRecordstatus());
        if (StringUtils.isNotBlank(serviceFunddetail.getRecordstatus())) {
            wrappers.eq(ServiceFunddetail::getRecordstatus, serviceFunddetail.getRecordstatus());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getCreateBy())){
            wrappers.eq(ServiceFunddetail::getCreateBy ,serviceFunddetail.getCreateBy());
        if (StringUtils.isNotBlank(serviceFunddetail.getCreateBy())) {
            wrappers.eq(ServiceFunddetail::getCreateBy, serviceFunddetail.getCreateBy());
        }
        if (serviceFunddetail.getCreateTime() != null){
            wrappers.eq(ServiceFunddetail::getCreateTime ,serviceFunddetail.getCreateTime());
        if (serviceFunddetail.getCreateTime() != null) {
            wrappers.eq(ServiceFunddetail::getCreateTime, serviceFunddetail.getCreateTime());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getUploadflag())){
            wrappers.eq(ServiceFunddetail::getUploadflag ,serviceFunddetail.getUploadflag());
        if (StringUtils.isNotBlank(serviceFunddetail.getUploadflag())) {
            wrappers.eq(ServiceFunddetail::getUploadflag, serviceFunddetail.getUploadflag());
        }
        if (serviceFunddetail.getUploadtime() != null){
            wrappers.eq(ServiceFunddetail::getUploadtime ,serviceFunddetail.getUploadtime());
        if (serviceFunddetail.getUploadtime() != null) {
            wrappers.eq(ServiceFunddetail::getUploadtime, serviceFunddetail.getUploadtime());
        }
        if (serviceFunddetail.getJxrq() != null) {
            wrappers.like(ServiceFunddetail::getJxrq, serviceFunddetail.getJxrq());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getIdcardno())) {
            wrappers.eq(ServiceFunddetail::getIdcardno, serviceFunddetail.getIdcardno());
        }
        if (StringUtils.isNotBlank(serviceFunddetail.getApplytype())) {
            wrappers.eq(ServiceFunddetail::getApplytype, serviceFunddetail.getApplytype());
        }
        if (serviceFunddetail.getDel_flag() != null) {
            wrappers.eq(ServiceFunddetail::getDel_flag, serviceFunddetail.getDel_flag());
        }
        if (serviceFunddetail.getDeptId() != null) {
            wrappers.eq(ServiceFunddetail::getDeptId, serviceFunddetail.getDeptId());
        }
        if (serviceFunddetail.getDeptName() != null) {
            wrappers.eq(ServiceFunddetail::getDeptName, serviceFunddetail.getDeptName());
        }
        return this.list(wrappers);
    }
    @Override
    public List<ServiceFunddetail> getDataBybeneficiaryNo(FunddetailReqVo funddetailReqVo) {
        if (StringUtils.isEmpty(funddetailReqVo.getStarttime())) {
            // 获取当月第一天日期
            funddetailReqVo.setStarttime(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()).toString());
        }
        if (StringUtils.isEmpty(funddetailReqVo.getEndtime())) {
            // 获取当月最后一天日期
            funddetailReqVo.setEndtime(LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()).toString());
        }
        List<ServiceFunddetail> dataBybeneficiaryNo = serviceFunddetailMapper.getDataBybeneficiaryNo(funddetailReqVo);
        return dataBybeneficiaryNo;
    }
    /**
     * 根据受益人身份证编号获取税费金额
     *
     * @param taxMoneyVo
     * @return
     */
    @Override
    public Double getTaxByBeneFiciaryNo(TaxMoneyVO taxMoneyVo) {
        // 金额累加必须用 BigDecimal:double 累加会引入浮点尾差,导致算出的个税出现分以下误差
        BigDecimal sum = BigDecimal.ZERO;
        BigDecimal totalScore = BigDecimal.ZERO;
        List<ServiceFunddetail> taxationByBeneFiciaryNo = serviceFunddetailMapper.getTaxBeforeByBeneFiciaryNo(taxMoneyVo);
        if (CollectionUtils.isNotEmpty(taxationByBeneFiciaryNo)) {
            //计算申请金额总和,不包括当前传进来的
            sum = taxationByBeneFiciaryNo.stream()
                    .map(ServiceFunddetail::getAmount)
                    .filter(java.util.Objects::nonNull)
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //不加本次薪酬的个税
            totalScore = taxationByBeneFiciaryNo.stream()
                    .map(ServiceFunddetail::getTaxamount)
                    .filter(java.util.Objects::nonNull)
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        sum = sum.add(new BigDecimal(taxMoneyVo.getMoney()));
        //加上本次薪酬的总个税
        String taxation = TaxtUtils.getTaxation(sum);
        Double tax = new BigDecimal(taxation).subtract(totalScore).doubleValue();
        return tax;
    }
    /**
     * 根据税后工资,算出税前工资
     *
     * @param taxMoneyVo
     * @return
     */
    @Override
    public TaxedMoneyVO getTaxBeforeByAfterMoney(TaxMoneyVO taxMoneyVo) {
        TaxedMoneyVO taxedMoneyVO = new TaxedMoneyVO();
        // 金额累加必须用 BigDecimal,避免浮点尾差影响税前/税额结果
        BigDecimal sum = BigDecimal.ZERO;
        BigDecimal totalScore = BigDecimal.ZERO;
        List<ServiceFunddetail> taxationByBeneFiciaryNo = serviceFunddetailMapper.getTaxBeforeByBeneFiciaryNo(taxMoneyVo);
        if (CollectionUtils.isNotEmpty(taxationByBeneFiciaryNo)) {
            //计算出税后总金额(不包含本次)
            sum = taxationByBeneFiciaryNo.stream()
                    .map(ServiceFunddetail::getTaxedamount)
                    .filter(java.util.Objects::nonNull)
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //求出之前的总的个税
            totalScore = taxationByBeneFiciaryNo.stream()
                    .map(ServiceFunddetail::getTaxamount)
                    .filter(java.util.Objects::nonNull)
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        //计算出总的税后薪酬(包含本次)
        sum = sum.add(new BigDecimal(taxMoneyVo.getMoney()));
        //税前总金额
        String taxationBefore = TaxtUtils.getTaxationBefore(sum);
        //总个税
        BigDecimal tax = new BigDecimal(taxationBefore).subtract(sum);
        //本次的税前金额
        String nowTaxMoney = TaxtUtils.getTaxationBefore(new BigDecimal(taxMoneyVo.getMoney()));
        //本次的税费
        BigDecimal subtract = new BigDecimal(nowTaxMoney).subtract(new BigDecimal(taxMoneyVo.getMoney()));
        taxedMoneyVO.setAllTax(tax.toString());
        taxedMoneyVO.setAllTaxbeforeMoney(taxationBefore);
        taxedMoneyVO.setAllAaxAfterMoney(sum.toString());
        taxedMoneyVO.setNowTaxBeforeMoney(nowTaxMoney);
        taxedMoneyVO.setNowTax(subtract.toString());
        return taxedMoneyVO;
    }
    @Override
    public List<ServiceFunddetail> getAllDetailsByFDIDLW(Long id) {
@@ -115,20 +253,353 @@
        ServiceFunddetail serviceFunddetail = serviceFunddetailMapper.selectById(id);
        Long fundid = serviceFunddetail.getFundid();
        ServiceFund serviceFund = serviceFundMapper.selectById(fundid);
        if (ObjectUtils.isNotEmpty(serviceFund)) {
            // 金额一律用 BigDecimal 累加/扣减,避免浮点尾差
            BigDecimal pretax = toMoney(serviceFund.getPretaxcost()).subtract(toMoney(serviceFunddetail.getAmount()));
            BigDecimal aftertax = toMoney(serviceFund.getTaxedcost()).subtract(toMoney(serviceFunddetail.getTaxedamount()));
            BigDecimal vat = toMoney(serviceFund.getVatCost()).subtract(toMoney(serviceFunddetail.getVatAmount()));
            BigDecimal cityTax = toMoney(serviceFund.getCityTaxCost()).subtract(toMoney(serviceFunddetail.getCityTaxAmount()));
            BigDecimal laborPretax = toMoney(serviceFund.getLaborPretaxCost()).subtract(toMoney(serviceFunddetail.getLaborPretaxAmount()));
            BigDecimal tax = toMoney(serviceFund.getTaxcost()).subtract(toMoney(serviceFunddetail.getTaxamount()));
            BigDecimal amount = pretax.add(aftertax);
        Double pretax = serviceFund.getPretaxcost();
        Double aftertax = serviceFund.getTaxedcost();
        pretax = pretax - serviceFunddetail.getAmount();
        aftertax = aftertax - serviceFunddetail.getTaxedamount();
        Double amount = pretax + aftertax;
        serviceFund.setPretaxcost(pretax);
        serviceFund.setTaxedcost(aftertax);
        serviceFund.setAmountrequested(amount);
        int updateAmount = serviceFundMapper.updateById(serviceFund);
            serviceFund.setPretaxcost(pretax.doubleValue());
            serviceFund.setTaxedcost(aftertax.doubleValue());
            serviceFund.setVatCost(vat.doubleValue());
            serviceFund.setCityTaxCost(cityTax.doubleValue());
            serviceFund.setLaborPretaxCost(laborPretax.doubleValue());
            serviceFund.setTaxcost(tax.doubleValue());
            serviceFund.setAmountrequested(amount.doubleValue());
            int updateAmount = serviceFundMapper.updateById(serviceFund);
        }
        return serviceFunddetailMapper.deleteById(id);
    }
    @Override
    public List<ServiceFunddetailVO> getFundDetail(Long id) {
        List<ServiceFunddetail> serviceFunddetails = serviceFunddetailMapper.selectFundDetailListById(id);
        List<ServiceFunddetailVO> serviceFunddetailVOS = DtoConversionUtils.sourceToTarget(serviceFunddetails, ServiceFunddetailVO.class);
        for (ServiceFunddetailVO serviceFunddetailVO : serviceFunddetailVOS) {
            if (!StringUtils.isEmpty(serviceFunddetailVO.getAnnexfiles())) {
                List<RbDetailFile> rbDetailFiles = JSONArray.parseArray(serviceFunddetailVO.getAnnexfiles(), RbDetailFile.class);
                serviceFunddetailVO.setAnnexfilesList(rbDetailFiles);
            }
            if (!StringUtils.isEmpty(serviceFunddetailVO.getInvoicefiles())) {
                List<RbDetailFile> rbDetailFiles = JSONArray.parseArray(serviceFunddetailVO.getInvoicefiles(), RbDetailFile.class);
                serviceFunddetailVO.setInvoicefilesList(rbDetailFiles);
            }
        }
        return serviceFunddetailVOS;
    }
    /**
     * 批量算税主方法(劳务个税 + 增值税 + 城建税,v2 口径)
     * <p>
     * 金额模型:
     * <pre>
     * 税前录入:V = ceil(P × 1%)、C = ceil(V × 3.5%)、L = P - V - C、
     *          T = 劳务个税(当月累计 L) - 原累计 T、N = L - T
     * 税后录入:N累计 = 原累计 N + N、L累计 = getTaxationBefore(N累计)、
     *          L = L累计 - 原累计 L、T = L - N、P/V/C = solveGross(L)
     * 无身份证:V = C = T = 0,L = N = P
     * </pre>
     *
     * @param serviceFunddetails 费用明细列表
     * @param tempTaxSumMap      本月累计金额缓存(按身份证号)
     * @return 是否算税成功
     */
    @Override
    public Boolean calculateTax(List<ServiceFunddetail> serviceFunddetails, Map<String, TaxMoneySumEO> tempTaxSumMap) {
        return calculateTax(serviceFunddetails, tempTaxSumMap, new Date());
    }
    /**
     * 批量算税(指定本批算税时间,保证同批明细 tax_time 一致)
     *
     * @param serviceFunddetails 费用明细列表
     * @param tempTaxSumMap      本月累计金额缓存(按身份证号)
     * @param taxTime            本次算税时间
     * @return 是否算税成功
     */
    @Override
    public Boolean calculateTax(List<ServiceFunddetail> serviceFunddetails, Map<String, TaxMoneySumEO> tempTaxSumMap, Date taxTime) {
        // 1. 校验参数
        if (CollectionUtils.isEmpty(serviceFunddetails)) {
            throw new BaseException("算税条件为空,请检查后,再进行计算");
        }
        // 2. 排序:税时间为空的排后面,再按 id 保证同批顺序稳定
        serviceFunddetails.sort(Comparator
                .comparing((ServiceFunddetail obj) -> ObjectUtils.isEmpty(obj.getTaxTime()) ? 1 : 0)
                .thenComparing(obj -> obj.getId() == null ? Long.MAX_VALUE : obj.getId()));
        // 3. 获取本批次 fundid 及主表信息
        Long fundid = serviceFunddetails.get(0).getFundid();
        log.info("算税的fundid的值为:{}", fundid);
        ServiceFund serviceFund1 = serviceFundMapper.selectById(fundid);
        if (serviceFund1 == null) {
            throw new BaseException("未找到费用申请单,ID=" + fundid);
        }
        // 明细 tax_time 统一使用本次算税时间
        if (taxTime == null) {
            taxTime = new Date();
        }
        // 4. 本批次合计(全部用 BigDecimal,禁止 double 累加)
        BigDecimal pretaxTotal = BigDecimal.ZERO;
        BigDecimal vatTotal = BigDecimal.ZERO;
        BigDecimal cityTaxTotal = BigDecimal.ZERO;
        BigDecimal laborPretaxTotal = BigDecimal.ZERO;
        BigDecimal taxTotal = BigDecimal.ZERO;
        BigDecimal taxedTotal = BigDecimal.ZERO;
        List<ServiceFunddetail> updateList = new ArrayList<>();
        // 5. 遍历每条明细
        for (ServiceFunddetail detail : serviceFunddetails) {
            if (detail.getAmount() == null) {
                detail.setAmount(0.0);
            }
            if (detail.getTaxedamount() == null) {
                detail.setTaxedamount(0.0);
            }
            // 服务说明为空按“非税后”处理
            String scopeName = detail.getServicesscopename() == null ? "" : detail.getServicesscopename().trim();
            boolean afterTax = scopeName.contains("税后");
            // 5.1 身份证号为空:不扣增值税/城建税/劳务个税
            if (StringUtils.isEmpty(detail.getIdcardno())) {
                BigDecimal p = afterTax ? toMoney(detail.getTaxedamount()) : toMoney(detail.getAmount());
                detail.setAmount(p.doubleValue());
                detail.setVatAmount(0.0);
                detail.setCityTaxAmount(0.0);
                detail.setLaborPretaxAmount(p.doubleValue());
                detail.setTaxamount(0.0);
                detail.setTaxedamount(p.doubleValue());
                detail.setTaxVersion(VatTaxUtils.TAX_VERSION_V2);
                detail.setTaxTime(taxTime);
                updateList.add(detail);
                pretaxTotal = pretaxTotal.add(p);
                laborPretaxTotal = laborPretaxTotal.add(p);
                taxedTotal = taxedTotal.add(p);
                continue;
            }
            // 5.2 身份证号不为空:本月累计 + 分档算税
            String idcard = detail.getIdcardno().trim();
            // 5.2.1 取本月累计(缓存避免重复查库)
            TaxMoneySumEO taxSum = tempTaxSumMap.get(idcard);
            if (taxSum == null) {
                taxSum = new TaxMoneySumEO();
                taxSum.setXh(0L);
                tempTaxSumMap.put(idcard, taxSum);
            }
            long xh = (taxSum.getXh() == null ? 0L : taxSum.getXh()) + 1;
            taxSum.setXh(xh);
            detail.setXh(xh);
            // 累计税前金额(不含本笔),用于页面展示
            detail.setAllAmount(taxSum.getAmounts());
            BigDecimal prevAmount = toMoney(taxSum.getAmounts());
            BigDecimal prevLaborPretax = toMoney(taxSum.getLaborPretaxAmounts());
            BigDecimal prevTax = toMoney(taxSum.getTaxAmounts());
            BigDecimal prevTaxed = toMoney(taxSum.getTaxedAmounts());
            BigDecimal prevVat = toMoney(taxSum.getVatAmounts());
            BigDecimal prevCityTax = toMoney(taxSum.getCityTaxAmounts());
            BigDecimal pretax;
            BigDecimal vat;
            BigDecimal cityTax;
            BigDecimal laborPretax;
            BigDecimal taxAmount;
            BigDecimal taxedAmount;
            if (afterTax) {
                // 5.2.2 税后录入:先反算劳务税前,再循环反解税前/增值税/城建税
                taxedAmount = toMoney(detail.getTaxedamount());
                BigDecimal sumTaxed = prevTaxed.add(taxedAmount);
                BigDecimal sumLaborPretax = new BigDecimal(TaxtUtils.getTaxationBefore(sumTaxed));
                laborPretax = VatTaxUtils.roundMoney(sumLaborPretax.subtract(prevLaborPretax));
                if (laborPretax.signum() < 0) {
                    // 逐笔向上取整可能带来几分钱的反算误差,容差内按 0 处理;超出容差说明数据异常
                    if (laborPretax.abs().compareTo(new BigDecimal("0.05")) <= 0) {
                        log.warn("税后金额反算劳务税前出现负尾差,已按 0 处理。人员:{},反算劳务税前={},原累计劳务税前={}",
                                safeName(detail), sumLaborPretax, prevLaborPretax);
                        laborPretax = BigDecimal.ZERO;
                    } else {
                        throw new BaseException("税后金额反算劳务税前失败,人员:" + safeName(detail));
                    }
                }
                taxAmount = VatTaxUtils.roundMoney(laborPretax.subtract(taxedAmount));
                if (taxAmount.signum() < 0) {
                    taxAmount = BigDecimal.ZERO;
                }
                VatTaxUtils.GrossAmount gross = VatTaxUtils.solveGross(laborPretax);
                pretax = gross.getPretax();
                vat = gross.getVat();
                cityTax = gross.getCityTax();
            } else {
                // 5.2.3 税前录入:先算增值税/城建税/劳务税前,再按累计劳务税前算劳务个税
                pretax = toMoney(detail.getAmount());
                vat = VatTaxUtils.calcVat(pretax);
                cityTax = VatTaxUtils.calcCityTax(vat);
                laborPretax = VatTaxUtils.roundMoney(pretax.subtract(vat).subtract(cityTax));
                BigDecimal sumLaborPretax = prevLaborPretax.add(laborPretax);
                BigDecimal sumTax = new BigDecimal(TaxtUtils.getTaxation(sumLaborPretax));
                taxAmount = VatTaxUtils.roundMoney(sumTax.subtract(prevTax));
                if (taxAmount.signum() < 0) {
                    taxAmount = BigDecimal.ZERO;
                }
                taxedAmount = VatTaxUtils.roundMoney(laborPretax.subtract(taxAmount));
            }
            detail.setAmount(pretax.doubleValue());
            detail.setVatAmount(vat.doubleValue());
            detail.setCityTaxAmount(cityTax.doubleValue());
            detail.setLaborPretaxAmount(laborPretax.doubleValue());
            detail.setTaxamount(taxAmount.doubleValue());
            detail.setTaxedamount(taxedAmount.doubleValue());
            detail.setTaxVersion(VatTaxUtils.TAX_VERSION_V2);
            detail.setTaxTime(taxTime);
            updateList.add(detail);
            // 5.2.4 更新本月累计
            taxSum.setAmounts(prevAmount.add(pretax).doubleValue());
            taxSum.setVatAmounts(prevVat.add(vat).doubleValue());
            taxSum.setCityTaxAmounts(prevCityTax.add(cityTax).doubleValue());
            taxSum.setLaborPretaxAmounts(prevLaborPretax.add(laborPretax).doubleValue());
            taxSum.setTaxAmounts(prevTax.add(taxAmount).doubleValue());
            taxSum.setTaxedAmounts(prevTaxed.add(taxedAmount).doubleValue());
            pretaxTotal = pretaxTotal.add(pretax);
            vatTotal = vatTotal.add(vat);
            cityTaxTotal = cityTaxTotal.add(cityTax);
            laborPretaxTotal = laborPretaxTotal.add(laborPretax);
            taxTotal = taxTotal.add(taxAmount);
            taxedTotal = taxedTotal.add(taxedAmount);
        }
        // 6. 批量更新所有明细
        for (ServiceFunddetail d : updateList) {
            this.updateById(d);
        }
        // 7. 更新主表 service_fund 的 6 个金额、算税时间、状态、版本
        ServiceFund serviceFund = new ServiceFund();
        serviceFund.setId(fundid);
        serviceFund.setPretaxcost(pretaxTotal.doubleValue());
        serviceFund.setVatCost(vatTotal.doubleValue());
        serviceFund.setCityTaxCost(cityTaxTotal.doubleValue());
        serviceFund.setLaborPretaxCost(laborPretaxTotal.doubleValue());
        serviceFund.setTaxcost(taxTotal.doubleValue());
        serviceFund.setTaxedcost(taxedTotal.doubleValue());
        serviceFund.setTaxVersion(VatTaxUtils.TAX_VERSION_V2);
        serviceFund.setFundtaxtime(taxTime);
        serviceFund.setIstax(1);
        serviceFundMapper.updateById(serviceFund);
        return true;
    }
    /**
     * null 安全的金额转换
     */
    private static BigDecimal toMoney(Double value) {
        return value == null ? BigDecimal.ZERO : BigDecimal.valueOf(value);
    }
    /**
     * 报错时能定位到具体人员
     */
    private static String safeName(ServiceFunddetail detail) {
        String name = detail.getBeneficiaryname() == null ? "" : detail.getBeneficiaryname();
        String idcard = detail.getIdcardno() == null ? "" : detail.getIdcardno();
        return name + "(" + idcard + ")";
    }
//    @Override
//    public Boolean calculateTax2(List<ServiceFunddetail> serviceFunddetails) {
//        //用于缓存每个身份证号(idcardno)本月累计的税前、税金、税后金额(TaxMoneySumEO对象)
//        Map<String, TaxMoneySumEO> tempTaxSumMap = new HashMap<>();
//
//        TaxMoneyByItemEO taxMoneyVO = new TaxMoneyByItemEO();
//        Date firstDay = Date.from(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
//        taxMoneyVO.setFirstDay(firstDay);
//        taxMoneyVO.setTaxTime(new Date());
//
//        List<TaxMoneySumEO> taxSum = serviceFunddetailMapper.getTaxSum(taxMoneyVO);
//        for (TaxMoneySumEO taxMoneySumEO : taxSum) {
//            tempTaxSumMap.put(taxMoneySumEO.getIDCardNo(), taxMoneySumEO);
//        }
//
//        return calculateTax(serviceFunddetails, tempTaxSumMap);
//    }
    @Override
    public Map<String, Double> performance(ServiceFunddetail serviceFunddetail) {
        //根据"身份证号"和"绩效日期(年份)"查询个人历史绩效
        ServiceFunddetail serviceFunddetailEo = new ServiceFunddetail();
        serviceFunddetailEo.setIdcardno(serviceFunddetail.getIdcardno());
        serviceFunddetailEo.setApplytype("5");
        Calendar cal = Calendar.getInstance();
        //默认本年度
        serviceFunddetailEo.setJxrq(String.valueOf(cal.get(Calendar.YEAR)));
        List<ServiceFunddetail> serviceFunddetails = queryList(serviceFunddetailEo);
        //统计历史的税
        BigDecimal historyTax = BigDecimal.valueOf(0.00);
        //计算扣去每月5000的历史税前金额
        BigDecimal historyTaxBefore = BigDecimal.valueOf(0.00);
        //本月是否已经算过绩效(下面扣除5000需要用到这个,如果本月已经扣过5000,就不再扣了)
        Boolean deduct = false;
        //获取当前月份
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String nowMonth = sdf.format(date);
        for (ServiceFunddetail serviceFunddetail1 : serviceFunddetails) {
            historyTaxBefore = historyTaxBefore.add(BigDecimal.valueOf(serviceFunddetail1.getAmount())).subtract(BigDecimal.valueOf(5000));
            historyTax = historyTax.add(BigDecimal.valueOf(serviceFunddetail1.getTaxamount()));
            if (serviceFunddetail1.getJxrq().equals(nowMonth)) {
                deduct = true;
            }
        }
        BigDecimal allValue = BigDecimal.valueOf(0.00);
        //先查询一下本月是否已经算过绩效(一个月只减一次5000,如果上一次已经减过,这一次就不在减了)
        if (deduct == true) {
            //本月已经减过5000了
            allValue = historyTaxBefore.add(BigDecimal.valueOf(serviceFunddetail.getAmount()));
        } else {
            BigDecimal subtract = BigDecimal.valueOf(serviceFunddetail.getAmount()).subtract(BigDecimal.valueOf(5000));
            allValue = historyTaxBefore.add(subtract);
        }
        //计算加上本次的税前金额的总税
        BigDecimal personTaxation = PerformanceTaxtUtils.getPersonTaxation(allValue);
        //计算本次的税
        BigDecimal nowSingleTax = personTaxation.subtract(historyTax);
        //计算本次的税后
        BigDecimal taxAfter = BigDecimal.valueOf(serviceFunddetail.getAmount()).subtract(nowSingleTax);
        //将计算出来的数据放到serviceFunddetail中
        serviceFunddetail.setTaxamount(nowSingleTax.doubleValue());
        serviceFunddetail.setTaxedamount(taxAfter.doubleValue());
        // 绩效不属于专家费:不计算增值税/城建税,劳务税前 = 税前金额
        serviceFunddetail.setVatAmount(0.0);
        serviceFunddetail.setCityTaxAmount(0.0);
        serviceFunddetail.setLaborPretaxAmount(serviceFunddetail.getAmount());
        serviceFunddetail.setJxrq(nowMonth);
        save(serviceFunddetail);
        Map map = new HashMap();
        map.put("amount", serviceFunddetail.getAmount());
        map.put("taxedamount", taxAfter.doubleValue());
        return map;
    }
    @Override
    public List<SpStatBonus> getListBySpStatBonus(SpStatBonusReq spStatBonusReq) {
        return spStatBonusMapper.getListBySpStatBonus(spStatBonusReq.getPabegtime(), spStatBonusReq.getPaendtime(), spStatBonusReq.getPadeptno(), spStatBonusReq.getPausername());
    }
}