/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.yifu.cloud.plus.v1.yifu.salary.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainSelectVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprArchivesProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.SocialDaprUtils;
import com.yifu.cloud.plus.v1.yifu.salary.constants.SalaryConstants;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccountItem;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryTaxConfig;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TStatisticsBonus;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSalaryAccountMapper;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TStatisticsBonusMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryAccountItemService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryTaxConfigService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TStatisticsBonusService;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TPaymentVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TStatisticsBonusImportVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TStatisticsBonusSearchVo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TPaymentInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 全年一次性奖金申报表
 *
 * @author huyc
 * @date 2022-08-14 21:31:15
 */
@Log4j2
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(DaprArchivesProperties.class)
public class TStatisticsBonusServiceImpl extends ServiceImpl<TStatisticsBonusMapper, TStatisticsBonus> implements TStatisticsBonusService {

	private final TSalaryTaxConfigService tSalaryTaxConfigService;

	private final DaprArchivesProperties archivesProperties;

	private final TSalaryAccountItemService tSalaryAccountItemService;

	private final TSalaryAccountMapper accountMapper;

	private final SocialDaprUtils socialDaprUtils;

    /**
     * 全年一次性奖金申报表简单分页查询
     * @param tStatisticsBonus 全年一次性奖金申报表
     * @return
     */
    @Override
    public IPage<TStatisticsBonus> getTStatisticsBonusPage(Page<TStatisticsBonus> page, TStatisticsBonusSearchVo tStatisticsBonus){
        return baseMapper.getTStatisticsBonusPage(page,tStatisticsBonus);
    }

