/*
 *    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.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.*;
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.ekp.util.EkpFundUtil;
import com.yifu.cloud.plus.v1.yifu.ekp.util.EkpSalaryUtil;
import com.yifu.cloud.plus.v1.yifu.ekp.util.EkpSocialUtil;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpPushFundParam;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpPushSocialParam;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpSalaryParam;
import com.yifu.cloud.plus.v1.yifu.ekp.vo.EkpSalaryParamVo;
import com.yifu.cloud.plus.v1.yifu.salary.entity.MSalaryEstimate;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TApprovalRecord;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccount;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryStandard;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSalaryStandardMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.MSalaryEstimateService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TApprovalRecordService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryAccountService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryStandardService;
import com.yifu.cloud.plus.v1.yifu.salary.util.SalaryConstants;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryStandardExportVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryStandardSearchVo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TIncomeDetail;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSendEkpError;
import com.yifu.cloud.plus.v1.yifu.social.vo.TIncomeDetailReturnVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.*;

/**
 * 标准薪酬工资表
 *
 * @author hgw
 * @date 2022-08-05 11:40:14
 */
@Log4j2
@Service
@EnableConfigurationProperties({DaprArchivesProperties.class, DaprSocialProperties.class})
public class TSalaryStandardServiceImpl extends ServiceImpl<TSalaryStandardMapper, TSalaryStandard> implements TSalaryStandardService {

	@Autowired
	private TApprovalRecordService approvalRecordService;

	@Autowired
	private TSalaryAccountService salaryAccountService;

	@Autowired
	private MSalaryEstimateService mSalaryEstimateService;

	@Autowired
	private DaprSocialProperties socialProperties;

	@Autowired
	private DaprArchivesProperties archivesProperties;

	@Autowired
	private EkpSalaryUtil ekpSalaryUtil;
	@Autowired
	private EkpSocialUtil ekpSocialUtil;
	@Autowired
	private EkpFundUtil ekpFundUtil;
	@Autowired
	private TApprovalRecordService auditLogService;

	/**
	 * 标准薪酬工资表简单分页查询
	 *
	 * @param tSalaryStandard 标准薪酬工资表
	 * @return
	 */
	@Override
	public IPage<TSalaryStandard> getTSalaryStandardPageApply(Page<TSalaryStandard> page, TSalaryStandardSearchVo tSalaryStandard) {
		return baseMapper.getTSalaryStandardPageApply(page, tSalaryStandard);
	}

	/**
	 * 标准薪酬工资表简单分页查询
	 *
	 * @param tSalaryStandard 标准薪酬工资表
	 * @return
	 */
	@Override
	public IPage<TSalaryStandard> getTSalaryStandardPage(Page<TSalaryStandard> page, TSalaryStandardSearchVo tSalaryStandard) {
		return baseMapper.getTSalaryStandardPage(page, tSalaryStandard);
	}

