package com.yifu.cloud.plus.v1.yifu.salary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TDepartSettlementInfo;
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.BigDecimalUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprArchivesProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprSocialProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.constants.SalaryConstants;
import com.yifu.cloud.plus.v1.yifu.salary.entity.*;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSalaryStandardMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.*;
import com.yifu.cloud.plus.v1.yifu.salary.util.SalaryAccountUtil;
import com.yifu.cloud.plus.v1.yifu.salary.vo.*;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 标准薪酬工资表
 *
 * @author hgw
 * @date 2019-07-30 15:00:05
 */
@Log4j2
@AllArgsConstructor
@Service("salaryUploadService")
@EnableConfigurationProperties({DaprArchivesProperties.class, DaprSocialProperties.class})
public class SalaryUploadServiceImpl extends ServiceImpl<TSalaryStandardMapper, TSalaryStandard> implements SalaryUploadService {

	private final DaprArchivesProperties archivesProperties;

	private final DaprSocialProperties socialProperties;

	private final TSalaryStandardService tSalaryStandardService;

	private final MSalaryEstimateService mSalaryEstimateService;

	private final TSalaryAccountService tSalaryAccountService;

	private final TSalaryAccountItemService tSalaryAccountItemService;

	private final TSalaryConfigStandardService tSalaryConfigStandardService;

	//配置-工资
	private final TConfigSalaryService configSalaryService;

	private final TSpecialDeducationSumService tSpecialDeducationSumService;

	private final TSalaryTaxConfigService tSalaryTaxConfigService;

	private final TPauseSalaryService tPauseSalaryService;

	private final TSalaryEmployeeService employeeService;

	private final TSalaryStandardSetService tSalaryStandardSetService;

	private final TOwnDeptService tOwnDeptService;

	private final TSalaryLockService salaryLockService;

	private final MSalaryPaymentResService salaryPaymentResService;

	private final TSalaryAttaService tSalaryAttaService;

	private final TApprovalRecordService auditLogService;

	/**
	 * @param jsonString 客户原表数据
	 * @param repeatFlag 默认 0：不允许重复导入已存在系统内的数据；1：允许重复导入
	 * @Description: 普通工资上传
	 * @Author: hgw
	 * @Date: 2019/9/4 15:58
	 * @return: com.yifu.cloud.v1.common.core.util.R
	 **/
	@Override
	public R salaryUpload(String jsonString, String settleDepart, String configId, String salaryType) {
		if (Common.isNotNull(jsonString) && Common.isNotNull(settleDepart) && Common.isNotNull(configId) && Common.isNotNull(salaryType)) {
			R<TSettleDomainSelectVo> sdr = HttpDaprUtil.invokeMethodPost(archivesProperties.getAppUrl(), archivesProperties.getAppId()
					, "/tsettledomain/inner/getSettleDomainVoById", settleDepart, TSettleDomainSelectVo.class, SecurityConstants.FROM_IN);
			// 结算主体
			TSettleDomainSelectVo dept = null;
			if (sdr != null && sdr.getData() != null) {
				dept = sdr.getData();
			}
			if (dept == null || dept.getId() == null) {
				return R.failed("新建工资主表失败-获取结算主体信息为空");
			}
			// 2020-3-29 11:24:14变更为结算主体的封面抬头
			String invoiceTitle = dept.getBusinessSubjectName();
			if (Common.isEmpty(invoiceTitle)) {
				return R.failed("上传失败-获取结算主体的-封面抬头-信息为空，请去<客户管理-结算主体>模块，编辑封面抬头后再导入");
			}
			// 薪资识别配置（原表-标准模板）
			List<TSalaryConfigStandard> salaryAccountList = tSalaryConfigStandardService.list();
			Map<String, TSalaryConfigStandard> salaryConfigMap = new HashMap<>();  //存放所有字段
			Map<String, Boolean> isMustMap = new HashMap<>();  //存放必填字段
			for (TSalaryConfigStandard sc : salaryAccountList) {
				salaryConfigMap.put(sc.getCnName(), sc);
				if (Common.isNotNull(sc.getIsMustNeed()) && SalaryConstants.IS_MUST.equals(sc.getIsMustNeed())) {
					isMustMap.put(sc.getDbFiedName(), true);
				}
			}
			// 薪资配置-结算月、社保月等信息
			TConfigSalary configSalary = configSalaryService.getById(configId);

			YifuUser user = SecurityUtils.getUser();
			if (null == user || null == user.getId()) {
				return R.failed("获取登录用户信息失败！");
			}
			try {
				jsonString = URLDecoder.decode(jsonString, "UTF-8").replace("=", "");
				SalaryAccountUtil util1 = new SalaryAccountUtil();

				TSalaryEmployee empSearch = new TSalaryEmployee();
				empSearch.setUnitId(dept.getCustomerId());
				List<TSalaryEmployee> empList = employeeService.list(Wrappers.<TSalaryEmployee>query().lambda()
						.eq(TSalaryEmployee::getUnitId, dept.getCustomerId()));
				Map<String, TSalaryEmployee> empIdCardMap = new HashMap<>();
				Map<String, TSalaryEmployee> empNameMap = new HashMap<>();
				boolean isDuplicateName = false;
				if (empList != null) {
					TSalaryEmployee es;//筛选人员，添加判断：非在职，或开户行为空，或 结算主体等于选择的结算主体且在职，都可以存入Map优先备用
					for (TSalaryEmployee e : empList) {
						es = empIdCardMap.get(e.getEmpIdcard());
						if (es == null || CommonConstants.ZERO_INT != es.getFileStatus() || Common.isEmpty(es.getBankName())
								|| (e.getDeptId().equals(settleDepart) && CommonConstants.ZERO_INT == e.getFileStatus()
								&& Common.isNotNull(e.getBankName()))) {
							empIdCardMap.put(e.getEmpIdcard(), e);
							empNameMap.put(e.getEmpName().replace(" ", ""), e);
						}
					}
					if (empNameMap.size() == empIdCardMap.size()) {
						isDuplicateName = true;
					}
				}
				// 自有员工结算主体id，新员工使用
				Map<String, Integer> ownDeptMap = tOwnDeptService.getOwnDeptMap();
				// 自有员工所在结算主体Map
				Map<String, Integer> ownEmployeeMap = tOwnDeptService.getOwnEmpMap();

				// 2.6.6:校验导入数据重复的Map格式：#身份证号_工资月份_报表类型_应发金额
				Map<String, Integer> checkMap = tSalaryAccountService.getAccountCheckMap(dept.getId(), DateUtil.addMonth(configSalary.getSalaryMonth()));
				util1.getJsonStringToList(user, jsonString,
						dept, configSalary, salaryConfigMap, isMustMap, empIdCardMap, empNameMap, isDuplicateName
						, salaryType, invoiceTitle, employeeService, checkMap, ownEmployeeMap, ownDeptMap, tSalaryAccountService);
				List<TSalaryAccountVo> saList = util1.getEntityList();

				if ((null != util1.getErrorInfo() && !util1.getErrorInfo().isEmpty())) {
					return R.failed(util1.getErrorInfo());
				} else {
					if (null != saList && !saList.isEmpty()) {
						// return R.ok(saList)
						return this.saveAndSubmit(saList);
					} else {
						return R.failed("导入数据不可为空");
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage());
				return R.failed("数据导入解析失败！");
			}
		}
		return R.failed("导入数据不可为空");
	}

	/**
	 * @param strList list
	 * @Description: 返回idStr
	 * @Author: hgw
	 * @Date: 2019/10/17 14:50
	 * @return: java.lang.String
	 **/
	public static String salaryEstimateListToStr(List<MSalaryEstimate> strList) {
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < strList.size(); i++) {
			if (i == 0) {
				result.append("'").append(strList.get(0).getEstimateId()).append("'");
			} else {
				result.append(",'").append(strList.get(i).getEstimateId()).append("'");
			}
		}
		return result.toString();
	}

	// 判断一个字符串是否含有数字
	public static boolean HasNumber(String content) {
		boolean flag = false;
		Pattern p = Pattern.compile(".*\\d+.*");
		Matcher m = p.matcher(content);
		if (m.matches()) {
			flag = true;
		}
		return flag;
	}