    /**
     * 全年一次性奖金申报表批量导出
     * @param searchVo 全年一次性奖金申报表
     * @return
     */
    @Override
    public void listExport(HttpServletResponse response, TStatisticsBonusSearchVo searchVo){
        String fileName = "全年一次性奖金批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
        //获取要导出的列表
        List<TStatisticsBonus> list = new ArrayList<>();
        long count = noPageCountDiy(searchVo);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
            response.setCharacterEncoding("utf-8");
            response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , "UTF-8"));
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
            ExcelWriter  excelWriter = EasyExcel.write(out, TStatisticsBonus.class).build();
            int index = 0;
            if (count >  CommonConstants.ZERO_INT){
                for (int i = 0; i <= count; ) {
                    // 获取实际记录
                    searchVo.setLimitStart(i);
                    searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
                    list = noPageDiy(searchVo);
                    if (Common.isNotNull(list)){
                        ExcelUtil<TStatisticsBonus> util = new ExcelUtil<>(TStatisticsBonus.class);
                        for (TStatisticsBonus vo:list){
                            util.convertEntity(vo,null,null,null);
                        }
                    }
                    if (Common.isNotNull(list)){
                        WriteSheet writeSheet = EasyExcel.writerSheet("全年一次性奖金申报表"+index).build();
                        excelWriter.write(list,writeSheet);
                        index++;
                    }
                    i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
                    if (Common.isNotNull(list)){
                        list.clear();
                    }
                }
            }else {
                WriteSheet writeSheet = EasyExcel.writerSheet("全年一次性奖金申报表"+index).build();
                excelWriter.write(list,writeSheet);
            }
            if (Common.isNotNull(list)){
                list.clear();
            }
            out.flush();
            excelWriter.finish();
        }catch (Exception e){
            log.error("执行异常" ,e);
        }finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                log.error("执行异常", e);
            }
        }
    }

	/**
	 * 全年一次性奖金测算
	 * @param deptId 部门ID
	 * @return
	 */
	@Override
	public void importDiy(HttpServletResponse response, List<TStatisticsBonusImportVo> list, String deptId){
		String fileName = "全年一次性奖金测算导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		ServletOutputStream out = null;
		//本次纳税额
		BigDecimal res;
		//应发工资合计
		BigDecimal ySalary;
		//未发薪资（年终奖和12月工资未发薪资）
		BigDecimal wSalary;
		//薪资扣除额合计
		BigDecimal sumDeductSalary;
		//专项扣除汇总金额
		BigDecimal sdSum;
		//薪资扣税合计
		BigDecimal sumTax;
		//工资下限
		BigDecimal minSalary;
		BigDecimal isTax;
		//减除费用
		BigDecimal costReduction;
		//年终奖上限
		BigDecimal maxAnualSalary;
		//年终奖单独扣税12月税费
		BigDecimal finalSalaryNoSalary;
		//年终奖合并扣税12月税费
		BigDecimal finalSalaryWithSalary;
		//12月已发工资税费
		BigDecimal twlSalaryTax;
		//12月社保公积金扣费
		BigDecimal socialFundTax;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , "UTF-8"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TStatisticsBonusImportVo.class).build();
			int index = 0;
			//个税配置
			List<TSalaryTaxConfig> personTax = tSalaryTaxConfigService.getTaxConfigByPersonList(new TSalaryTaxConfig());
			//年终奖配置
			List<TSalaryTaxConfig> annousTax = tSalaryTaxConfigService.getTaxConfigByAnnualBonusList(new TSalaryTaxConfig());

			R<TSettleDomainSelectVo> sdr = HttpDaprUtil.invokeMethodPost(archivesProperties.getAppUrl(), archivesProperties.getAppId()
					, "/tsettledomain/inner/getSettleDomainVoById", deptId, TSettleDomainSelectVo.class, SecurityConstants.FROM_IN);
			// 结算主体
			String invoiceTitle = "";
			TSettleDomainSelectVo dept = null;
			if (sdr != null && sdr.getData() != null) {
				dept = sdr.getData();
			}
			if (dept != null && dept.getId() != null) {
				invoiceTitle = dept.getBusinessSubjectName();
			}

			if (list.size() >  CommonConstants.ZERO_INT){
				List<String> idCardList = new ArrayList<>();
				for (TStatisticsBonusImportVo vo : list) {
					if (Common.isNotNull(vo.getEmpIdcard())) {
						idCardList.add(vo.getEmpIdcard());
					}
				}
				Map<String, List<TSalaryAccountItem>> itemMap = tSalaryAccountItemService.getSalaryItemVoList(idCardList, invoiceTitle);
				for (TStatisticsBonusImportVo infoVo: list) {
					//本次纳税额
					res = BigDecimal.ZERO;
					//应发工资合计
					ySalary = BigDecimal.ZERO;
					//未发薪资（年终奖和12月工资未发薪资）
					wSalary = BigDecimal.ZERO;
					//薪资扣除额合计
					sumDeductSalary = BigDecimal.ZERO;
					//专项扣除汇总金额
					sdSum = BigDecimal.ZERO;
					//薪资扣税合计
					sumTax = BigDecimal.ZERO;
					minSalary = BigDecimal.ZERO;
					maxAnualSalary = BigDecimal.ZERO;
					costReduction = BigDecimal.ZERO;
					isTax = BigDecimal.ZERO;
					twlSalaryTax = BigDecimal.ZERO;
					//12月是否发薪
					Boolean isSend = false;
					//年终奖单独扣税12月税费
					finalSalaryNoSalary = BigDecimal.ZERO;
					//年终奖合并扣税12月税费
					finalSalaryWithSalary = BigDecimal.ZERO;
					//12月份应纳税所得额扣除费用
					BigDecimal deductTaxSalary = infoVo.getDeductTaxSalary();
					//12月社保公积金扣费
					socialFundTax = BigDecimal.ZERO;
					//专项扣除列表
					List<BigDecimal> sdSumList = new ArrayList<>();
					//减除费用列表
					List<BigDecimal> costReductionList = new ArrayList<>();

					//查询缴费库获取生成月为12月的社保公积金扣费
					List<TPaymentInfo> paymentInfoList = new ArrayList<>();
					TPaymentInfo paymentInfo = new TPaymentInfo();
					paymentInfo.setEmpIdcard(infoVo.getEmpIdcard());
					paymentInfo.setSettleDomainId(deptId);
					R<TPaymentVo> paymentVo = socialDaprUtils.getPaymentSocialAndFound(paymentInfo);
					if (paymentVo != null && paymentVo.getData() != null && paymentVo.getData().getPaymentInfoList() != null) {
						paymentInfoList = paymentVo.getData().getPaymentInfoList();
					}
					for (TPaymentInfo infoPayment: paymentInfoList) {
						socialFundTax = BigDecimalUtils.safeAdd(infoPayment.getSocialSecurityPersonalSum(),
								infoPayment.getPersonalProvidentSum());
					}

					List<TSalaryAccountItem> list1 = itemMap.get(infoVo.getEmpIdcard());
					if (Common.isNotNull(list1)) {
						for (TSalaryAccountItem item: list1) {
							if (SalaryConstants.RELAY_SALARY_JAVA.equals(item.getJavaFiedName())) {
								ySalary = ySalary.add(item.getSalaryMoney());
							}
							if (item.getSettlementMonth().contains(CommonConstants.TWELVE_STRING)) {
								//减除费用
								if (SalaryConstants.COST_REDUCTION_JAVA.equals(item.getJavaFiedName())) {
									costReductionList.add(item.getSalaryMoney());
								}
								//专项扣除
								if (SalaryConstants.SPECIAL_DEDU_MONEY_SUM_JAVA.equals(item.getJavaFiedName())) {
									sdSumList.add(item.getSalaryMoney());
								}
							}
							if (SalaryConstants.SALARY_TAX_JAVA.equals(item.getJavaFiedName())) {
								//12月份个税
								if (item.getSettlementMonth().contains(CommonConstants.TWELVE_STRING)) {
									twlSalaryTax = twlSalaryTax.add(item.getSalaryMoney());
								} else {
									//1-11月份个税
									sumTax = sumTax.add(item.getSalaryMoney());
								}
							}
							if (SalaryConstants.PERSONAL_SOCIAL_JAVA.equals(item.getJavaFiedName())) {
								isTax = isTax.add(item.getSalaryMoney());
							}
							if (SalaryConstants.PERSONAL_FUND_JAVA.equals(item.getJavaFiedName())) {
								isTax = isTax.add(item.getSalaryMoney());
							}
							if (SalaryConstants.EXEMPTION_PERSION_TAX_JAVA.equals(item.getJavaFiedName())) {
								isTax = isTax.add(item.getSalaryMoney());
							}
							if (SalaryConstants.WITHHOLIDING_PERSON_SOCIAL.equals(item.getJavaFiedName())) {
								isTax = isTax.add(item.getSalaryMoney());
							}
							if (SalaryConstants.WITHHOLIDING_PERSON_FUND.equals(item.getJavaFiedName())) {
								isTax = isTax.add(item.getSalaryMoney());
							}
							if (SalaryConstants.ENTERPRISE_ANNUITY_JAVA.equals(item.getJavaFiedName())) {
								isTax = isTax.add(item.getSalaryMoney());
							}
							if (SalaryConstants.ONLY_CHILD_JAVA.equals(item.getJavaFiedName())) {
								isTax = isTax.add(item.getSalaryMoney());
							}
						}
					}
					if (CommonConstants.IS_TRUE.equals(infoVo.getIsTSend())) {
						isSend = true;
					}
					if (Common.isNotNull(sdSumList)) {
						sdSum = Collections.max(sdSumList);
					}
					if (Common.isNotNull(costReductionList)) {
						costReduction = Collections.max(costReductionList);
					}
					//当月工资已发
					if (isSend) {
						//年终奖单独扣税
						finalSalaryNoSalary = BigDecimalUtils.safeAdd(calculationSalary(annousTax,infoVo.getAnnualBonus()),twlSalaryTax);
						wSalary = infoVo.getAnnualBonus();
						finalSalaryWithSalary = BigDecimalUtils.safeSubtract(calculationSalaryT(personTax,
								BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary,infoVo.getAnnualBonus()),
								BigDecimalUtils.safeAdd(sdSum,isTax,costReduction))),sumTax);
						//12月薪资扣除额合计
						sumDeductSalary = BigDecimalUtils.safeAdd(sdSum,isTax,costReduction);
					} else {
						//当月工资未发
						//年终奖单独扣税
						wSalary = BigDecimalUtils.safeAdd(infoVo.getAnnualBonus(), infoVo.getAnnualTSalary());
						finalSalaryNoSalary = calculationSalary(annousTax,wSalary);
						//年终奖合并扣税
						finalSalaryWithSalary = BigDecimalUtils.safeSubtract(calculationSalaryT(personTax,BigDecimalUtils.safeSubtract(
								BigDecimalUtils.safeAdd(wSalary,ySalary),BigDecimalUtils.safeAdd(
										infoVo.getDeductTaxSalary(),isTax))),sumTax);
						//12月薪资扣除额合计
						sumDeductSalary = BigDecimalUtils.safeAdd(isTax,infoVo.getDeductTaxSalary());
					}

					if (BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary, wSalary), sumDeductSalary).
							compareTo(new BigDecimal("36000")) <= 0) {
						if (wSalary.compareTo(new BigDecimal("36000")) <= 0) {
							if (isSend) {
								maxAnualSalary = wSalary;
							} else {
								minSalary = socialFundTax;
								maxAnualSalary = BigDecimalUtils.safeSubtract(wSalary,socialFundTax);
							}
						}else {
							minSalary =  BigDecimalUtils.safeSubtract(wSalary,new BigDecimal("36000"));
							maxAnualSalary = new BigDecimal("36000");
						}
					} else if (BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary, wSalary), sumDeductSalary).
							compareTo(new BigDecimal("72000")) <= 0) {
						if (wSalary.compareTo(new BigDecimal("36000")) <= 0) {
							if (isSend) {
								maxAnualSalary = wSalary;
							} else {
								minSalary = socialFundTax;
								maxAnualSalary = BigDecimalUtils.safeSubtract(wSalary,socialFundTax);
							}
						}else {
							minSalary =  BigDecimalUtils.safeSubtract(wSalary,new BigDecimal("36000"));
							maxAnualSalary = new BigDecimal("36000");
						}
					}else if (BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary, wSalary), sumDeductSalary).
							compareTo(new BigDecimal("203100")) <= 0) {
						if (wSalary.compareTo(new BigDecimal("36000")) <= 0) {
							if (isSend) {
								maxAnualSalary = wSalary;
							} else {
								minSalary = socialFundTax;
								maxAnualSalary = BigDecimalUtils.safeSubtract(wSalary,socialFundTax);
							}
						}else {
							minSalary =  BigDecimalUtils.safeSubtract(wSalary,new BigDecimal("36000"));
							maxAnualSalary = new BigDecimal("36000");
						}
					}else if (BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary, wSalary), sumDeductSalary).
							compareTo(new BigDecimal("288000")) <= 0) {
						if (wSalary.compareTo(new BigDecimal("144000")) <= 0) {
							if (isSend) {
								maxAnualSalary = wSalary;
							} else {
								minSalary = socialFundTax;
								maxAnualSalary = BigDecimalUtils.safeSubtract(wSalary,socialFundTax);
							}
						}else {
							minSalary =  BigDecimalUtils.safeSubtract(wSalary,new BigDecimal("144000"));
							maxAnualSalary = new BigDecimal("144000");
						}
					}else if (BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary, wSalary), sumDeductSalary).
							compareTo(new BigDecimal("672000")) <= 0) {
						if (wSalary.compareTo(new BigDecimal("144000")) <= 0) {
							if (isSend) {
								maxAnualSalary = wSalary;
							} else {
								minSalary = socialFundTax;
								maxAnualSalary = BigDecimalUtils.safeSubtract(wSalary,socialFundTax);
							}
						}else {
							minSalary =  BigDecimalUtils.safeSubtract(wSalary,new BigDecimal("36000"));
							maxAnualSalary = new BigDecimal("36000");
						}
					}else if (BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary, wSalary), sumDeductSalary).
							compareTo(new BigDecimal("1277500")) <= 0) {
						if (wSalary.compareTo(new BigDecimal("300000")) <= 0) {
							if (isSend) {
								maxAnualSalary = wSalary;
							} else {
								minSalary = socialFundTax;
								maxAnualSalary = BigDecimalUtils.safeSubtract(wSalary,socialFundTax);
							}
						}else {
							minSalary =  BigDecimalUtils.safeSubtract(wSalary,new BigDecimal("300000"));
							maxAnualSalary = new BigDecimal("300000");
						}
					}else if (BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary, wSalary), sumDeductSalary).
							compareTo(new BigDecimal("1452500")) <= 0) {
						if (wSalary.compareTo(new BigDecimal("420000")) <= 0) {
							if (isSend) {
								maxAnualSalary = wSalary;
							} else {
								minSalary = socialFundTax;
								maxAnualSalary = BigDecimalUtils.safeSubtract(wSalary,socialFundTax);
							}
						}else {
							minSalary =  BigDecimalUtils.safeSubtract(wSalary,new BigDecimal("420000"));
							maxAnualSalary = new BigDecimal("420000");
						}
					}else if (BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(ySalary, wSalary), sumDeductSalary).
							compareTo(new BigDecimal("1452500")) > 0) {
						if (wSalary.compareTo(new BigDecimal("660000")) <= 0) {
							if (isSend) {
								maxAnualSalary = wSalary;
							} else {
								minSalary = socialFundTax;
								maxAnualSalary = BigDecimalUtils.safeSubtract(wSalary,socialFundTax);
							}
						}else {
							minSalary =  BigDecimalUtils.safeSubtract(wSalary,new BigDecimal("660000"));
							maxAnualSalary = new BigDecimal("660000");
						}
					}

					JSONObject jsonObject = calculationPersonSalary(personTax, annousTax, minSalary, maxAnualSalary,
							wSalary, sumTax, ySalary, sumDeductSalary, twlSalaryTax);
					res = jsonObject.getBigDecimal("zySalary");
					BigDecimal anRes = BigDecimal.ZERO;
					if (Common.isNotNull(jsonObject.getBigDecimal("anRes"))) {
						anRes = jsonObject.getBigDecimal("anRes");
					}
					infoVo.setBestPlanTax(res);
					infoVo.setAnnualATax(finalSalaryNoSalary);
					infoVo.setAnnualSTax(finalSalaryWithSalary);
					infoVo.setBestPlanTSalary(anRes);
					infoVo.setBestPlanBonus(BigDecimalUtils.safeSubtract(wSalary,anRes));
				}
				if (Common.isNotNull(list)) {
					WriteSheet writeSheet = EasyExcel.writerSheet("全年一次性奖金测算").build();
					excelWriter.write(list, writeSheet);
				}
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet("全年一次性奖金测算").build();
				excelWriter.write(list,writeSheet);
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	/**
	 * @param personTax 薪资扣税阶梯表list
	 * @param annousTax 年终奖扣税阶梯表list
	 * @param minSalary 工资下限
	 * @param maxAnualSalary 年终奖上限
	 * @param wSalary   未发金额
	 * @param sumTax    薪资扣税合计
	 * @Description: 计算薪资扣税-个税
	 * @Author: huyc
	 * @Date: 2022/8/23
	 * @return: java.math.BigDecimal
	 **/
	private static JSONObject calculationPersonSalary(List<TSalaryTaxConfig> personTax, List<TSalaryTaxConfig> annousTax,
													  BigDecimal minSalary, BigDecimal maxAnualSalary,
													  BigDecimal wSalary, BigDecimal sumTax, BigDecimal ySalary,
													  BigDecimal sumDeductSalary, BigDecimal twlSalaryTax) {
		JSONObject jsonObject = new JSONObject();
		BigDecimal anRes;
		BigDecimal res;
		List<BigDecimal> zySalary = new ArrayList<>();
		Map<String,BigDecimal> map = new HashMap<>();
		for (BigDecimal i = minSalary; i.compareTo(maxAnualSalary) <= 0; i = BigDecimalUtils.safeAdd(i,new BigDecimal(100)) ) {
			//本次薪资纳税额
			res = BigDecimal.ZERO;
			//本次年终奖纳税额
			anRes = BigDecimal.ZERO;;
			//年终奖金额
			BigDecimal annous = BigDecimalUtils.safeSubtract(wSalary,i);
			//计算个税
			if (i.compareTo(BigDecimal.ZERO) == SalaryConstants.MORE_THAN ) {
				BigDecimal sumI = BigDecimalUtils.safeSubtract(BigDecimalUtils.safeAdd(i,ySalary),
						BigDecimalUtils.safeAdd(sumDeductSalary));
				for (TSalaryTaxConfig sub : personTax) {
					if (sumI.compareTo(sub.getMinIncome()) == SalaryConstants.MORE_THAN
							&& sumI.compareTo(sub.getMaxIncome()) != SalaryConstants.MORE_THAN) {
						//sumI = realDeduSalary * ((double) ((i.getTaxRate() * 1.0) / 100)) - sumTax - sub.getQuick();
						//累计个税
						res = BigDecimalUtils.safeSubtract(sumI.multiply(new BigDecimal(sub.getWithholdingRate()).divide(
								SalaryConstants.B_ONEHUNDRED, SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP)), sub.getQuickDeducation());
						//本次个税
						BigDecimal bcTax = res.subtract(BigDecimalUtils.safeAdd(sumTax,twlSalaryTax));
						if (bcTax.compareTo(BigDecimal.ZERO) == SalaryConstants.MORE_THAN ||
								bcTax.compareTo(BigDecimal.ZERO) == SalaryConstants.EQUAL) {
							res = BigDecimalUtils.safeAdd(bcTax,twlSalaryTax);
						} else {
							res = BigDecimalUtils.safeAdd(twlSalaryTax,sumTax);
						}
						res = BigDecimalUtils.safeSubtract(sumI.multiply(new BigDecimal(sub.getWithholdingRate()).divide(
										SalaryConstants.B_ONEHUNDRED, SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP)),
										BigDecimalUtils.safeAdd(sumTax,sub.getQuickDeducation()));
						break;
					}
				}
			} else {
				res = twlSalaryTax;
			}
			//计算年终奖税
			//年终奖
			if (annous != null && annous.compareTo(SalaryConstants.B_ZERO) == SalaryConstants.MORE_THAN
					&& annousTax != null && annousTax.size() > CommonConstants.ZERO_INT) {
				BigDecimal month = annous.divide(SalaryConstants.B_TWELVE, SalaryConstants.TAX_FEE_PLACES, BigDecimal.ROUND_HALF_UP);
				// 应纳税额
				for (TSalaryTaxConfig sub : annousTax) {
					if (month.compareTo(sub.getMinIncome()) == SalaryConstants.MORE_THAN
							&& month.compareTo(sub.getMaxIncome()) != SalaryConstants.MORE_THAN) {
						anRes = annous.multiply(new BigDecimal(sub.getWithholdingRate()).divide(
										SalaryConstants.B_ONEHUNDRED, SalaryConstants.TAX_FEE_PLACES, BigDecimal.ROUND_HALF_UP))
								.subtract(sub.getQuickDeducation());
						break;
					}
				}
			}
			zySalary.add(BigDecimalUtils.safeAdd(res,anRes));
			map.put(BigDecimalUtils.safeAdd(res,anRes).toString(),i);
		}
		BigDecimal salary = BigDecimal.ZERO;
		if (Common.isNotNull(zySalary)) {
			salary = Collections.min(zySalary);
		}
		jsonObject.put("anRes",map.get(salary.toString()));
		jsonObject.put("zySalary",salary);
		map.clear();
		zySalary.clear();
		return jsonObject;
	}

	/**
	 * @param annousTax 薪资扣税阶梯表list
	 * @param annualSalary 年终奖
	 * @Description: 计算薪资扣税-个税
	 * @Author: huyc
	 * @Date: 2022/8/23
	 * @return: java.math.BigDecimal
	 **/
	private static BigDecimal calculationSalary(List<TSalaryTaxConfig> annousTax, BigDecimal annualSalary) {
		//本次年终奖纳税额
		BigDecimal anRes = BigDecimal.ZERO;
		//计算年终奖税
		//年终奖
		if (annualSalary != null && annualSalary.compareTo(SalaryConstants.B_ZERO) == SalaryConstants.MORE_THAN
				&& annousTax != null && annousTax.size() > CommonConstants.ZERO_INT) {
			BigDecimal month = annualSalary.divide(SalaryConstants.B_TWELVE, SalaryConstants.TAX_FEE_PLACES, BigDecimal.ROUND_HALF_UP);
			// 应纳税额
			for (TSalaryTaxConfig sub : annousTax) {
				if (month.compareTo(sub.getMinIncome()) == SalaryConstants.MORE_THAN
						&& month.compareTo(sub.getMaxIncome()) != SalaryConstants.MORE_THAN) {
					anRes = annualSalary.multiply(new BigDecimal(sub.getWithholdingRate()).divide(
									SalaryConstants.B_ONEHUNDRED, SalaryConstants.TAX_FEE_PLACES, BigDecimal.ROUND_HALF_UP))
							.subtract(sub.getQuickDeducation());
					break;
				}
			}
		}
		return anRes;
	}

	/**
	 * @param personTax 薪资扣税阶梯表list
	 * @param annualSalary 年终奖
	 * @Description: 计算薪资扣税-个税
	 * @Author: huyc
	 * @Date: 2022/8/23
	 * @return: java.math.BigDecimal
	 **/
	private static BigDecimal calculationSalaryT(List<TSalaryTaxConfig> personTax, BigDecimal annualSalary) {
		//本次年终奖纳税额
		BigDecimal res = BigDecimal.ZERO;
		//计算年终奖税
		//计算个税
		for (TSalaryTaxConfig sub : personTax) {
			if (annualSalary.compareTo(sub.getMinIncome()) == SalaryConstants.MORE_THAN
					&& annualSalary.compareTo(sub.getMaxIncome()) != SalaryConstants.MORE_THAN) {
				//annualSalary = realDeduSalary * ((double) ((annualSalary.getTaxRate() * 1.0) / 100)) - sumTax - sub.getQuick();
				res = annualSalary.multiply(new BigDecimal(sub.getWithholdingRate()).divide(
								SalaryConstants.B_ONEHUNDRED, SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP))
								.subtract(sub.getQuickDeducation());// 应纳税额
				break;
			}
		}
		return res;
	}

    @Override
    public List<TStatisticsBonus> noPageDiy(TStatisticsBonusSearchVo searchVo) {
        LambdaQueryWrapper<TStatisticsBonus> wrapper = buildQueryWrapper(searchVo);
        List<String> idList = Common.getList(searchVo.getIds());
        if (Common.isNotNull(idList)){
            wrapper.in(TStatisticsBonus::getId,idList);
        }
        if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0){
            wrapper.last(" limit "+ searchVo.getLimitStart() +","+ searchVo.getLimitEnd());
        }
        return baseMapper.selectList(wrapper);
    }

	@Override
	public R batchDelete(String declareMonth) {
		if (Common.isNotNull(declareMonth)) {
			List<TStatisticsBonus> deleteList = baseMapper.selectList(Wrappers.<TStatisticsBonus>query().lambda()
					.in(TStatisticsBonus::getDeclareMonth, declareMonth));
			if (Common.isNotNull(deleteList)) {
				List<String> idList = deleteList.stream().map(TStatisticsBonus::getId).collect(Collectors.toList());
 				baseMapper.deleteBatchIds(idList);
				 return R.ok();
			}
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		return null;
	}

	@Override
	public R doStatisticsBonus() {
		String nowMonth = DateUtil.addMonth(0);  //本月
		TStatisticsBonus std = new TStatisticsBonus();
		std.setDeclareMonth(nowMonth);
		QueryWrapper<TStatisticsBonus> queryWrapperSs = new QueryWrapper<>();
		queryWrapperSs.setEntity(std);
		long num = this.count(queryWrapperSs);
		if (num > 0) {
			return R.failed("上月数据已生成，不可重复生成！");
		} else {
			String lastMonth =  DateUtil.addMonth(-1);  //上月
			String lastYear = lastMonth.substring(0,4);
			List<TStatisticsBonus> stdvoList = baseMapper.doStatisticsBonus(nowMonth,lastYear);
			for (TStatisticsBonus bonus : stdvoList) {
				this.save(bonus);
			}
			return R.ok();
		}
	}

	private  Long noPageCountDiy(TStatisticsBonusSearchVo searchVo) {
        LambdaQueryWrapper<TStatisticsBonus> wrapper = buildQueryWrapper(searchVo);
        List<String> idList = Common.getList(searchVo.getIds());
        if (Common.isNotNull(idList)){
            wrapper.in(TStatisticsBonus::getId,idList);
        }
        return baseMapper.selectCount(wrapper);
    }

    private LambdaQueryWrapper buildQueryWrapper(TStatisticsBonusSearchVo entity){
        LambdaQueryWrapper<TStatisticsBonus> wrapper = Wrappers.lambdaQuery();
		if (Common.isNotNull(entity.getDeclareMonth())) {
			wrapper.eq(TStatisticsBonus::getDeclareMonth,entity.getDeclareMonth());
		}
		if (Common.isNotNull(entity.getDeclareUnit())) {
			wrapper.eq(TStatisticsBonus::getDeclareUnit,entity.getDeclareUnit());
		}
        return wrapper;
    }

}