	/**
	 * 标准薪酬工资表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TSalaryStandardSearchVo searchVo) {
		String fileName = "项目薪酬查询批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TSalaryStandardExportVo> 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 = EasyExcelFactory.write(out, TSalaryStandardExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TSalaryStandardExportVo> util = new ExcelUtil<>(TSalaryStandardExportVo.class);
						for (TSalaryStandardExportVo vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcelFactory.writerSheet("项目薪酬表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcelFactory.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);
			}
		}
	}

	@Override
	public List<TSalaryStandardExportVo> noPageDiy(TSalaryStandardSearchVo searchVo) {
		return baseMapper.getSalaryStandardExport(searchVo, Common.getList(searchVo.getIds()));
	}

	private int noPageCountDiy(TSalaryStandardSearchVo searchVo) {
		return baseMapper.getSalaryStandardExportCount(searchVo, Common.getList(searchVo.getIds()));
	}

	@Override
	public IPage<TSalaryStandard> getTSalaryStandardAuditPage(Page<TSalaryStandard> page, TSalaryStandardSearchVo tSalaryStandard) {
		return baseMapper.getTSalaryStandardAuditPage(page, tSalaryStandard);
	}

	@Override
	public R<String> salaryStandardAudit(String auditFlag, String auditRemark, String id) {
		YifuUser user = SecurityUtils.getUser();
		TSalaryStandard tSalaryStandard = baseMapper.selectById(id);
		if (Common.isNotNull(tSalaryStandard)) {
			//新增流程进展明细
			TApprovalRecord tApprovalRecord = new TApprovalRecord();

			if (CommonConstants.ZERO_STRING.equals(auditFlag)) {
				tSalaryStandard.setStatus(CommonConstants.TWO_INT);
				tApprovalRecord.setApprovalResult(CommonConstants.ZERO_STRING);
				tApprovalRecord.setNodeId("审核通过");
				// 收入相关
				R<String> failed = doIncomeDetail(id, tSalaryStandard);
				if (failed != null) return failed;
			} else {
				tSalaryStandard.setStatus(CommonConstants.FIVE_INT);
				tApprovalRecord.setApprovalResult(CommonConstants.ONE_STRING);
				tApprovalRecord.setNodeId("审核不通过");
			}
			if (Common.isNotNull(auditRemark)) {
				tSalaryStandard.setAuditRemark(auditRemark);
				tApprovalRecord.setApprovalOpinion(auditRemark);
			}
			tSalaryStandard.setAuditUser(user.getId());
			tSalaryStandard.setAuditTime(DateUtil.getCurrentDateTime());
			baseMapper.updateById(tSalaryStandard);

			tApprovalRecord.setSalaryId(tSalaryStandard.getId());
			tApprovalRecord.setApprovalMan(user.getId());
			tApprovalRecord.setApprovalManName(user.getNickname());
			tApprovalRecord.setApprovalTime(DateUtil.getCurrentDateTime());
			approvalRecordService.save(tApprovalRecord);
		}
		return R.ok();

	}

	/**
	 * @param id
	 * @param tSalaryStandard
	 * @Description: 处理收入明细
	 * @Author: hgw
	 * @Date: 2022/9/2 17:35
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	private R<String> doIncomeDetail(String id, TSalaryStandard tSalaryStandard) {
		R<TSettleDomainSelectVo> sdr = HttpDaprUtil.invokeMethodPost(archivesProperties.getAppUrl(), archivesProperties.getAppId()
				, "/tsettledomain/inner/getSettleDomainVoById", tSalaryStandard.getDeptId()
				, TSettleDomainSelectVo.class, SecurityConstants.FROM_IN);
		// 结算主体
		TSettleDomainSelectVo dept;
		if (sdr != null && sdr.getData() != null) {
			dept = sdr.getData();
		} else {
			return R.failed("获取项目信息失败，请联管理员！");
		}
		List<TSalaryAccount> salaryAccountList = salaryAccountService.getListByIncome(id);
		if (salaryAccountList != null && !salaryAccountList.isEmpty()) {
			List<String> idCardList = new ArrayList<>();
			for (TSalaryAccount account : salaryAccountList) {
				idCardList.add(account.getEmpIdcard());
			}
			Map<String, Integer> detailMap = new HashMap<>();
			// 收入相关
			R<String> failed1 = getIncomeDetailMap(tSalaryStandard, dept, idCardList, detailMap);
			if (failed1 != null) return failed1;
			// 含有薪资，则计算收入
			// 管理费
			if (Common.isNotNull(dept.getManageServerItem()) && dept.getManageServerItem().contains(CommonConstants.FOUR_STRING)
					&& CommonConstants.ZERO_STRING.equals(dept.getManagementTag())) {
				// 金额-人数
				if (CommonConstants.TWO_STRING.equals(dept.getManagementType())) {
					// 保存明细
					R<String> failed = saveIncomeDetail(salaryAccountList, tSalaryStandard, dept, detailMap, dept.getManagementType(), CommonConstants.ONE_STRING);
					if (failed != null) return failed;
				} else {
					// 保存明细
					R<String> failed = saveIncomeDetail(salaryAccountList, tSalaryStandard, dept, new HashMap<>(), dept.getManagementType(), CommonConstants.ONE_STRING);
					if (failed != null) return failed;
				}
			}
			// 风险金
			if (Common.isNotNull(dept.getRiskServerItem()) && dept.getRiskServerItem().contains(CommonConstants.FOUR_STRING)
					&& CommonConstants.ZERO_STRING.equals(dept.getRiskFundTag())) {
				// 金额-人数
				if (CommonConstants.TWO_STRING.equals(dept.getRiskFundType())) {
					// 保存明细
					R<String> failed = saveIncomeDetail(salaryAccountList, tSalaryStandard, dept, detailMap, dept.getRiskFundType(), CommonConstants.TWO_STRING);
					if (failed != null) return failed;
				} else {
					// 保存明细
					R<String> failed = saveIncomeDetail(salaryAccountList, tSalaryStandard, dept, new HashMap<>(), dept.getRiskFundType(), CommonConstants.TWO_STRING);
					if (failed != null) return failed;
				}
			}
		}
		return null;
	}

	/**
	 * @Description: 获取收入信息
	 * @Author: hgw
	 * @Date: 2022/9/6 10:39
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	private R<String> getIncomeDetailMap(TSalaryStandard tSalaryStandard, TSettleDomainSelectVo dept, List<String> idCardList, Map<String, Integer> detailMap) {
		TIncomeDetail detail = new TIncomeDetail();
		detail.setPayMonth(tSalaryStandard.getSalaryMonth());
		detail.setIdCardList(idCardList);
		detail.setDeptId(dept.getId());
		R<TIncomeDetailReturnVo> detailR = HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
				, "/tincomedetail/inner/getTIncomeDetailList", detail
				, TIncomeDetailReturnVo.class, SecurityConstants.FROM_IN);
		Integer value;
		if (detailR != null) {
			if (detailR.getData() != null && detailR.getData().getDetailList() != null && !detailR.getData().getDetailList().isEmpty()) {
				TIncomeDetailReturnVo vo = detailR.getData();
				List<TIncomeDetail> detailList = vo.getDetailList();
				for (TIncomeDetail incomeDetail : detailList) {
					value = detailMap.get(incomeDetail.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING
							+ incomeDetail.getDeptId() + CommonConstants.DOWN_LINE_STRING + incomeDetail.getFeeType()
							+ CommonConstants.DOWN_LINE_STRING + incomeDetail.getSourceType());
					if (Common.isEmpty(value)) {
						value = CommonConstants.ZERO_INT;
					}
					if (CommonConstants.ZERO_STRING.equals(incomeDetail.getRedData())) {
						value++;
					} else {
						value--;
					}
					detailMap.put(incomeDetail.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING
							+ incomeDetail.getDeptId() + CommonConstants.DOWN_LINE_STRING
							+ incomeDetail.getFeeType() + CommonConstants.DOWN_LINE_STRING
							+ incomeDetail.getSourceType(), value);
				}
			}
		} else {
			return R.failed("获取收入明细的详情出错，请联系管理员！");
		}
		return null;
	}

	/**
	 * @param feeType  1按比例2金额-人数3金额-人次
	 * @param isManage 1 管理费2 风险金
	 * @Description: 保存明细
	 * @Author: hgw
	 * @Date: 2022/9/2 17:25
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	private R<String> saveIncomeDetail(List<TSalaryAccount> salaryAccountList, TSalaryStandard tSalaryStandard
			, TSettleDomainSelectVo dept, Map<String, Integer> detailMap, String feeType, String isManage) {
		TIncomeDetail detail;
		Integer value;
		BigDecimal money;
		for (TSalaryAccount account : salaryAccountList) {
			value = detailMap.get(account.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING
					+ account.getDeptId() + CommonConstants.DOWN_LINE_STRING + isManage
					+ CommonConstants.DOWN_LINE_STRING
					+ CommonConstants.FOUR_STRING);
			if (Common.isEmpty(value) || value == 0) {
				detail = new TIncomeDetail();
				detail.setPayMonth(account.getSalaryMonth());
				detail.setDeptId(account.getDeptId());
				detail.setDeptName(account.getDeptName());
				detail.setDeptNo(account.getDeptNo());
				detail.setUnitId(tSalaryStandard.getUnitId());
				detail.setUnitName(tSalaryStandard.getUnitName());
				detail.setUnitNo(tSalaryStandard.getUnitNo());
				detail.setCreateMonth(account.getSalaryMonth());
				detail.setEmpIdcard(account.getEmpIdcard());
				detail.setEmpName(account.getEmpName());
				detail.setFeeMode(dept.getManagementType());
				detail.setFeeType(isManage);
				detail.setCharges(String.valueOf(dept.getManagementFee()));
				money = dept.getManagementFee();
				if (CommonConstants.TWO_STRING.equals(isManage)) {
					money = dept.getRiskFundFee();
					detail.setCharges(String.valueOf(dept.getRiskFundFee()));
					detail.setFeeMode(dept.getRiskFundType());
				}
				if (CommonConstants.ONE_STRING.equals(feeType)) {
					money = BigDecimalUtils.safeMultiply(account.getRelaySalary(), money, CommonConstants.ONE_OF_PERCENT);
				}
				detail.setMoney(money);
				detail.setMrSettleType(dept.getMrSettleType());
				detail.setRedData(CommonConstants.ZERO_STRING);
				detail.setSourceId(account.getId());
				detail.setSourceType(CommonConstants.FOUR_STRING);
				R<Boolean> saveR = HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
						, "/tincome/inner/saveDetail", detail, Boolean.class, SecurityConstants.FROM_IN);
				if (saveR == null || saveR.getCode() == CommonConstants.ONE_INT || Boolean.FALSE.equals(saveR.getData())) {
					return R.failed("保存收入明细以及统计出错！");
				}
			}
		}
		return null;
	}

	/**
	 * @Description: 删除
	 * @Author: hgw
	 * @Date: 2022/9/2 17:16
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> deleteSalaryById(String id) {
		if (id != null) {
			TSalaryStandard sf = this.getById(id);
			if (sf != null && Common.isNotNull(sf.getId())) {
				if (sf.getStatus() != null && !SalaryConstants.AUDIT_STATUS[0].equals(sf.getStatus())
						&& !SalaryConstants.AUDIT_STATUS[5].equals(sf.getStatus())
						&& !SalaryConstants.AUDIT_STATUS[7].equals(sf.getStatus())) {
					return R.failed("状态为：【" + SalaryConstants.AUDIT_STATUS_STRING[sf.getStatus()] + "】，不可删除");
				}
			} else {
				return R.failed("删除失败：未找到工资表！");
			}
			YifuUser user = SecurityUtils.getUser();
			if (null == user || null == user.getId()) {
				return R.failed("删除工资表失败-获取登录人信息为空");
			}
			//查询结算单：T_SETTLEMENTH_FORM
			if (sf.getType() == null || sf.getType() != CommonConstants.ONE_INT) {
				//4：删除报账
				TSalaryAccount querySalaryAccountEntity = new TSalaryAccount();
				querySalaryAccountEntity.setSalaryFormId(id);
				QueryWrapper<TSalaryAccount> querySalaryAccountWrapper = new QueryWrapper<>();
				querySalaryAccountWrapper.setEntity(querySalaryAccountEntity);
				List<TSalaryAccount> salaryAccountList = salaryAccountService.list(querySalaryAccountWrapper);
				if (salaryAccountList != null && salaryAccountList.size() > CommonConstants.ZERO_INT) {
					for (TSalaryAccount entity : salaryAccountList) {
						entity.setDeleteFlag(SalaryConstants.DELETED);
					}
					salaryAccountService.updateBatchById(salaryAccountList);
					//5：更新预估库结算标识为0
					MSalaryEstimate salaryEstimate = new MSalaryEstimate();
					salaryEstimate.setSalaryId(id);
					salaryEstimate.setIsSocial(SalaryConstants.IS_SOCIAL_ZERO);
					salaryEstimate.setType(CommonConstants.ZERO_INT);
					QueryWrapper<MSalaryEstimate> salaryEstimateQueryWrapper = new QueryWrapper<>();
					salaryEstimateQueryWrapper.setEntity(salaryEstimate);
					//缴费库社保
					List<MSalaryEstimate> socialList = mSalaryEstimateService.list(salaryEstimateQueryWrapper);
					salaryEstimate.setIsSocial(SalaryConstants.IS_FUND_ONE);
					salaryEstimateQueryWrapper.setEntity(salaryEstimate);
					//缴费库公积金
					List<MSalaryEstimate> fundList = mSalaryEstimateService.list(salaryEstimateQueryWrapper);

					salaryEstimate.setType(CommonConstants.ONE_INT);
					salaryEstimateQueryWrapper.setEntity(salaryEstimate);
					//缴费库公积金
					List<MSalaryEstimate> forecastFundList = mSalaryEstimateService.list(salaryEstimateQueryWrapper);

					salaryEstimate.setIsSocial(SalaryConstants.IS_SOCIAL_ZERO);
					salaryEstimateQueryWrapper.setEntity(salaryEstimate);
					//缴费库公积金
					List<MSalaryEstimate> forecastSocialList = mSalaryEstimateService.list(salaryEstimateQueryWrapper);

					List<String> stringList;
					if (socialList != null && !socialList.isEmpty()) {
						stringList = new ArrayList<>();
						for (MSalaryEstimate s : socialList) {
							stringList.add(s.getEstimateId());
						}
						//更新社保状态为-待结算
						HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
								, "/tpaymentinfo/inner/updatePaymentSocialStatusToNoSettle", stringList, TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
					}
					if (fundList != null && !fundList.isEmpty()) {
						stringList = new ArrayList<>();
						for (MSalaryEstimate s : fundList) {
							stringList.add(s.getEstimateId());
						}
						//更新公积金状态为-待结算
						HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
								, "/tpaymentinfo/inner/updatePaymentFundStatusToNoSettle", stringList, TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
					}
					if (forecastSocialList != null && !forecastSocialList.isEmpty()) {
						stringList = new ArrayList<>();
						for (MSalaryEstimate s : forecastSocialList) {
							stringList.add(s.getEstimateId());
						}
						//更新社保状态为-待结算
						HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
								, "/tforecastlibrary/inner/updateForecastSocialStatusToNoSettle", stringList, TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
					}
					if (forecastFundList != null && !forecastFundList.isEmpty()) {
						stringList = new ArrayList<>();
						for (MSalaryEstimate s : forecastFundList) {
							stringList.add(s.getEstimateId());
						}
						//更新公积金状态为-待结算
						HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
								, "/tforecastlibrary/inner/updateForecastFundStatusToNoSettle", stringList, TDepartSettlementInfo.class, SecurityConstants.FROM_IN);
					}

				}
			}
			//6：删除工资表
			sf.setDeleteFlag(SalaryConstants.DELETED);
			this.updateById(sf);
			return R.ok("级联删除工资表成功");
		}
		return R.failed("id 不可为空");
	}

	/**
	 * @Description: 推送
	 * @Author: hgw
	 * @Date: 2022/9/2 17:16
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> doSend(String id) {
		TSalaryStandard s = this.getById(id);
		if (s == null) {
			return R.failed("未找到工资表");
		} else if (s.getStatus() == SalaryConstants.STATUS[2] || s.getStatus() == SalaryConstants.STATUS[10]) {
			// 2022-9-15 10:50:57需求变更：代扣的要组装预估明细给EKP，EKP自己找差额、变更实缴结算状态。
			//报账表
			List<EkpSalaryParamVo> ekpList = salaryAccountService.getEkpSalaryParamList(id);
			YifuUser user = SecurityUtils.getUser();
			if (user != null) {
				if (ekpList != null && !ekpList.isEmpty()){
					boolean sendStatus = true;
					String sendBack;
					List<TSalaryAccount> accountList = new ArrayList<>();
					TSalaryAccount account;
					Date sendTime = new Date();
					String nowMonth = DateUtil.addMonth(0);
					EkpSalaryParam salaryParam;
					for (EkpSalaryParamVo sendParam : ekpList) {
						salaryParam = new EkpSalaryParam();
						BeanUtils.copyProperties(sendParam, salaryParam);
						// 转化报账表的参数
						account = new TSalaryAccount();
						account.setId(sendParam.getFd_3b10af838eab5c());
						// 社保
						if ((Common.isNotNull(sendParam.getUnitSocial())
								&& !CommonConstants.ZERO_STRING.equals(sendParam.getUnitSocial()))
							||(Common.isNotNull(sendParam.getFd_3b16ce48a9735c())
								&& !CommonConstants.ZERO_STRING.equals(sendParam.getFd_3b16ce48a9735c()))) {
							doSendForecastSocialToEkp(sendParam, s);
						}
						// 公积金
						if ((Common.isNotNull(sendParam.getUnitFund())
								&& !CommonConstants.ZERO_STRING.equals(sendParam.getUnitFund()))
								|| (Common.isNotNull(sendParam.getFd_3b16ce4b7fc42a())
								&& !CommonConstants.ZERO_STRING.equals(sendParam.getFd_3b16ce4b7fc42a()))) {
							doSendForecastFundToEkp(sendParam, s);
						}
						sendBack = ekpSalaryUtil.sendToEKP(salaryParam);
						if (Common.isEmpty(sendBack) || sendBack.length() != 32) {
							sendBack = ekpSalaryUtil.sendToEKP(salaryParam);
						}
						account.setSendTime(sendTime);
						account.setSendUser(user.getId());
						account.setSendUserName(user.getNickname());
						if (Common.isNotNull(sendBack) && sendBack.length() == 32) {
							account.setSendStatus(CommonConstants.ONE_STRING);
							account.setSendMonth(nowMonth);
							account.setEkpId(sendBack);
						} else {
							sendStatus = false;
							TSendEkpError error = new TSendEkpError();
							error.setCreateTime(new Date());
							error.setCreateDay(DateUtil.getThisDay());
							error.setType(CommonConstants.ONE_STRING);
							error.setCreateUserName(s.getCreateName());
							error.setLinkId(account.getId());
							error.setTitle(sendBack);
							error.setNums(CommonConstants.ONE_INT);
							HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
									, "/tsendekperror/inner/saveError", error, Boolean.class, SecurityConstants.FROM_IN);
						}
						accountList.add(account);
					}
					salaryAccountService.updateBatchById(accountList);
					if (sendStatus) {
						s.setSendTime(new Date());
						s.setSendMonth(DateUtil.addMonth(0));
						s.setStatus(SalaryConstants.STATUS[3]);
						this.updateById(s);
						// 添加流程进展明细
						this.saveRecordLog(s, user, CommonConstants.ZERO_STRING, "发送数字化平台-成功");
						return R.ok("发送成功！");
					} else {
						s.setStatus(SalaryConstants.STATUS[10]);
						this.updateById(s);
						// 添加流程进展明细
						this.saveRecordLog(s, user, CommonConstants.ONE_STRING, "发送数字化平台-失败");
						return R.ok("发送失败！");
					}
				}else {
					return R.ok("无数据可发送！");
				}
			} else {
				return R.failed("请登录！");
			}
		} else {
			return R.failed("请刷新后检查薪资表状态！");
		}
	}

	/**
	 * @Description: 添加流程进展明细
	 * @Author: hgw
	 * @Date: 2022/9/6 16:02
	 * @return: void
	 **/
	@Override
	public void saveRecordLog(TSalaryStandard tSalaryStandard, YifuUser user, String status, String nodeId) {
		TApprovalRecord tApprovalRecord = new TApprovalRecord();
		tApprovalRecord.setApprovalResult(status);
		tApprovalRecord.setApprovalOpinion(tSalaryStandard.getRemark());
		tApprovalRecord.setSalaryId(tSalaryStandard.getId());
		tApprovalRecord.setNodeId(nodeId);
		tApprovalRecord.setApprovalMan(user.getId());
		tApprovalRecord.setApprovalManName(user.getNickname());
		tApprovalRecord.setApprovalTime(DateUtil.getCurrentDateTime());
		auditLogService.save(tApprovalRecord);
	}