	/**
	 * @param sav  报账表vo
	 * @param dept 结算主体
	 * @param user 登录人
	 * @Description: 新建工资主表
	 * @Author: hgw
	 * @Date: 2019/9/26 9:44
	 * @return: com.yifu.cloud.v1.hrms.api.entity.TSalaryStandard
	 **/
	public R<TSalaryStandard> saveNewTSalary(TSalaryAccountVo sav, TSettleDomainSelectVo dept, YifuUser user,
											 LocalDateTime nowTime) {
		TSalaryStandard s = null;
		if (sav != null) {
			if (null == user || null == user.getId()) {
				return null;
			}
			s = new TSalaryStandard();
			s.setType(CommonConstants.ZERO_INT);
			s.setBelongDeptId(String.valueOf(user.getDeptId()));
			if (Common.isNotNull(user.getDeptName())) {
				s.setBelongDeptCode(user.getDeptName());
			} else {
				s.setBelongDeptCode("未获取到员工的DeptName");
			}
			s.setCreateTime(nowTime);
			s.setDeleteFlag(SalaryConstants.NOT_DELETE);
			s.setDeptId(dept.getId());
			s.setDeptName(dept.getDepartName());
			s.setDeptNo(dept.getDepartNo());
			if (dept.getProvince() != null) {
				s.setProvince(dept.getProvince());
			}
			if (dept.getCity() != null) {
				s.setCity(dept.getCity());
			}
			if (dept.getTown() != null) {
				s.setTown(dept.getTown());
			}
			s.setFormType(sav.getFormType());
			s.setMoneyFrom(CommonConstants.ZERO_INT);
			s.setSalaryMonth(sav.getSalaryMonth());
			s.setSettlementMonth(sav.getSettlementMonth());
			//s.setSettlementAmount()
			s.setStatus(SalaryConstants.AUDIT_STATUS[0]);
		}
		return new R<>(s);
	}

	/**
	 * @param savList 报账表Vo
	 * @Description: 保存并提交
	 * @Author: hgw
	 * @Date: 2019/9/20 17:05
	 * @return: com.yifu.cloud.v1.common.core.util.R
	 **/
	@Override
	public R saveAndSubmit(List<TSalaryAccountVo> savList) {
		if (Common.isNotNull(savList) && !savList.isEmpty()) {
			TSalaryAccountVo salaryAccountVo = savList.get(0);
			List<TSalaryAccountItem> saiList = null;  //报账明细List
			TSalaryAccountItem sai = null;  //报账明细
			R<TSettleDomainSelectVo> sdr = HttpDaprUtil.invokeMethodPost(archivesProperties.getAppUrl(), archivesProperties.getAppId()
					, "/tsettledomain/inner/getSettleDomainVoById", salaryAccountVo.getDeptId(), TSettleDomainSelectVo.class, SecurityConstants.FROM_IN);
			//结算主体
			TSettleDomainSelectVo dept = null;
			if (sdr != null && sdr.getData() != null) {
				dept = sdr.getData();
			}
			if (dept == null || dept.getId() == null) {
				return R.failed("新建工资主表失败-获取结算主体信息为空");
			}
			String invoiceTitle = dept.getBusinessSubjectName();
			if (Common.isEmpty(invoiceTitle)) {
				return R.failed("新建工资主表失败-获取结算主体的-封面抬头-信息为空，请去<客户管理-结算主体>模块，编辑封面抬头后再导入");
			}

			YifuUser user = SecurityUtils.getUser();
			if (null == user || null == user.getId()) {
				return R.failed("新建工资主表失败-获取登录人信息为空");
			}
			LocalDateTime nowTime = LocalDateTime.now();
			TSalaryStandard salary;
			R<TSalaryStandard> sr = this.saveNewTSalary(salaryAccountVo, dept, user, nowTime);  //工资主表
			if (sr == null || sr.getCode() == CommonConstants.FAIL) {
				return sr;
			} else {
				salary = sr.getData();
			}
			boolean isActual = false;  //false：应发导入； true：实发 倒推导入
			List<TSalaryAccountItemVo> itemList = salaryAccountVo.getSaiList();
			for (TSalaryAccountItemVo item : itemList) {
				if (SalaryConstants.ACTUAL_SALARY_SUM_JAVA.equals(item.getJavaFiedName())) {
					isActual = true;
					break;
				}
			}
			if (salary != null) {

				// 薪资导入、删除前加锁：
				TSalaryLock lock = salaryLockService.lambdaQuery()
						.eq(TSalaryLock::getDeptId, dept.getId())
						.eq(TSalaryLock::getDeleteFlag, CommonConstants.ZERO_INT)
						.last("limit 1").one();
				if (lock != null && Common.isNotNull(lock.getId())) {
					return R.failed("当前结算主体已被用户锁定，请稍等！超过10分钟还没释放，请联系管理员！当前时间：" + nowTime);
				} else {
					lock = new TSalaryLock();
					lock.setCreateTime(nowTime);
					lock.setDeleteFlag(CommonConstants.ZERO_INT);
					lock.setDeptId(dept.getId());
					lock.setDeptName(dept.getDepartName());
					lock.setSettleMonth(salaryAccountVo.getSettlementMonth());
					lock.setType(CommonConstants.ZERO_INT);
					salaryLockService.save(lock);
					TSalaryLock lockUpdate;
					try {
						// 薪资核心导入代码
						return this.doCoreSalary(savList, salaryAccountVo, saiList, sai, dept, invoiceTitle, user, nowTime, salary, isActual);
					} catch (Exception e) {
						lockUpdate = new TSalaryLock();
						lockUpdate.setId(lock.getId());
						lockUpdate.setDeleteFlag(CommonConstants.ONE_INT);
						salaryLockService.updateById(lockUpdate);
						throw new RuntimeException(e.getMessage() == null ? "薪资导入失败！" : e.getMessage());
					} finally {
						lockUpdate = new TSalaryLock();
						lockUpdate.setId(lock.getId());
						lockUpdate.setDeleteFlag(CommonConstants.ONE_INT);
						if (Common.isNotNull(salary.getId())) {
							lockUpdate.setSalaryId(salary.getId());
							lockUpdate.setSettleMoney(salary.getSettlementAmount());
						}
						salaryLockService.updateById(lockUpdate);
					}
				}
			} else {
				return R.failed("新建工资主表失败");
			}
		}
		return R.failed("提交的数据不可为空");
	}