	private void doSendForecastSocialToEkp(EkpSalaryParamVo account, TSalaryStandard s) {
		EkpPushSocialParam socialParam = new EkpPushSocialParam();
		//订单类型
		socialParam.setFd_3add9dd7833db8("预估");
		//是否有预估
		socialParam.setFd_3add9de0be85e4(CommonConstants.IS_TRUE);
		//与工资合并结算
		socialParam.setFd_3add9e1a670144(CommonConstants.IS_FALSE);
		//项目编码
		socialParam.setFd_3adfe8c70d3fd4(account.getFd_3adfedf98ccba2());
		//项目名称
		socialParam.setFd_3adfe8c8468e54(account.getFd_3adfedf9d2bf1c());
		//单号
		socialParam.setFd_3adfe95c169c48(CommonConstants.EMPTY_STRING);
		//客户编码
		socialParam.setFd_3adfe8c73cb5a4(account.getFd_3adfedfacd65d6());
		//客户名称
		socialParam.setFd_3adfe8c81a0e42(account.getFd_3adfedfb174068());
		//社保户
		socialParam.setFd_3aeafa25916e82(CommonConstants.EMPTY_STRING);
		//员工姓名
		socialParam.setFd_3adfe8c79989d4(account.getFd_3adfedfb5a68a2());
		//员工身份证
		socialParam.setFd_3adfe8c7e4cf7a(account.getFd_3adfedfb8f76d4());
		// 缴纳月份
		socialParam.setFd_3adfe8cf632700(account.getDeduSocialMonth());
		// 生成月份
		socialParam.setFd_3adfe8cb96c41e(account.getDeduSocialMonth());
		// 预估单位合计
		socialParam.setFd_3adfeb4e8064a8(account.getUnitSocial());
		// 预估个人合计
		socialParam.setFd_3adfeb52a4d2e2(account.getFd_3b16ce48a9735c());
		//应收
		socialParam.setFd_3adfeb7b624f06(account.getSocialSum());
		//预估合计
		socialParam.setFd_3af9ed7e813b86(account.getSocialSum());
		//单位养老金额
		socialParam.setFd_3af9ec80a9de7a(CommonConstants.EMPTY_STRING);
		//单位医疗金额
		socialParam.setFd_3af9eba5899c90(CommonConstants.EMPTY_STRING);
		//单位工伤金额
		socialParam.setFd_3af9eba684f592(CommonConstants.EMPTY_STRING);
		//单位失业金额
		socialParam.setFd_3af9eba5f6e19e(CommonConstants.EMPTY_STRING);
		//单位生育金额
		socialParam.setFd_3af9eba71c0138(CommonConstants.EMPTY_STRING);
		//单位大病金额
		socialParam.setFd_3af9eba863c0ee(CommonConstants.EMPTY_STRING);
		//个人养老金额
		socialParam.setFd_3af9ebbd791662(CommonConstants.EMPTY_STRING);
		//个人医疗金额
		socialParam.setFd_3af9ebbdd9797e(CommonConstants.EMPTY_STRING);
		//预估个人大病救助
		socialParam.setFd_3af9ebbf3e8be2(CommonConstants.EMPTY_STRING);
		//预估个人失业
		socialParam.setFd_3af9ebbe29ce1c(CommonConstants.EMPTY_STRING);
		//结算状态
		socialParam.setFd_3add9ea428879a(CommonConstants.SALARY_UNFLAG);
		//结算月份
		socialParam.setFd_3adfe8cff746bc(CommonConstants.EMPTY_STRING);
		//单位差异
		socialParam.setFd_3adfeb53c70f72(CommonConstants.EMPTY_STRING);
		//个人差异
		socialParam.setFd_3adfeb5413fb44(CommonConstants.EMPTY_STRING);
		//收款状态
		socialParam.setFd_3add9eaeed2560(CommonConstants.EMPTY_STRING);
		//结算单号
		socialParam.setFd_3adfeb830523b6(CommonConstants.EMPTY_STRING);
		//收款单号
		socialParam.setFd_3adfeb8489e6c2(CommonConstants.EMPTY_STRING);
		//应支出
		socialParam.setFd_3adfeb7bd97464(CommonConstants.EMPTY_STRING);
		//支出结算状态
		socialParam.setFd_3add9edfbc6f7e(CommonConstants.EMPTY_STRING);
		//付款状态
		socialParam.setFd_3add9eed23894a(CommonConstants.EMPTY_STRING);
		//支出缴纳单号
		socialParam.setFd_3adfeb83a704c8(CommonConstants.EMPTY_STRING);
		//实缴单位生育
		socialParam.setFd_3af9ee3afb34c2(CommonConstants.EMPTY_STRING);
		//付款单号
		socialParam.setFd_3adfeb84175f28(CommonConstants.EMPTY_STRING);
		//实缴个人合计
		socialParam.setFd_3af9ee3cb6d4fa(CommonConstants.EMPTY_STRING);
		//实缴单位合计
		socialParam.setFd_3af9ee3c0bf286(CommonConstants.EMPTY_STRING);
		//实缴个人补缴利息
		socialParam.setFd_3af9ee3d634946(CommonConstants.EMPTY_STRING);
		//实缴单位医疗
		socialParam.setFd_3af9ee39dea6a8(CommonConstants.EMPTY_STRING);
		//预估个人补缴利息
		socialParam.setFd_3af9ebbecc4aa8(CommonConstants.EMPTY_STRING);
		//预估单位补缴利息
		socialParam.setFd_3af9eba7c3da5e(CommonConstants.EMPTY_STRING);
		//实缴单位养老
		socialParam.setFd_3af9ee3938170a(CommonConstants.EMPTY_STRING);
		//实缴个人失业
		socialParam.setFd_3af9ee3db44d96(CommonConstants.EMPTY_STRING);
		//实缴单位补缴利息
		socialParam.setFd_3af9ee3b5ddae8(CommonConstants.EMPTY_STRING);
		//实缴单位大病救助
		socialParam.setFd_3af9ee3ba76f54(CommonConstants.EMPTY_STRING);
		//实缴单位工伤
		socialParam.setFd_3af9ee3aa9c84a(CommonConstants.EMPTY_STRING);
		//实缴合计
		socialParam.setFd_3af9ee3c6bfc74(CommonConstants.EMPTY_STRING);
		//实缴个人医疗
		socialParam.setFd_3af9ee3e066d48(CommonConstants.EMPTY_STRING);
		//实缴单位失业
		socialParam.setFd_3af9ee3a46b7e6(CommonConstants.EMPTY_STRING);
		//实缴个人养老
		socialParam.setFd_3af9ee3e513962(CommonConstants.EMPTY_STRING);
		//实缴个人大病救助
		socialParam.setFd_3af9ee3d0ba3b6(CommonConstants.EMPTY_STRING);
		//我司到款单位
		socialParam.setFd_3b01953871b8be(s.getInvoiceTitle());
		//社保id
		socialParam.setFd_3b0afbe1f94a08(account.getFd_3b10af838eab5c());
		// 是否为BPO业务
		socialParam.setFd_3b178dfcf9e3e6(s.getBpoFlag());
		String sendBack = ekpSocialUtil.sendToEKP(socialParam);
		if (Common.isEmpty(sendBack) || sendBack.length() != 32) {
			sendBack = ekpSocialUtil.sendToEKP(socialParam);
		}
		if (Common.isEmpty(sendBack) || sendBack.length() != 32) {
			TSendEkpError error = new TSendEkpError();
			error.setCreateTime(new Date());
			error.setCreateDay(DateUtil.getThisDay());
			error.setType(CommonConstants.ZERO_STRING);
			error.setCreateUserName(s.getCreateName());
			error.setLinkId(account.getFd_3b10af838eab5c());
			error.setTitle(sendBack);
			error.setNums(CommonConstants.ONE_INT);
			HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
					, "/tsendekperror/inner/saveError", error, Boolean.class, SecurityConstants.FROM_IN);
		}
	}

	private void doSendForecastFundToEkp(EkpSalaryParamVo account, TSalaryStandard s) {
		EkpPushFundParam socialParam = new EkpPushFundParam();
		//订单类型
		socialParam.setFd_3add9dd7833db8("预估");
		//是否有预估
		socialParam.setFd_3add9de0be85e4(CommonConstants.IS_TRUE);
		//与工资合并结算
		socialParam.setFd_3add9e1a670144(CommonConstants.IS_FALSE);
		//项目编码
		socialParam.setFd_3adfe8c70d3fd4(account.getFd_3adfedf98ccba2());
		//项目名称
		socialParam.setFd_3adfe8c8468e54(account.getFd_3adfedf9d2bf1c());
		//单号
		socialParam.setFd_3adfe95c169c48(CommonConstants.EMPTY_STRING);
		//客户编码
		socialParam.setFd_3adfe8c73cb5a4(account.getFd_3adfedfacd65d6());
		//客户名称
		socialParam.setFd_3adfe8c81a0e42(account.getFd_3adfedfb174068());
		//公积金账户
		socialParam.setFd_3aeafa8cc144bc(CommonConstants.EMPTY_STRING);
		//员工姓名
		socialParam.setFd_3adfe8c79989d4(account.getFd_3adfedfb5a68a2());
		//员工身份证
		socialParam.setFd_3adfe8c7e4cf7a(account.getFd_3adfedfb8f76d4());
		// 预估单位代缴
		socialParam.setFd_3adfeb4e8064a8(account.getUnitFund());
		// 预估个人代缴
		socialParam.setFd_3adfeb52a4d2e2(account.getFd_3b16ce4b7fc42a());
		//应收
		socialParam.setFd_3adfeb7b624f06(account.getFundSum());
		// 缴纳月份
		socialParam.setFd_3adfe8cf632700(account.getDeduProvidentMonth());
		// 生成月份
		socialParam.setFd_3adfe8cb96c41e(account.getDeduProvidentMonth());
		//结算状态
		socialParam.setFd_3add9ea428879a(CommonConstants.SALARY_UNFLAG);
		//单位代缴
		socialParam.setFd_3adfeb52fbe966(CommonConstants.EMPTY_STRING);
		//个人代缴
		socialParam.setFd_3adfeb5366dd82(CommonConstants.EMPTY_STRING);
		//结算月份
		socialParam.setFd_3adfe8cff746bc(CommonConstants.EMPTY_STRING);
		//单位差异
		socialParam.setFd_3adfeb53c70f72(CommonConstants.EMPTY_STRING);
		//个人差异
		socialParam.setFd_3adfeb5413fb44(CommonConstants.EMPTY_STRING);
		//收款状态
		socialParam.setFd_3add9eaeed2560(CommonConstants.EMPTY_STRING);
		//结算单号
		socialParam.setFd_3adfeb830523b6(CommonConstants.EMPTY_STRING);
		//收款单号
		socialParam.setFd_3adfeb8489e6c2(CommonConstants.EMPTY_STRING);
		//应支出
		socialParam.setFd_3adfeb7bd97464(CommonConstants.EMPTY_STRING);
		//支出结算状态
		socialParam.setFd_3add9edfbc6f7e(CommonConstants.EMPTY_STRING);
		//付款状态
		socialParam.setFd_3add9eed23894a(CommonConstants.EMPTY_STRING);
		//支出缴纳单号
		socialParam.setFd_3adfeb83a704c8(CommonConstants.EMPTY_STRING);
		//付款单号
		socialParam.setFd_3adfeb84175f28(CommonConstants.EMPTY_STRING);
		//我司到款单位
		socialParam.setFd_3b019a2e9bfdd6(s.getInvoiceTitle());
		// 公积金id
		socialParam.setFd_3b0afbaf10df2c(account.getFd_3b10af838eab5c());
		// 是否为BPO业务
		socialParam.setFd_3b178ea361cabe(s.getBpoFlag());
		String sendBack = ekpFundUtil.sendToEKP(socialParam);
		if (Common.isEmpty(sendBack) || sendBack.length() != 32) {
			sendBack = ekpFundUtil.sendToEKP(socialParam);
		}
		if (Common.isEmpty(sendBack) || sendBack.length() != 32) {
			TSendEkpError error = new TSendEkpError();
			error.setCreateTime(new Date());
			error.setCreateDay(DateUtil.getThisDay());
			error.setType(CommonConstants.ZERO_STRING);
			error.setCreateUserName(s.getCreateName());
			error.setLinkId(account.getFd_3b10af838eab5c());
			error.setTitle(sendBack);
			error.setNums(CommonConstants.ONE_INT);
			HttpDaprUtil.invokeMethodPost(socialProperties.getAppUrl(), socialProperties.getAppId()
					, "/tsendekperror/inner/saveError", error, Boolean.class, SecurityConstants.FROM_IN);
		}
	}
}