	/**
	 * @Description: 薪资导入核心代码
	 * @Author: hgw
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.String>
	 **/
	@Transactional
	public R doCoreSalary(List<TSalaryAccountVo> savList, TSalaryAccountVo salaryAccountVo
			, List<TSalaryAccountItem> saiList, TSalaryAccountItem sai, TSettleDomainSelectVo dept
			, String invoiceTitle, YifuUser user, LocalDateTime nowTime, TSalaryStandard salary
			, boolean isActual) {
		List<TSalaryAccount> aList;
		TSalaryAccount a;//定库：
		List<TPaymentBySalaryVo> socialEstmateList = null;  //社保预估库
		List<TPaymentBySalaryVo> fundEstmateList = null;  //公积金预估库
		List<MSalaryPaymentRes> salaryPaymentList = salaryPaymentResService.list(Wrappers.<MSalaryPaymentRes>query().lambda()
				.eq(MSalaryPaymentRes::getDeptId, dept.getId()));  //薪资缴费库同步表list
		Map<String, MSalaryPaymentRes> salaryPaymentMap = new HashMap<>();  //薪资缴费库同步表Map
		List<TPaymentBySalaryVo> noSalarySocialEstmateList = null;  //无工资人员-社保预估库
		List<TPaymentBySalaryVo> noSalaryFundEstmateList = null;  //无工资人员-公积金预估库
		List<TPaymentBySalaryVo> noSalarySocialEstmateListCopy;  //无工资人员-社保预估库-循环
		List<TPaymentBySalaryVo> noSalaryFundEstmateListCopy;  //无工资人员-公积金预估库-循环
		TPaymentBySalaryVo forecast = new TPaymentBySalaryVo();
		if (salaryPaymentList != null && !salaryPaymentList.isEmpty()) {
			for (MSalaryPaymentRes res : salaryPaymentList) {
				salaryPaymentMap.put(res.getId(), res);
			}
		}
		//不扣社保
		if (salaryAccountVo != null && !CommonConstants.ZERO_STRING.equals(salaryAccountVo.getIsDeductSocial())) {
			forecast.setSettleDomainId(dept.getId());
			if (SalaryConstants.PRIORITY_ZERO.equals(salaryAccountVo.getSocialPriority())) {
				forecast.setSocialCreateMonth(salaryAccountVo.getDeduSocialMonth());
			} else if (SalaryConstants.PRIORITY_ONE.equals(salaryAccountVo.getSocialPriority())) {
				forecast.setSocialPayMonth(salaryAccountVo.getDeduSocialMonth());
			} else {
				forecast.setSocialPayMonth(SalaryConstants.PRIORITY_ZERO); //没优先级，则限制住
			}
			R<TPaymentVo> tPaymentVoR = HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
					, "/tpaymentinfo/inner/selectTPaymentBySalaryVo", forecast, TPaymentVo.class, SecurityConstants.FROM_IN);
			if (tPaymentVoR != null && tPaymentVoR.getData() != null && tPaymentVoR.getData().getPaymentList() != null) {
				socialEstmateList = tPaymentVoR.getData().getPaymentList();
				// 新增一步：根据同步表里的数据更新获取到的社保缴费库数据
				if (!salaryPaymentMap.isEmpty()) {
					MSalaryPaymentRes res;
					for (TPaymentBySalaryVo vo : socialEstmateList) {
						res = salaryPaymentMap.get(vo.getId());
						if (res != null) {
							vo.setSalarySocialFlag(res.getSalarySocialFlag());
							vo.setSalaryFundFlag(res.getSalaryFundFlag());
						}
					}
				}
				noSalarySocialEstmateList = new ArrayList<>();
				noSalarySocialEstmateList.addAll(socialEstmateList);
			} else {
				// TODO - 预估数据
			}
		}
		if (salaryAccountVo != null && !CommonConstants.ZERO_STRING.equals(salaryAccountVo.getIsDeductFund())) {
			forecast = new TPaymentBySalaryVo();
			forecast.setSettleDomainId(dept.getId());
			if (SalaryConstants.PRIORITY_ZERO.equals(salaryAccountVo.getFundPriority())) {
				forecast.setProvidentCreateMonth(salaryAccountVo.getDeduProvidentMonth());
			} else if (SalaryConstants.PRIORITY_ONE.equals(salaryAccountVo.getFundPriority())) {
				forecast.setProvidentPayMonth(salaryAccountVo.getDeduProvidentMonth());
			} else {
				forecast.setProvidentPayMonth(SalaryConstants.PRIORITY_ZERO); //没优先级，则限制住
			}
			R<TPaymentVo> tPaymentVoR = HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
					, "/tpaymentinfo/inner/selectTPaymentBySalaryVo", forecast, TPaymentVo.class, SecurityConstants.FROM_IN);
			if (tPaymentVoR != null && tPaymentVoR.getData() != null && tPaymentVoR.getData().getPaymentList() != null) {
				fundEstmateList = tPaymentVoR.getData().getPaymentList();
				// 新增一步：根据同步表里的数据更新获取到的社保缴费库数据
				if (!salaryPaymentMap.isEmpty()) {
					MSalaryPaymentRes res;
					for (TPaymentBySalaryVo vo : fundEstmateList) {
						res = salaryPaymentMap.get(vo.getId());
						if (res != null) {
							vo.setSalarySocialFlag(res.getSalarySocialFlag());
							vo.setSalaryFundFlag(res.getSalaryFundFlag());
						}
					}
				}
				noSalaryFundEstmateList = new ArrayList<>();
				noSalaryFundEstmateList.addAll(fundEstmateList);
			} else {
				// TODO - 预估数据
			}
		}
		aList = new ArrayList<>();
		//true：从缴费库等扣社保标识；false：走代扣
		boolean modelPersonSocialFlag;
		boolean modelPersonFundFlag;
		boolean modelUnitSocialFlag;
		boolean modelUnitFundFlag;
		BigDecimal money = new BigDecimal(CommonConstants.ZERO_STRING);  //初始化金额备用

		Set<String> socialList = new HashSet<>();  //社保需要存储的id
		Set<String> fundList = new HashSet<>();  //公积金需要存储的id
		BigDecimal relaySalary;  //工资应发
		BigDecimal relaySalarySum = BigDecimal.ZERO;  //工资应发
		BigDecimal personalDebt;  //个人社保、公积金欠款
		//前次个人待补足
		String preMonth = DateUtil.addMonth(-1);
		List<TSalaryAccountItem> preSupplyList = tSalaryAccountItemService.getAllTSalaryAccountItem(
				dept.getId(), preMonth, SalaryConstants.PRE_CURRENT_SUPPLY_JAVA, null, null, null);
		BigDecimal preSupply;  //前次个人待补足

		//年终奖list-验证年终奖次数
		List<TSalaryAccountItem> annualBonusList;
		BigDecimal annualBonus;
		TSpecialDeducationSum sds;
		String nowYearMonth = DateUtil.getCurrentDateString("yyyyMM");
		BigDecimal sdSum;  // 专项扣除汇总金额
		BigDecimal costReduction;  //减除费用
		String maxYearMonth = null;  //起始计税月（例如：计税月是今年之前的，则取值今年1月，否则=计税月）
		List<TSalaryAccountItem> asList;  //累计扣税
		String checkYearFinalStyle;  //薪资和年终奖扣税方案(0：合并；1：单独)
		List<TSalaryTaxConfig> personTax = tSalaryTaxConfigService.getTaxConfigByPersonList(new TSalaryTaxConfig());
		List<TSalaryTaxConfig> annousTax = tSalaryTaxConfigService.getTaxConfigByAnnualBonusList(new TSalaryTaxConfig());
		//结算主体-薪资配置
		TDepartSettlementInfo deptSet = null;
		R<TDepartSettlementInfo> deptSetR = HttpDaprUtil.invokeMethodPost(archivesProperties.getAppUrl(), archivesProperties.getAppId()
				, "/tsettledomain/inner/getInnerBySettlementId", dept.getId(), TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
		if (deptSetR == null || deptSetR.getData() == null || Common.isEmpty(deptSetR.getData().getId())) {
			return R.failed("请去客户管理模块编辑结算主体 " + dept.getDepartName() + "（" + dept.getDepartNo() + "）的结算配置！");
		} else {
			deptSet = deptSetR.getData();
		}
		int size = savList.size();
		TSalaryAccountItem annousSai;
		// 自有员工人数
		int ownNum = 0;
		// 自有员工应发金额
		BigDecimal ownMoney = BigDecimal.ZERO;

		// 年终奖是否已存在 （true：已存在，不可导入）
		boolean yearEndError = false;
		// 劳务费、稿酬是否含有发薪false：否；true：是
		boolean haveSalaryFlag = false;
		// 是否含有特殊金额false：否；true：是
		boolean haveSpecialFlag = false;
		// 是否重复金额false：否；true：是
		boolean repeatFlag = false;
		// 年终奖错误信息合计：
		StringBuilder yearEndInfo = new StringBuilder();
		List<String> idCardList = new ArrayList<>();
		for (TSalaryAccountVo vo : savList) {
			if (Common.isNotNull(vo.getEmpIdcard())) {
				idCardList.add(vo.getEmpIdcard());
			}
		}
		// 工资查询所需的全部list，组装Map来使用
		Map<String, TSpecialDeducationSum> sdsMap = tSpecialDeducationSumService.getTSpecialDeducationSumMap(nowYearMonth, idCardList);
		Map<String, List<TSalaryAccountItem>> itemMap = tSalaryAccountItemService.getAllItemVoList(idCardList, invoiceTitle);

		// 是否劳务费，true:是
		boolean isLabor = false;
		if ("3".equals(salaryAccountVo.getFormType())) {
			isLabor = true;
		}
		for (int i = CommonConstants.ZERO_INT; i < size; i++) {
			modelPersonSocialFlag = true;
			modelPersonFundFlag = true;
			modelUnitSocialFlag = true;
			modelUnitFundFlag = true;
			relaySalary = BigDecimal.ZERO;
			personalDebt = BigDecimal.ZERO;
			preSupply = BigDecimal.ZERO;
			annualBonus = null;
			sdSum = BigDecimal.ZERO;
			a = new TSalaryAccount();
			costReduction = BigDecimal.ZERO;
			annousSai = null;
			try {
				SalaryAccountUtil.reflectionAttr(savList.get(i), a);
				if (!haveSalaryFlag && a.getHaveSalaryFlag() != null && a.getHaveSalaryFlag() == CommonConstants.ONE_INT) {
					haveSalaryFlag = true;
				}
				if (!haveSpecialFlag && a.getHaveSpecialFlag() != null && a.getHaveSpecialFlag() == CommonConstants.ONE_INT) {
					haveSpecialFlag = true;
				}
				if (!repeatFlag && a.getIsRepeat() != null && a.getIsRepeat() == CommonConstants.ONE_INT) {
					repeatFlag = true;
				}
				checkYearFinalStyle = a.getAnnualBonusType();
				if (Common.isNotNull(a.getTaxMonth())) {
					maxYearMonth = DateUtil.getMaxYearMonth(a.getTaxMonth());
				} else if (!isLabor) {
					return R.failed("获取计税月错误");
				}
				if (noSalarySocialEstmateList != null && noSalarySocialEstmateList.size() > CommonConstants.ZERO_INT) {
					noSalarySocialEstmateListCopy = new ArrayList<>();
					noSalarySocialEstmateListCopy.addAll(noSalarySocialEstmateList);
					for (int j = CommonConstants.ZERO_INT; j < noSalarySocialEstmateListCopy.size(); j++) {
						if (a.getEmpIdcard().equals(noSalarySocialEstmateListCopy.get(j).getEmpIdcard())) {
							noSalarySocialEstmateList.remove(noSalarySocialEstmateListCopy.get(j));
						}
					}
				}
				if (noSalaryFundEstmateList != null && noSalaryFundEstmateList.size() > CommonConstants.ZERO_INT) {
					noSalaryFundEstmateListCopy = new ArrayList<>();
					noSalaryFundEstmateListCopy.addAll(noSalaryFundEstmateList);
					for (int j = CommonConstants.ZERO_INT; j < noSalaryFundEstmateListCopy.size(); j++) {
						if (a.getEmpIdcard().equals(noSalaryFundEstmateListCopy.get(j).getEmpIdcard())) {
							noSalaryFundEstmateList.remove(noSalaryFundEstmateListCopy.get(j));
						}
					}
				}
				if (savList.get(i).getSaiList() != null && !savList.get(i).getSaiList().isEmpty()) {
					saiList = new ArrayList<>();
					annousSai = null;
					for (int j = 0; j < savList.get(i).getSaiList().size(); j++) {
						sai = new TSalaryAccountItem();
						SalaryAccountUtil.reflectionAttr(savList.get(i).getSaiList().get(j), sai);
						if (sai.getIsTax() == null) {
							sai.setIsTax(CommonConstants.ZERO_INT);
						}
						//代扣个人社保
						if (SalaryConstants.WITHHOLIDING_PERSON_SOCIAL.equals(sai.getJavaFiedName())) {
							modelPersonSocialFlag = false;
							personalDebt = personalDebt.add(sai.getSalaryMoney());
							sai.setIsTax(CommonConstants.ONE_INT);
						}
						if (SalaryConstants.WITHHOLIDING_PERSON_FUND.equals(sai.getJavaFiedName())) {
							modelPersonFundFlag = false;
							personalDebt = personalDebt.add(sai.getSalaryMoney());
							sai.setIsTax(CommonConstants.ONE_INT);
						}
						//个人代扣：李靖2020-6-16 18:16:09提的需求：
						if (SalaryConstants.PDEDUCTION_JAVA.equals(sai.getJavaFiedName())) {
							personalDebt = personalDebt.add(sai.getSalaryMoney());
						}
						if (SalaryConstants.WITHHOLIDING_UNIT_SOCIAL.equals(sai.getJavaFiedName())) {
							modelUnitSocialFlag = false;
						}
						if (SalaryConstants.WITHHOLIDING_UNIT_FUND.equals(sai.getJavaFiedName())) {
							modelUnitFundFlag = false;
						}
						saiList.add(sai);
						//工资应发
						if (SalaryConstants.RELAY_SALARY_JAVA.equals(sai.getJavaFiedName())) {
							relaySalary = sai.getSalaryMoney();
							relaySalarySum = relaySalarySum.add(sai.getSalaryMoney());
						}
						//减除费用
						if (SalaryConstants.COST_REDUCTION_JAVA.equals(sai.getJavaFiedName())) {
							costReduction = sai.getSalaryMoney();
						}
						//年终奖
						if (SalaryConstants.ANNUAL_BONUS_JAVA.equals(sai.getJavaFiedName())) {
							annualBonus = sai.getSalaryMoney();
							annousSai = sai;
						}
					}
					if (Common.isEmpty(a.getIsDeductSocial()) || SalaryConstants.IS_DEDUCT_ONE.equals(a.getIsDeductSocial())) {
						a.setIsDeductSocial(SalaryConstants.IS_DEDUCT_ONE);
						//社保公积金金额扣缴：   true : 从库里扣除社保等;false : 走代扣
						if (modelPersonSocialFlag) {
							personalDebt = personalDebt.add(this.saveNewItems(sai, saiList, SalaryConstants.PERSONAL_SOCIAL,
									SalaryConstants.PERSONAL_SOCIAL_JAVA,
									this.getSocialOrFundMoneyForForecast(deptSet, a.getEmpIdcard(), socialEstmateList, money, true, true, socialList, fundList), CommonConstants.ONE_INT));
						}
						if (modelUnitSocialFlag) {
							this.saveNewItems(sai, saiList, SalaryConstants.UNIT_SOCIAL,
									SalaryConstants.UNIT_SOCIAL_JAVA,
									this.getSocialOrFundMoneyForForecast(deptSet, a.getEmpIdcard(), socialEstmateList, money, true, false, socialList, fundList), CommonConstants.ZERO_INT);
						}
					}
					if (Common.isEmpty(a.getIsDeductFund()) || SalaryConstants.IS_DEDUCT_ONE.equals(a.getIsDeductFund())) {
						a.setIsDeductFund(SalaryConstants.IS_DEDUCT_ONE);
						if (modelPersonFundFlag) {
							personalDebt = personalDebt.add(this.saveNewItems(sai, saiList, SalaryConstants.PERSONAL_FUND,
									SalaryConstants.PERSONAL_FUND_JAVA,
									this.getSocialOrFundMoneyForForecast(deptSet, a.getEmpIdcard(), fundEstmateList, money, false, true, socialList, fundList), CommonConstants.ONE_INT));
						}
						if (modelUnitFundFlag) {
							this.saveNewItems(sai, saiList, SalaryConstants.UNIT_FUND,
									SalaryConstants.UNIT_FUND_JAVA,
									this.getSocialOrFundMoneyForForecast(deptSet, a.getEmpIdcard(), fundEstmateList, money, false, false, socialList, fundList), CommonConstants.ZERO_INT);
						}
					}
				}

				// 自有员工以及自有员工应发金额
				if (Common.isNotNull(a.getOwnFlag()) && a.getOwnFlag() == 1) {
					ownNum++;
					ownMoney = ownMoney.add(relaySalary);
				}

				//2019-9-29 17:56:10：与主管确认取消这一项_个人社保卡费
				//account.setPsocialCardMoney(calculationPSocialCardMoney(account))// 个人社保卡费

				//前次个人待补足
				for (TSalaryAccountItem saips : preSupplyList) {
					preSupply = preSupply.add(saips.getSalaryMoney());
				}
				if (preSupply.compareTo(SalaryConstants.B_ZERO) != SalaryConstants.EQUAL) {
					this.saveNewItems(sai, saiList, SalaryConstants.PRE_CURRENT_SUPPLY,
							SalaryConstants.PRE_CURRENT_SUPPLY_JAVA, preSupply, CommonConstants.ZERO_INT);
				}
				//专项信息
				sds = sdsMap.get(a.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + invoiceTitle);
				if (sds != null && Common.isNotNull(sds.getId())) {
					//累计子女教育
					sdSum = sdSum.add(this.saveNewItems(sai, saiList, SalaryConstants.SUM_CHILD_EDU_MONEY,
							SalaryConstants.SUM_CHILD_EDU_MONEY_JAVA, sds.getSumChildEduMoney(), CommonConstants.ZERO_INT));
					//累计住房贷款利息
					sdSum = sdSum.add(this.saveNewItems(sai, saiList, SalaryConstants.SUM_HOUSING_LOAN_MONEY,
							SalaryConstants.SUM_HOUSING_LOAN_MONEY_JAVA, sds.getSumHousingLoanMoney(), CommonConstants.ZERO_INT));
					//累计住房租金
					sdSum = sdSum.add(this.saveNewItems(sai, saiList, SalaryConstants.SUM_HOUSING_RENT_MONEY,
							SalaryConstants.SUM_HOUSING_RENT_MONEY_JAVA, sds.getSumHousingRentMoney(), CommonConstants.ZERO_INT));
					//累计赡养老人
					sdSum = sdSum.add(this.saveNewItems(sai, saiList, SalaryConstants.SUM_SUPPORT_ELDERLY_MONEY,
							SalaryConstants.SUM_SUPPORT_ELDERLY_MONEY_JAVA, sds.getSumSupportElderlyMoney(), CommonConstants.ZERO_INT));
					//累计继续教育
					sdSum = sdSum.add(this.saveNewItems(sai, saiList, SalaryConstants.SUM_CONTINUING_EDUCATION_MONEY,
							SalaryConstants.SUM_CONTINUING_EDUCATION_MONEY_JAVA, sds.getSumContinuingEducationMoney(), CommonConstants.ZERO_INT));
					//累计婴幼儿照护费用
					sdSum = sdSum.add(this.saveNewItems(sai, saiList, SalaryConstants.SUM_BABY_MONEY,
							SalaryConstants.SUM_BABY_MONEY_JAVA, sds.getSumBabyMoney(), CommonConstants.ZERO_INT));
					//累计专项扣除总额
					this.saveNewItems(sai, saiList, SalaryConstants.SPECIAL_DEDU_MONEY_SUM,
							SalaryConstants.SPECIAL_DEDU_MONEY_SUM_JAVA, sdSum, CommonConstants.ZERO_INT);
				}
				//累计扣税list
				// 2022-1-19 18:01:31 根据樊青青、王成，修改为去除姓名校验
				// asList = tSalaryAccountItemService.getEmpAllSalaryAccountItem(a.getEmpIdcard(), maxYearMonth, invoiceTitle)
				if (!isLabor) {
					asList = this.getAsList(itemMap.get(a.getEmpIdcard()), Integer.parseInt(maxYearMonth));
				} else {
					asList = this.getLaborAsList(itemMap.get(a.getEmpIdcard()), a.getSettlementMonth());
				}

				//验证年终奖计算
				// 2021-12-30 17:09:29王成说年终奖按结算月的年来计算
				if (annualBonus != null && annualBonus.compareTo(SalaryConstants.B_ZERO) != SalaryConstants.EQUAL) {
					annualBonusList = tSalaryAccountItemService.getAllTSalaryAccountItem(
							null, null, SalaryConstants.ANNUAL_BONUS_JAVA,
							a.getSettlementMonth().substring(0, 4), a.getEmpIdcard(), null);
					if (annualBonusList != null && annualBonusList.size() > CommonConstants.ZERO_INT) {
						if (!yearEndError) {
							yearEndError = true;
							yearEndInfo.append("以下人员，年终奖重复发放（一个结算年只能发一次）： ||");
						}
						yearEndInfo.append("第" + (i + 2) + "行：【" + a.getEmpIdcard() + "】 ||");
					} else {
						//年终奖优化方案 2：自动计算
						if (CommonConstants.TWO_STRING.equals(checkYearFinalStyle)) {
							checkYearFinalStyle = checkYearFinalStyle(isActual, saiList, checkYearFinalStyle, asList, sdSum
									, costReduction, personTax, sai, saiList, relaySalary, annualBonus, annousTax);
						}
						//年终奖单独扣税
						if (CommonConstants.ONE_STRING.equals(checkYearFinalStyle)) {
							if (!isActual) {
								personalDebt = personalDebt.add(this.saveNewItems(sai, saiList, SalaryConstants.ANNUAL_BONUS_TAX,
										SalaryConstants.ANNUAL_BONUS_TAX_JAVA, calculation2FinalSalary(annualBonus, annousTax), CommonConstants.ZERO_INT));
							} else {
								this.saveNewItems(sai, saiList, SalaryConstants.ANNUAL_BONUS_TAX,
										SalaryConstants.ANNUAL_BONUS_TAX_JAVA, calculation2FinalSalary(annualBonus, annousTax), CommonConstants.ZERO_INT);
							}
							if (annousSai != null) {
								annousSai.setIsTax(CommonConstants.ONE_INT);
							}
						}
					}
				}
				// 薪资扣税 1：扣税
				//if (Common.isNotNull(a.getSalaryTaxFlag()) && CommonConstants.ONE.equals(a.getSalaryTaxFlag())) {
				// 应发顺推个税
				if (!isActual) {
					personalDebt = personalDebt.add(this.saveNewItems(sai, saiList, SalaryConstants.SALARY_TAX,
							SalaryConstants.SALARY_TAX_JAVA,
							calculation2PersonSalary(isActual, saiList, checkYearFinalStyle, asList, sdSum
									, costReduction, personTax, sai, saiList, relaySalary), CommonConstants.ZERO_INT));
				} else {
					// 实发倒推个税应发
					if (!isLabor) {
						this.saveNewItems(sai, saiList, SalaryConstants.SALARY_TAX,
								SalaryConstants.SALARY_TAX_JAVA,
								calculation2PersonSalary(isActual, saiList, checkYearFinalStyle, asList, sdSum
										, costReduction, personTax, sai, saiList, relaySalary), CommonConstants.ZERO_INT);
					} else {
						// 实发劳务费，按月累计扣税 2022-3-2 17:32:40 樊青青提的需求
						this.saveNewItems(sai, saiList, SalaryConstants.SALARY_TAX,
								SalaryConstants.SALARY_TAX_JAVA,
								calculation2Labor(saiList, asList
										, saiList), CommonConstants.ZERO_INT);
					}

				}
				//}

				if (!isActual) {  //导入应发，顺推实发
					// 个人实发合计
					this.saveNewItems(sai, saiList, SalaryConstants.ACTUAL_SALARY_SUM,
							SalaryConstants.ACTUAL_SALARY_SUM_JAVA,
							calculation(relaySalary, saiList), CommonConstants.ZERO_INT);
				}
				//计算个人社保、公积金欠款————工资不够扣缴社保的
				if (relaySalary.compareTo(personalDebt) == SalaryConstants.LESS_THAN) {
					this.saveNewItems(sai, saiList, SalaryConstants.PERSONAL_DEBT,
							SalaryConstants.PERSONAL_DEBT_JAVA, relaySalary.subtract(personalDebt), CommonConstants.ZERO_INT);
				}
				a.setSaiList(saiList);
				aList.add(a);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (yearEndError) {
			return new R<>(CommonConstants.TWO_INT, "年终奖重复", yearEndInfo.toString());
		}
		salary.setOwnNums(ownNum);
		salary.setOwnMoney(ownMoney);
		TSalaryDetailVo salaryDetailVo = new TSalaryDetailVo();
		salaryDetailVo.setSalaryAccountList(aList);
		salary.setSettlementAmount(relaySalarySum);
		salary.setHaveSalaryFlag(CommonConstants.ZERO_INT);
		salary.setHaveSpecialFlag(CommonConstants.ZERO_INT);
		salary.setIsRepeat(CommonConstants.ZERO_INT);
		if (haveSalaryFlag || haveSpecialFlag || ownNum>0 || repeatFlag) {
			salary.setStatus(SalaryConstants.AUDIT_STATUS[0]);
			if (haveSalaryFlag) {
				salary.setHaveSalaryFlag(CommonConstants.ONE_INT);
			}
			if (haveSpecialFlag) {
				salary.setHaveSpecialFlag(CommonConstants.ONE_INT);
			}
			if (repeatFlag) {
				salary.setIsRepeat(CommonConstants.ONE_INT);
			}
		} else {
			salary.setStatus(SalaryConstants.AUDIT_STATUS[2]);
		}
		//保存工资表
		tSalaryStandardService.save(salary);

		// 获取上一个工资条顺序，复制：
		tSalaryStandardSetService.copyLastSetByDeptId(salary.getId(), dept.getId(), String.valueOf(user.getId()));

		// 保存后，修改结算预警统计中的结算状态
		List<String> deptIdList = new ArrayList<>();
		deptIdList.add(dept.getId());

		salaryDetailVo.setSalary(salary);
		MSalaryEstimate se;

		// 新增一步：增加同步表
		MSalaryPaymentRes res;
		Map<String, MSalaryPaymentRes> saveResMap = new HashMap<>();
		if (!socialList.isEmpty()) {
			for (String estId : socialList) {
				se = new MSalaryEstimate();
				se.setSalaryId(salary.getId());
				se.setEstimateId(estId);
				se.setIsSocial(SalaryConstants.IS_SOCIAL_ZERO);
				se.setIsNoSalary(SalaryConstants.NOT_IS_NO_SALARY_ZERO);
				mSalaryEstimateService.save(se);
				res = salaryPaymentMap.get(estId);
				if (res == null) {
					res = new MSalaryPaymentRes();
					res.setId(estId);
					res.setDeptId(dept.getId());
				}
				res.setSalarySocialFlag(CommonConstants.ONE_STRING);
				saveResMap.put(estId, res);
			}
		}
		if (!fundList.isEmpty()) {
			for (String estId : fundList) {
				se = new MSalaryEstimate();
				se.setSalaryId(salary.getId());
				se.setEstimateId(estId);
				se.setIsSocial(SalaryConstants.IS_FUND_ONE);
				se.setIsNoSalary(SalaryConstants.NOT_IS_NO_SALARY_ZERO);
				mSalaryEstimateService.save(se);
				res = saveResMap.get(estId);
				if (res == null) {
					res = salaryPaymentMap.get(estId);
				}
				if (res == null) {
					res = new MSalaryPaymentRes();
					res.setId(estId);
					res.setDeptId(dept.getId());
				}
				res.setSalaryFundFlag(CommonConstants.ONE_STRING);
				saveResMap.put(estId, res);
			}
		}
		// 开始更新res
		if (!saveResMap.isEmpty()) {
			Iterator<MSalaryPaymentRes> iter = saveResMap.values().iterator();
			while (iter.hasNext()) {
				res = iter.next();
				salaryPaymentResService.saveOrUpdate(res);
			}
		}
		TPauseSalary ps;
		for (TSalaryAccount account : aList) {
			saiList = account.getSaiList();
			account.setSaiList(null);
			account.setSalaryFormId(salary.getId());
			tSalaryAccountService.save(account);
			money = SalaryConstants.B_ZERO;
			for (TSalaryAccountItem item : saiList) {
				if (SalaryConstants.ACTUAL_SALARY_SUM_JAVA.equals(item.getJavaFiedName())) {
					money = item.getSalaryMoney();
				}
				item.setSalaryAccountId(account.getId());
				tSalaryAccountItemService.save(item);
			}
			//暂停发
			if (SalaryConstants.SALARY_GIVE_TIME_VALUE.equals(account.getSalaryGiveTime())) {
				ps = new TPauseSalary();
				ps.setBalance(money);
				ps.setName(account.getEmpName());
				ps.setIdCard(account.getEmpIdcard());
				ps.setBankName(account.getBankName());
				ps.setBankNo(account.getBankNo());
				ps.setCreateTime(nowTime);
				ps.setCreateBy(user.getId());
				ps.setSettleDepartId(dept.getId());
				ps.setSettleDepartNo(dept.getDepartNo());
				ps.setSettleDepartName(dept.getDepartName());
				ps.setSalaryFormId(salary.getId());
				ps.setSalaryAccountId(account.getId());
				ps.setSalaryDate(account.getSalaryMonth());
				ps.setSettleDate(account.getSettlementMonth());
				ps.setType(SalaryConstants.PAUSE_TYPE[0]);
				tPauseSalaryService.save(ps);
			}
		}
		return R.ok(salaryDetailVo);
	}

	/**
	 * @param itemList
	 * @param maxYearMonth
	 * @Description: 循环获取符合条件的报账
	 * @Author: hgw
	 * @Date: 2022/1/27 17:32
	 * @return: java.util.List<com.yifu.cloud.v1.hrms.api.entity.TSalaryAccountItem>
	 **/
	private List<TSalaryAccountItem> getAsList(List<TSalaryAccountItem> itemList, int maxYearMonth) {
		List<TSalaryAccountItem> backList = new ArrayList<>();
		if (itemList != null && !itemList.isEmpty()) {
			for (TSalaryAccountItem item : itemList) {
				if (!"3".equals(item.getSalaryType()) && Integer.parseInt(item.getSettlementMonth()) >= maxYearMonth) {
					backList.add(item);
				}
			}
		}
		return backList;
	}

	/**
	 * @param itemList
	 * @param settleMonth
	 * @Description: 循环获取符合条件的报账
	 * @Author: hgw
	 * @Date: 2022/1/27 17:32
	 * @return: java.util.List<com.yifu.cloud.v1.hrms.api.entity.TSalaryAccountItem>
	 **/
	private List<TSalaryAccountItem> getLaborAsList(List<TSalaryAccountItem> itemList, String settleMonth) {
		List<TSalaryAccountItem> backList = new ArrayList<>();
		if (itemList != null && !itemList.isEmpty()) {
			for (TSalaryAccountItem item : itemList) {
				if ("3".equals(item.getSalaryType()) && settleMonth.equals(item.getSettlementMonth())) {
					backList.add(item);
				}
			}
		}
		return backList;
	}

	/**
	 * @param realSalary 应发工资
	 * @param saiList    报账详情表list
	 * @Description: 计算个人实发合计
	 * @Author: hgw
	 * @Date: 2019/10/9 15:14
	 * @return: java.math.BigDecimal
	 **/
	private static BigDecimal calculation(BigDecimal realSalary, List<TSalaryAccountItem> saiList) {
		// 实际发放工资 = 应发工资合计-
		// 个人社保扣缴 -个人公积金扣缴-薪资扣税-年终奖扣税-代扣风险抵押金
		// -个人其他费用(就是工资表中的其他费用1+其他费用2+其他费用3) -前次个人待补足 -单位补足扣返
		// -个人代扣-免个税个人代扣 - 企业（职业）年金 - 代扣个人社保 - 代扣个人公积金
		// -个人社保卡费(暂无)
		BigDecimal sum = SalaryConstants.B_ZERO;
		for (TSalaryAccountItem item : saiList) {
			if (SalaryConstants.PERSONAL_SOCIAL_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.PERSONAL_FUND_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.SALARY_TAX_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.ANNUAL_BONUS_TAX_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.RISK_MORTGAGE_MONEY_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.OTHER_MONEY_ONE_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.OTHER_MONEY_TWO_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.OTHER_MONEY_THREE_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.PRE_CURRENT_SUPPLY_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.UNIT_SUPPLY_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.PDEDUCTION_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.EXEMPTION_PERSION_TAX_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.ENTERPRISE_ANNUITY_JAVA.equals(item.getJavaFiedName())
					|| SalaryConstants.WITHHOLIDING_PERSON_SOCIAL.equals(item.getJavaFiedName())
					|| SalaryConstants.WITHHOLIDING_PERSON_FUND.equals(item.getJavaFiedName())) {
				sum = sum.add(item.getSalaryMoney()).setScale(SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP);
			}
		}
		sum = realSalary.subtract(sum).setScale(SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP);
		if (sum.compareTo(SalaryConstants.B_ZERO) == SalaryConstants.LESS_THAN) {
			return SalaryConstants.B_ZERO;
		} else {
			return sum;
		}
	}

	/**
	 * @param yearFinal 年终奖
	 * @param annousTax 税率
	 * @Description: 计算年终奖个税
	 * @Author: hgw
	 * @Date: 2019/10/8 15:11
	 * @return: java.math.BigDecimal
	 **/
	private static BigDecimal calculation2FinalSalary(BigDecimal yearFinal, List<TSalaryTaxConfig> annousTax) {
		//年终奖
		if (yearFinal != null && yearFinal.compareTo(SalaryConstants.B_ZERO) == SalaryConstants.MORE_THAN
				&& annousTax != null && annousTax.size() > CommonConstants.ZERO_INT) {
			BigDecimal month = yearFinal.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) {
					return yearFinal.multiply(new BigDecimal(sub.getWithholdingRate()).divide(
									SalaryConstants.B_ONEHUNDRED, SalaryConstants.TAX_FEE_PLACES, BigDecimal.ROUND_HALF_UP))
							.subtract(sub.getQuickDeducation());
				}
			}
		}
		return SalaryConstants.B_ZERO;
	}

	/**
	 * @param sai      报账明细
	 * @param saiList  报账明细list
	 * @param cnName   中文名-表头名
	 * @param javaName 属性
	 * @param money    金额
	 * @param isTax    是否进行计算扣税：1：计算；0：不计算
	 * @Description: 保存报账明细
	 * @Author: hgw
	 * @Date: 2019/9/30 17:02
	 * @return: java.math.BigDecimal - 报账明细金额
	 **/
	private BigDecimal saveNewItems(TSalaryAccountItem sai, List<TSalaryAccountItem> saiList,
									String cnName, String javaName, BigDecimal money, Integer isTax) {
		sai = new TSalaryAccountItem();
		sai.setCnName(cnName);
		sai.setJavaFiedName(javaName);
		if (money == null) {
			money = new BigDecimal("0");
		}
		sai.setSalaryMoney(money);
		if (isTax != null) {
			sai.setIsTax(isTax);
		} else {
			sai.setIsTax(CommonConstants.ZERO_INT);
		}
		saiList.add(sai);
		return money;
	}

	/**
	 * @param estmateList 预估库数据列表
	 * @param idNumber    身份证
	 * @param money       金额
	 * @param isSocial    true:社保 false:公积金
	 * @param isPerson    true:个人 false:单位
	 * @param socialList  预估库id,社保list
	 * @param fundList    预估库id,公积金list
	 * @Description: 获取预估库-金额
	 * @Author: hgw
	 * @Date: 2019/9/26 15:38
	 * @return: java.math.BigDecimal
	 **/
	public BigDecimal getSocialOrFundMoneyForForecast(TDepartSettlementInfo deptSet, String idNumber
			, List<TPaymentBySalaryVo> estmateList, BigDecimal money, boolean isSocial, boolean isPerson
			, Set<String> socialList, Set<String> fundList) {
		money = SalaryConstants.B_ZERO;
		BigDecimal sub = SalaryConstants.B_ZERO;
		if (isSocial) {
			if (deptSet.getUnitSeriousIllnessProp() != null
					&& deptSet.getUnitSeriousIllnessProp().compareTo(SalaryConstants.B_ONEHUNDRED) == SalaryConstants.LESS_THAN) {
				sub = (new BigDecimal("100").subtract(deptSet.getUnitSeriousIllnessProp()))
						.divide(SalaryConstants.B_ONEHUNDRED, SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP);
			}
			//sub = sub.divide(SalaryConstants.B_ONEHUNDRED, SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP)
		}
		if (estmateList != null && estmateList.size() > CommonConstants.ZERO_INT) {
			money = money.setScale(SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP);
			for (TPaymentBySalaryVo m : estmateList) {
				if (Common.isNotNull(idNumber) && idNumber.equals(m.getEmpIdcard())) {
					//社保
					if (isSocial && (!Common.isNotNull(m.getSalarySocialFlag()) || CommonConstants.ZERO_STRING.equals(m.getSalarySocialFlag()))
							&& (m.getPersonalSocialSum() != null || m.getUnitSocialSum() != null)) {
						if (isPerson && m.getPersonalSocialSum() != null) {
							money = money.add(m.getPersonalSocialSum());
							if (sub.compareTo(SalaryConstants.B_ZERO) != SalaryConstants.EQUAL
									&& m.getUnitBitmailmentFee() != null) {
								money = money.add(m.getUnitBitmailmentFee().multiply(sub));
							}
						}
						if (!isPerson && m.getUnitSocialSum() != null) {
							money = money.add(m.getUnitSocialSum());
							if (sub.compareTo(SalaryConstants.B_ZERO) != SalaryConstants.EQUAL
									&& m.getUnitBitmailmentFee() != null) {
								money = money.subtract(m.getUnitBitmailmentFee().multiply(sub));
							}
						}
						socialList.add(m.getId());
					}
					//公积金
					if (!isSocial && (!Common.isNotNull(m.getSalaryFundFlag()) || CommonConstants.ZERO_STRING.equals(m.getSalaryFundFlag()))
							&& (m.getPersonalFundSum() != null || m.getUnitFundSum() != null)) {
						if (isPerson && m.getPersonalFundSum() != null) {
							money = money.add(m.getPersonalFundSum());
						}
						if (!isPerson && m.getUnitFundSum() != null) {
							money = money.add(m.getUnitFundSum());
						}
						fundList.add(m.getId());
					}
				}
			}
		}
		return money;
	}

	/**
	 * @param noSalaryEstmateList 无工资人员-预估库数据列表
	 * @param money               金额
	 * @param isSocial            true:社保 false:公积金
	 * @param isPerson            true:个人 false:单位
	 * @param noSalarySocialList  预估库id,社保list
	 * @param noSalaryFundList    预估库id,公积金list
	 * @Description: 无工资人员社保、公积金信息
	 * @Author: hgw
	 * @Date: 2019/9/26 16:39
	 * @return: java.math.BigDecimal
	 **/
	public BigDecimal getNoSalarySocialOrFundMoneyForForecast(List<TPaymentBySalaryVo> noSalaryEstmateList
			, BigDecimal money, boolean isSocial, boolean isPerson, Set<String> noSalarySocialList, Set<String> noSalaryFundList) {
		money = SalaryConstants.B_ZERO;
		if (noSalaryEstmateList != null && noSalaryEstmateList.size() > CommonConstants.ZERO_INT) {
			money = money.setScale(2, BigDecimal.ROUND_HALF_UP);
			for (TPaymentBySalaryVo m : noSalaryEstmateList) {
				//社保
				if (isSocial && (!Common.isNotNull(m.getSalarySocialFlag()) || CommonConstants.ZERO_STRING.equals(m.getSalarySocialFlag()))) {
					if (isPerson && m.getPersonalSocialSum() != null) {
						money = money.add(m.getPersonalSocialSum());
					}
					if (!isPerson && m.getUnitSocialSum() != null) {
						money = money.add(m.getUnitSocialSum());
					}
					noSalarySocialList.add(m.getId());
				}
				//公积金
				if (!isSocial && (!Common.isNotNull(m.getSalaryFundFlag()) || CommonConstants.ZERO_STRING.equals(m.getSalaryFundFlag()))) {
					if (isPerson && m.getPersonalFundSum() != null) {
						money = money.add(m.getPersonalFundSum());
					}
					if (!isPerson && m.getUnitFundSum() != null) {
						money = money.add(m.getUnitFundSum());
					}
					noSalaryFundList.add(m.getId());
				}
			}
		}
		return money;
	}

	/**
	 * @param isActual            false：有应发顺推；true：有实发，倒推应发
	 * @param itemList            本次报账金额
	 * @param checkYearFinalStyle //薪资和年终奖扣税方案(0：合并(默认)；1：单独)
	 * @param itemHistoryList     历史报账金额
	 * @param specialDeductionSum 专项信息
	 * @param costReduction       减除费用
	 * @param subs                薪资扣税阶梯表list
	 * @Description: 计算薪资扣税-个税
	 * @Author: hgw
	 * @Date: 2019/10/8 18:34
	 * @return: java.math.BigDecimal
	 **/
	private static BigDecimal calculation2PersonSalary(boolean isActual, List<TSalaryAccountItem> itemList
			, String checkYearFinalStyle, List<TSalaryAccountItem> itemHistoryList, BigDecimal specialDeductionSum
			, BigDecimal costReduction, List<TSalaryTaxConfig> subs, TSalaryAccountItem sai
			, List<TSalaryAccountItem> saiList, BigDecimal relaySalary) {
		//本次纳税额
		BigDecimal res = SalaryConstants.B_ZERO;
		BigDecimal annualBonus = SalaryConstants.B_ZERO;
		BigDecimal sumTax = SalaryConstants.B_ZERO;

		BigDecimal realDeduSalary = SalaryConstants.B_ZERO;
		BigDecimal addRelaySalary = SalaryConstants.B_ZERO;  // 实发倒推应发后需要加上其余金额，成为应发。
		BigDecimal actualSalarySumNow = SalaryConstants.B_ZERO;  // 本次实发。
		//本次
		for (TSalaryAccountItem item : itemList) {
			if (SalaryConstants.ANNUAL_BONUS_JAVA.equals(item.getJavaFiedName())) {
				annualBonus = item.getSalaryMoney();
			}
			if (SalaryConstants.RELAY_SALARY_JAVA.equals(item.getJavaFiedName())) {
				res = res.add(item.getSalaryMoney());
			}
			if (SalaryConstants.ACTUAL_SALARY_SUM_JAVA.equals(item.getJavaFiedName())) {
				realDeduSalary = realDeduSalary.add(item.getSalaryMoney());
				actualSalarySumNow = actualSalarySumNow.add(item.getSalaryMoney());
			}
               /*if (SalaryConstants.ANNUAL_BONUS_TAX_JAVA.equals(item.getJavaFiedName())) {
                    sumTax = sumTax.add(item.getSalaryMoney());
               }*/
			if (CommonConstants.ONE_INT == item.getIsTax()) {
				res = res.subtract(item.getSalaryMoney());
				realDeduSalary = realDeduSalary.subtract(item.getSalaryMoney());
				addRelaySalary = addRelaySalary.add(item.getSalaryMoney());
			}
		}
		BigDecimal realSalaryHistory = SalaryConstants.B_ZERO;
		//历史累计
		for (TSalaryAccountItem item : itemHistoryList) {
			if (SalaryConstants.ANNUAL_BONUS_JAVA.equals(item.getJavaFiedName())) {
				annualBonus = annualBonus.add(item.getSalaryMoney());
			}
			if (SalaryConstants.SALARY_TAX_JAVA.equals(item.getJavaFiedName())) {
				sumTax = sumTax.add(item.getSalaryMoney());
			}
               /*if (SalaryConstants.ANNUAL_BONUS_TAX_JAVA.equals(item.getJavaFiedName())) {
                    sumTax = sumTax.add(item.getSalaryMoney());
               }*/
			if (SalaryConstants.RELAY_SALARY_JAVA.equals(item.getJavaFiedName())) {
				res = res.add(item.getSalaryMoney());
				realSalaryHistory = realSalaryHistory.add(item.getSalaryMoney());
			}
			if (SalaryConstants.ACTUAL_SALARY_SUM_JAVA.equals(item.getJavaFiedName())) {
				realDeduSalary = realDeduSalary.add(item.getSalaryMoney());
			}
			if (CommonConstants.ONE_INT == item.getIsTax()) {
				res = res.subtract(item.getSalaryMoney());
				addRelaySalary = addRelaySalary.add(item.getSalaryMoney());
			}
		}
		if (specialDeductionSum != null) {
			res = res.subtract(specialDeductionSum);
			realDeduSalary = realDeduSalary.subtract(specialDeductionSum);
			//addRelaySalary = addRelaySalary.add(specialDeductionSum);
		}
		if (costReduction != null) {
			res = res.subtract(costReduction);
			realDeduSalary = realDeduSalary.subtract(costReduction);
			addRelaySalary = addRelaySalary.add(costReduction);
		}
		//不合并年终奖扣税
          /*if (CommonConstants.ONE.equals(checkYearFinalStyle)) {
               res = res.subtract(annualBonus);
               addRelaySalary = addRelaySalary.add(annualBonus);
          }*/
		if (!isActual) {
			for (TSalaryTaxConfig sub : subs) {
				if (res.compareTo(sub.getMinIncome()) == SalaryConstants.MORE_THAN
						&& res.compareTo(sub.getMaxIncome()) != SalaryConstants.MORE_THAN) {
					//res = realDeduSalary * ((double) ((sub.getTaxRate() * 1.0) / 100)) - sumTax - sub.getQuick();
					res = res.multiply(new BigDecimal(sub.getWithholdingRate()).divide(
									SalaryConstants.B_ONEHUNDRED, SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP))
							.subtract(sumTax).subtract(sub.getQuickDeducation());// 应纳税额
					break;
				}
			}
		} else {
			BigDecimal testArea;  // 应发-起征点，判断计算金额范围；
			//倒推公式（原先）：
			//((实发合计-减除费用)/ (1-税率) - (速算/(1-税率)) + 减除费用)
			//        -
			//        (历史应发)
			//        =
			//        本次应发
			for (TSalaryTaxConfig sub : subs) {
				//res = realDeduSalary / (1- (double) ((sub.getTaxRate() * 1.0) / 100))
				// - (sub.getQuick()/ (1- (double) ((sub.getTaxRate() * 1.0) / 100)))
				// + addRelaySalary;
				res = realDeduSalary.divide(new BigDecimal("1").subtract(new BigDecimal(sub.getWithholdingRate()).divide(
								SalaryConstants.B_ONEHUNDRED, SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP)), SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP)
						.subtract(sub.getQuickDeducation().divide(new BigDecimal("1").subtract(new BigDecimal(sub.getWithholdingRate()).divide(
								SalaryConstants.B_ONEHUNDRED, SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP)), SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP))
						.add(addRelaySalary);
				testArea = res.subtract(costReduction);
				if (testArea.compareTo(SalaryConstants.B_ZERO) == SalaryConstants.LESS_THAN) {
					testArea = SalaryConstants.B_ZERO;
				}
				if (testArea.compareTo(sub.getMinIncome()) == SalaryConstants.MORE_THAN
						&& testArea.compareTo(sub.getMaxIncome()) != SalaryConstants.MORE_THAN) {
					//res = res - realSalary - tf.getActualSalarySum(); //应发-历史应发=本次应发；本次应发-本次实发=税
					relaySalary = res.subtract(realSalaryHistory);
					res = relaySalary.subtract(actualSalarySumNow);
					// 本次个人应发合计
					sai = new TSalaryAccountItem();
					sai.setCnName(SalaryConstants.RELAY_SALARY);
					sai.setJavaFiedName(SalaryConstants.RELAY_SALARY_JAVA);
					sai.setIsTax(CommonConstants.ZERO_INT);
					if (res.compareTo(SalaryConstants.B_ZERO) != SalaryConstants.MORE_THAN) {
						sai.setSalaryMoney(actualSalarySumNow);
					} else {
						sai.setSalaryMoney(relaySalary);
					}
					saiList.add(sai);
					break;
				}
			}
		}
		if (res.compareTo(SalaryConstants.B_ZERO) == SalaryConstants.LESS_THAN) {
			return SalaryConstants.B_ZERO;
		}
		return res.setScale(SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP);
	}


	/**
	 * @param itemList
	 * @param itemHistoryList
	 * @param saiList
	 * @Description: 计算劳务费个税、应发
	 * @Author: hgw
	 * @Date: 2022/3/3 11:30
	 * @return: java.math.BigDecimal
	 **/
	private static BigDecimal calculation2Labor(List<TSalaryAccountItem> itemList
			, List<TSalaryAccountItem> itemHistoryList, List<TSalaryAccountItem> saiList) {
		// B7 = 当月实发合计
		// 税=ROUND(IF(B7<=800,0,IF(B7<=3360,(B7-800)/4,IF(B7<=21000,0.16*B7/0.84,IF(B7<=49500,(0.24*B7-2000)/0.76,(0.32*B7-7000)/0.68)))),2)
		// 本次实发
		BigDecimal actualSalarySumNow = BigDecimal.ZERO;
		// 当月实发合计
		BigDecimal actualSalarySum = BigDecimal.ZERO;
		// 历史个税合计
		BigDecimal sumTax = BigDecimal.ZERO;
		// 本次实发
		for (TSalaryAccountItem item : itemList) {
			if (SalaryConstants.ACTUAL_SALARY_SUM_JAVA.equals(item.getJavaFiedName())) {
				actualSalarySum = actualSalarySum.add(item.getSalaryMoney());
				actualSalarySumNow = actualSalarySumNow.add(item.getSalaryMoney());
			}
		}
		// 历史实发、个税
		for (TSalaryAccountItem item : itemHistoryList) {
			if (SalaryConstants.SALARY_TAX_JAVA.equals(item.getJavaFiedName())) {
				sumTax = sumTax.add(item.getSalaryMoney());
			}
			if (SalaryConstants.ACTUAL_SALARY_SUM_JAVA.equals(item.getJavaFiedName())) {
				actualSalarySum = actualSalarySum.add(item.getSalaryMoney());
			}
		}
		BigDecimal nowTax;
		// 2022-3-3 11:24:20 运营中心郭华照提供的公式：
		// ROUND(IF(B7<=800,0,IF(B7<=3360,(B7-800)/4,IF(B7<=21000,0.16*B7/0.84,IF(B7<=49500,(0.24*B7-2000)/0.76,(0.32*B7-7000)/0.68)))),2)
		if (actualSalarySum.compareTo(new BigDecimal("800")) <= 0) {
			nowTax = BigDecimal.ZERO;
		} else if (actualSalarySum.compareTo(new BigDecimal("3360")) <= 0) {
			// (B7-800)/4
			nowTax = BigDecimalUtils.safeDivide(BigDecimalUtils.safeSubtract(actualSalarySum, new BigDecimal("800"))
					, new BigDecimal("4"));
		} else if (actualSalarySum.compareTo(new BigDecimal("21000")) <= 0) {
			// 0.16*B7/0.84
			nowTax = BigDecimalUtils.safeDivide(BigDecimalUtils.safeMultiply(actualSalarySum, new BigDecimal("0.16"))
					, new BigDecimal("0.84"));
		} else if (actualSalarySum.compareTo(new BigDecimal("49500")) <= 0) {
			// (0.24*B7-2000)/0.76
			nowTax = BigDecimalUtils.safeDivide(BigDecimalUtils.safeSubtract(
							BigDecimalUtils.safeMultiply(actualSalarySum, new BigDecimal("0.24")), new BigDecimal("2000"))
					, new BigDecimal("0.76"));
		} else {
			nowTax = BigDecimalUtils.safeDivide(BigDecimalUtils.safeSubtract(
							BigDecimalUtils.safeMultiply(actualSalarySum, new BigDecimal("0.32")), new BigDecimal("7000"))
					, new BigDecimal("0.68"));
		}
		nowTax = nowTax.setScale(SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP);
		if (sumTax.compareTo(BigDecimal.ZERO) != 0) {
			nowTax = BigDecimalUtils.safeSubtract(nowTax, sumTax).setScale(SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP);
		}

		BigDecimal relaySalary = BigDecimalUtils.safeAdd(actualSalarySumNow, nowTax).setScale(SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP);
		// 本次个人应发合计
		TSalaryAccountItem sai = new TSalaryAccountItem();
		sai.setCnName(SalaryConstants.RELAY_SALARY);
		sai.setJavaFiedName(SalaryConstants.RELAY_SALARY_JAVA);
		sai.setIsTax(CommonConstants.ZERO_INT);
		sai.setSalaryMoney(relaySalary);
		saiList.add(sai);
		return nowTax;
	}

	/**
	 * 比较与薪资合并扣税和单独扣税的结果
	 *
	 * @return 1: 单独  0: 合并
	 * @createDate 2020-4-22 18:59:02
	 * @author hgw
	 */
	public static String checkYearFinalStyle(boolean isActual, List<TSalaryAccountItem> itemList
			, String checkYearFinalStyle, List<TSalaryAccountItem> asList, BigDecimal sdSum
			, BigDecimal costReduction, List<TSalaryTaxConfig> personTax, TSalaryAccountItem sai
			, List<TSalaryAccountItem> saiList, BigDecimal relaySalary, BigDecimal annualBonus, List<TSalaryTaxConfig> annousTax) {
		BigDecimal finalSalaryWithSalary = calculation2PersonSalary(isActual, saiList, checkYearFinalStyle, asList, sdSum
				, costReduction, personTax, sai, saiList, relaySalary);
		BigDecimal finalSalaryNoSalary = calculation2FinalSalary(annualBonus, annousTax);
		if (finalSalaryWithSalary.compareTo(finalSalaryNoSalary) == SalaryConstants.MORE_THAN) {
			return "1";
		}
		return "0";
	}

	/**
	 * @param salaryFormId 工资表id
	 * @Description: 获取结算单
	 * @Author: hgw
	 * @Date: 2019/9/9 17:49
	 * @return: com.yifu.cloud.v1.common.core.util.R
	 **/
	@Override
	public R<TSalaryDetailVo> getBill(String salaryFormId) {
		//工资主表
		TSalaryStandard salary = tSalaryStandardService.getById(salaryFormId);
		TSalaryDetailVo salaryDetailVo = new TSalaryDetailVo();
		if (salary != null) {
			List<TSalaryAtta> attaList = null;
			if (salary.getType() == null || salary.getType() != CommonConstants.ONE_INT) {
				//报账表
				TSalaryAccount salaryAccount = new TSalaryAccount();
				salaryAccount.setSalaryFormId(salaryFormId);
				QueryWrapper<TSalaryAccount> queryWrapperSa = new QueryWrapper<>();
				queryWrapperSa.setEntity(salaryAccount);
				List<TSalaryAccount> salaryAccountList = tSalaryAccountService.list(queryWrapperSa);
				//报账表明细
				if (salaryAccountList != null && salaryAccountList.size() > CommonConstants.ZERO_INT) {
					TSalaryAccountItem item;
					QueryWrapper<TSalaryAccountItem> queryWrapperAi;
					List<TSalaryAccountItem> itemList;
					for (TSalaryAccount a : salaryAccountList) {
						item = new TSalaryAccountItem();
						item.setSalaryAccountId(a.getId());
						queryWrapperAi = new QueryWrapper<>();
						queryWrapperAi.setEntity(item);
						itemList = tSalaryAccountItemService.list(queryWrapperAi);
						a.setSaiList(itemList);
					}
				}
				salaryDetailVo.setSalaryAccountList(salaryAccountList);
				attaList = tSalaryAttaService.getAttaListHaveSrc(salary.getId(), 230);
			}
			salaryDetailVo.setAttaList(attaList);
			salaryDetailVo.setAuditLogList(auditLogService.list(Wrappers.<TApprovalRecord>query().lambda().eq(TApprovalRecord::getSalaryId, salary.getId())));
		}
		//结算单
		salaryDetailVo.setSalary(salary);
		return new R<>(salaryDetailVo);
	}

}
