/*
 *    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.social.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
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.social.config.SocialConfig;
import com.yifu.cloud.plus.v1.yifu.social.entity.*;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TSocialSoldierMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.*;
import com.yifu.cloud.plus.v1.yifu.social.vo.*;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 社保士兵-推送
 *
 * @author hgw
 * @date 2024-5-8 14:55:36
 */
@AllArgsConstructor
@Log4j2
@Service
public class TSocialSoldierPushServiceImpl extends ServiceImpl<TSocialSoldierMapper, TSocialInfo> implements TSocialSoldierPushService {

	private RestTemplate restTemplate = new RestTemplate();
	private final SocialConfig socialConfig;
	private final TSocialInfoService tSocialInfoService;
	private final TSocialSoldierShenBaoTaskService tSocialSoldierShenBaoTaskService;
	private final TAutoPaymentInfoService tAutoPaymentInfoService;
	private final TAutoPaymentErrorService tAutoPaymentErrorService;
	private final TAutoPaymentDetailService tAutoPaymentDetailService;
	private final TSocialDeadlineInfoService tSocialDeadlineInfoService;
	private final TSocialSoldierLogService tSocialSoldierLogService;
	private final TSocialFreindSetService tSocialFreindSetService;
	// 安徽省之外的，默认社保士兵
	private static final String SOCIAL_PROVINCE = "安徽省";

	/**
	 * @param socialList
	 * @param file
	 * @param type
	 * @Description: 推送到社保士兵，更新社保表的任务id与状态
	 * @Author: hgw
	 * @Date: 2024/5/11 15:24
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> getOneAppGetModuleDetail(List<TSocialInfo> socialList, MultipartFile file, String type) {
		// 1获取模板id——社保增员、社保减员、医保增员、医保减员
		Map<String, String> moduleDetailMap = socialConfig.getOneModuleDetailMap(restTemplate);
		if (moduleDetailMap != null && !moduleDetailMap.isEmpty() && moduleDetailMap.get(type) != null) {
			// 2获取机器id
			String terminalId = socialConfig.getTwoTerminalId(restTemplate, moduleDetailMap.get(type));
			if (Common.isNotNull(terminalId)) {
				// 3上传文件，获取文件地址
				String fileAddUrl = socialConfig.getThreeTerminalId(restTemplate, file);
				// 4 推送办理任务，返回任务id：
				String addId = socialConfig.getFourAppAdd(restTemplate, fileAddUrl, moduleDetailMap.get(type), terminalId);
				for (TSocialInfo socialInfo : socialList) {
					if ("社保增员".equals(type) || "社保减员".equals(type)) {
						socialInfo.setYgsAddId(addId);
						socialInfo.setYgsHandleStatus(CommonConstants.TWO_STRING);
					} else {
						socialInfo.setYsdAddId(addId);
						socialInfo.setYsdHandleStatus(CommonConstants.TWO_STRING);
					}
				}
				tSocialInfoService.updateBatchById(socialList);
			}
		}
		return R.ok("推送成功！");
	}

	/**
	 * @Description: 组装社保与医保的文件流
	 * @Author: hgw
	 * @Date: 2024/5/23 17:59
	 * @return: org.springframework.web.multipart.MultipartFile
	 **/
	public MultipartFile getFileYgs(List<SocialSoldierYgsAddVo> list) {
		if (list != null) {
			String fileName = "soldierFileYgs" + DateUtil.getThisTime() + new Date().getTime() + CommonConstants.XLSX;
			ExcelWriter excelWriter = EasyExcelFactory.write(fileName).build();
			WriteSheet writeSheet = EasyExcelFactory.writerSheet("社保明细").head(SocialSoldierYgsAddVo.class).build();
			excelWriter.write(list, writeSheet);
			File file = new File(fileName);
			excelWriter.finish();
			return getMultipartFile(file);
		}
		return null;
	}

	/**
	 * @Description: 组装社保与医保的文件流
	 * @Author: hgw
	 * @Date: 2024/5/23 17:59
	 * @return: org.springframework.web.multipart.MultipartFile
	 **/
	public MultipartFile getFileYsd(List<SocialSoldierYsdAddVo> list) {
		if (list != null) {
			String fileName = "soldierFileYsd" + DateUtil.getThisTime() + new Date().getTime() + CommonConstants.XLSX;
			ExcelWriter excelWriter = EasyExcelFactory.write(fileName).build();
			WriteSheet writeSheet = EasyExcelFactory.writerSheet("医保明细").head(SocialSoldierYsdAddVo.class).build();
			excelWriter.write(list, writeSheet);
			File file = new File(fileName);
			excelWriter.finish();
			return getMultipartFile(file);
		}
		return null;
	}

	public static MultipartFile getMultipartFile(File file) {
		FileItem item = new DiskFileItemFactory().createItem("file", MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());
		try (InputStream input = new FileInputStream(file); OutputStream os = item.getOutputStream()) {
			// 流转移
			IOUtils.copy(input, os);
		} catch (Exception e) {
			throw new IllegalArgumentException("Invalid file: " + e, e);
		} finally {
			//删除临时文件
			try {
				org.apache.commons.io.FileUtils.forceDelete(file);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return new CommonsMultipartFile(item);
	}

	/**
	 * @param
	 * @Description: 查询配置开关是否为社保士兵 true:开 false 关（不是安徽省，也可以处理）
	 * @Author: hgw
	 * @Date: 2024/12/13 15:29
	 * @return: boolean
	 **/
	private boolean getFriendSet() {
		TSocialFreindSet set = tSocialFreindSetService.getById("1");
		boolean setFlag = false;
		if (set == null || Common.isEmpty(set.getType()) || 0 == set.getType()) {
			setFlag = true;
		}
		return setFlag;
	}
	/**
	 * @Description: 推送到社保士兵
	 * @Author: hgw
	 * @Date: 2024/5/10 17:53
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> pushSoldier(List<String> dispatchIdList) {

		// 查询配置开关是否为社保士兵 true:开 false 关（不是安徽省，也可以处理）
		boolean setFlag = getFriendSet();

		// 获取时间限制配置(获取 当月启用 的配置)
		Map<String, TSocialDeadlineInfo> socialsetMap = tSocialDeadlineInfoService.getSocialSet();

		// 社保增员、社保减员、医保增员、医保减员
		// 养工失新增列表
		List<SocialSoldierYgsAddVo> ygsAddlist = baseMapper.getSocialSoldierYgsAddVoList(dispatchIdList);
		if (ygsAddlist != null && !ygsAddlist.isEmpty()) {
			this.doPushSocialAndLogYgs(socialsetMap, ygsAddlist, "社保增员", setFlag);
		}

		// 养工失减少列表
		List<SocialSoldierYgsAddVo> ygsReducelist = baseMapper.getSocialSoldierYgsReduceVoList(dispatchIdList);
		if (ygsReducelist != null && !ygsReducelist.isEmpty()) {
			this.doPushSocialAndLogYgs(socialsetMap, ygsReducelist, "社保减员", setFlag);
		}
		// 医生大新增列表
		List<SocialSoldierYsdAddVo> ysdAddlist = baseMapper.getSocialSoldierYsdAddVoList(dispatchIdList);
		if (ysdAddlist != null && !ysdAddlist.isEmpty()) {
			this.doPushSocialAndLogYsd(socialsetMap, ysdAddlist, "医保增员", setFlag);
		}
		// 医生大减少列表
		List<SocialSoldierYsdAddVo> ysdReducelist = baseMapper.getSocialSoldierYsdReduceVoList(dispatchIdList);
		if (ysdReducelist != null && !ysdReducelist.isEmpty()) {
			this.doPushSocialAndLogYsd(socialsetMap, ysdReducelist, "医保减员", setFlag);
		}
		if ((ygsAddlist == null || ygsAddlist.isEmpty())
				&& (ygsReducelist == null || ygsReducelist.isEmpty())
				&& (ysdAddlist == null || ysdAddlist.isEmpty())
				&& (ysdReducelist == null || ysdReducelist.isEmpty())
		) {
			return R.failed("无数据，推送结束！");
		}

		return R.ok("推送成功！！");
	}

	/**
	 * @Description: 推送社保和记录日志
	 * @Author: hgw
	 * @Date: 2024/9/2 17:21
	 * @return: void
	 **/
	private void doPushSocialAndLogYgs(Map<String, TSocialDeadlineInfo> socialsetMap
			, List<SocialSoldierYgsAddVo> ygsAddlist, String socialType, boolean setFlag) {
		List<TSocialInfo> socialIdList = new ArrayList<>();
		int canPushType;
		TSocialInfo socialInfo;
		List<SocialSoldierYgsAddVo> ygsAddlistCopy = new ArrayList<>();
		String type = "提交";
		List<TSocialSoldierLog> logList = new ArrayList<>();
		TSocialSoldierLog socialLog;
		String remark;
		List<TSocialInfo> renGongList = new ArrayList<>();
		for (SocialSoldierYgsAddVo vo : ygsAddlist) {

			if (setFlag || !SOCIAL_PROVINCE.equals(vo.getSocialProvince())) {
				// 0：未到时间不动; 1：推送; 2：转人工
				canPushType = this.getCanPushType(socialsetMap, vo);

				if (1 == canPushType) {
					socialInfo = new TSocialInfo();
					socialInfo.setId(vo.getSocialId());
					socialIdList.add(socialInfo);
					ygsAddlistCopy.add(vo);
					remark = "已推送提交任务！";
				} else {
					if (0 == canPushType) {
						remark = "未到时间，不推送！";
					} else {
						remark = "无时间配置或超出办理截止时间，转人工！";
						socialInfo = new TSocialInfo();
						socialInfo.setId(vo.getSocialId());
						socialInfo.setYgsHandleStatus(CommonConstants.FIVE_STRING);
						renGongList.add(socialInfo);
					}
				}
				socialLog = tSocialSoldierLogService.getYgsSoldierLog(vo, type, remark);
				if (socialLog != null) {
					logList.add(socialLog);
				}
			}
		}
		if (!renGongList.isEmpty()) {
			tSocialInfoService.updateBatchById(renGongList);
		}
		if (!logList.isEmpty()) {
			tSocialSoldierLogService.saveBatch(logList);
		}
		// 3如果没有要办理的数据，就不需要推送
		if (!socialIdList.isEmpty()) {
			try {
				MultipartFile file = this.getFileYgs(ygsAddlistCopy);
				if (Common.isNotNull(file)) {
					this.getOneAppGetModuleDetail(socialIdList, file, socialType);
				}
			} catch (Exception e) {
				log.error("提交社保士兵异常2：",e);
				if (!logList.isEmpty()) {
					for (TSocialSoldierLog logTemp : logList) {
						logTemp.setRemark("提交社保士兵异常！");
					}
					tSocialSoldierLogService.updateBatchById(logList);
				}
			}
		}
	}

	/**
	 * @Description: 推送医保和记录日志
	 * @Author: hgw
	 * @Date: 2024/9/2 17:21
	 * @return: void
	 **/
	private void doPushSocialAndLogYsd(Map<String, TSocialDeadlineInfo> socialsetMap
			, List<SocialSoldierYsdAddVo> ysdAddlist, String socialType, boolean setFlag) {
		List<TSocialInfo> socialIdList = new ArrayList<>();
		int canPushType;
		TSocialInfo socialInfo;
		List<SocialSoldierYsdAddVo> ysdAddlistCopy = new ArrayList<>();
		String type = "提交";
		List<TSocialSoldierLog> logList = new ArrayList<>();
		TSocialSoldierLog socialLog;
		List<TSocialInfo> renGongList = new ArrayList<>();
		String remark;
		for (SocialSoldierYsdAddVo vo : ysdAddlist) {
			if (setFlag || !SOCIAL_PROVINCE.equals(vo.getSocialProvince())) {
				// 0：未到时间不动; 1：推送; 2：转人工
				canPushType = this.getCanPushTypeYsd(socialsetMap, vo);

				if (1 == canPushType) {
					socialInfo = new TSocialInfo();
					socialInfo.setId(vo.getSocialId());
					socialIdList.add(socialInfo);
					ysdAddlistCopy.add(vo);
					remark = "已推送提交任务！";
				} else {
					if (0 == canPushType) {
						remark = "未到时间，不推送！";
					} else {
						remark = "无时间配置或超出办理截止时间，转人工！";
						socialInfo = new TSocialInfo();
						socialInfo.setId(vo.getSocialId());
						socialInfo.setYsdHandleStatus(CommonConstants.FIVE_STRING);
						renGongList.add(socialInfo);
					}
				}
				socialLog = tSocialSoldierLogService.getYsdSoldierLog(vo, type, remark);
				if (socialLog != null) {
					logList.add(socialLog);
				}
			}
		}
		if (!renGongList.isEmpty()) {
			tSocialInfoService.updateBatchById(renGongList);
		}
		if (!logList.isEmpty()) {
			tSocialSoldierLogService.saveBatch(logList);
		}
		// 3如果没有要办理的数据，就不需要推送
		if (!socialIdList.isEmpty()) {
			try {
				MultipartFile file = this.getFileYsd(ysdAddlistCopy);
				if (Common.isNotNull(file)) {
					this.getOneAppGetModuleDetail(socialIdList, file, socialType);
				}
			} catch (Exception e) {
				log.error("提交社保士兵异常1：",e);
				if (!logList.isEmpty()) {
					for (TSocialSoldierLog logTemp : logList) {
						logTemp.setRemark("提交社保士兵异常！");
					}
					tSocialSoldierLogService.updateBatchById(logList);
				}
			}
		}
	}

	/**
	 * @param socialsetMap 时间限制配置Map
	 * @param vo           社保或医保
	 * @Description:
	 * @Author: hgw
	 * @Date: 2024/9/2 16:00
	 * @return: int
	 **/
	private int getCanPushType(Map<String, TSocialDeadlineInfo> socialsetMap, SocialSoldierYgsAddVo vo) {
		// 0：未到时间不动; 1：推送; 2：转人工
		int canPushType = 0;
		if (socialsetMap != null) {
			TSocialDeadlineInfo socialSet;
			StringBuilder addressKey;
			Date nowTime = new Date();
			if (Common.isNotNull(vo.getSocialProvince())) {
				addressKey = new StringBuilder(vo.getSocialProvince()).append(CommonConstants.DOWN_LINE_STRING);
				if (Common.isEmpty(vo.getSocialCity())) {
					addressKey.append(CommonConstants.CENTER_SPLIT_LINE_STRING);
				} else {
					addressKey.append(vo.getSocialCity());
				}
				addressKey.append(CommonConstants.DOWN_LINE_STRING);
				if (Common.isEmpty(vo.getSocialTown())) {
					addressKey.append(CommonConstants.CENTER_SPLIT_LINE_STRING);
				} else {
					addressKey.append(vo.getSocialTown());
				}
				socialSet = socialsetMap.get(addressKey.toString());

				if (socialSet != null) {
					Date start = socialSet.getSocialStartDate();
					Date end = socialSet.getSocialEndDate();
					if ("派减".equals(vo.getType())) {
						start = socialSet.getSocialStartDateReduce();
						end = socialSet.getSocialEndDateReduce();
					}
					if (Common.isNotNull(start) && Common.isNotNull(end)) {
						if (nowTime.before(start)) {
							canPushType = 0;
						} else if (nowTime.after(end)) {
							canPushType = 2;
						} else {
							canPushType = 1;
						}
					} else {
						// 无配置或配置时间为空
						canPushType = 2;
					}
				} else {
					// 无配置或配置时间为空
					canPushType = 2;
				}
			}
		} else {
			// 2无时间限制的转人工
			canPushType = 2;
		}
		return canPushType;
	}

	private int getCanPushTypeYsd(Map<String, TSocialDeadlineInfo> socialsetMap, SocialSoldierYsdAddVo vo) {
		// 0：未到时间不动; 1：推送; 2：转人工
		int canPushType = 0;
		if (socialsetMap != null) {
			TSocialDeadlineInfo socialSet;
			StringBuilder addressKey;
			Date nowTime = new Date();
			if (Common.isNotNull(vo.getSocialProvince())) {
				addressKey = new StringBuilder(vo.getSocialProvince()).append(CommonConstants.DOWN_LINE_STRING);
				if (Common.isEmpty(vo.getSocialCity())) {
					addressKey.append(CommonConstants.CENTER_SPLIT_LINE_STRING);
				} else {
					addressKey.append(vo.getSocialCity());
				}
				addressKey.append(CommonConstants.DOWN_LINE_STRING);
				if (Common.isEmpty(vo.getSocialTown())) {
					addressKey.append(CommonConstants.CENTER_SPLIT_LINE_STRING);
				} else {
					addressKey.append(vo.getSocialTown());
				}
				socialSet = socialsetMap.get(addressKey.toString());

				if (socialSet != null) {
					Date start = socialSet.getMedicalStartDate();
					Date end = socialSet.getMedicalEndDate();
					if ("派减".equals(vo.getType())) {
						start = socialSet.getMedicalStartDateReduce();
						end = socialSet.getMedicalEndDateReduce();
					}
					if (Common.isNotNull(start) && Common.isNotNull(end)) {
						if (nowTime.before(start)) {
							canPushType = 0;
						} else if (nowTime.after(end)) {
							canPushType = 2;
						} else {
							canPushType = 1;
						}
					} else {
						// 无配置或配置时间为空
						canPushType = 2;
					}
				} else {
					// 无配置或配置时间为空
					canPushType = 2;
				}
			}
		} else {
			// 2无时间限制的转人工
			canPushType = 2;
		}
		return canPushType;
	}

	/**
	 * @Description: 推送社保士兵审核结果查询文件
	 * @Author: hgw
	 * @Date: 2024-5-23 18:02:27
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> pushSoldierByAudit() {

		// 养工失待审核列表
		List<SocialSoldierYgsAuditVo> ygsAddlist = baseMapper.getSocialSoldierYgsAuditVoList();
		List<SocialSoldierYgsAuditVo> ygsAddByGroupBylist = baseMapper.getSocialSoldierYgsAuditVoListByGroupBy();
		String sheetName = "审核数据查询";
		String type = "审核";
		String remark = "已推送审核任务！";
		String errorRemark = "推送社保士兵审核异常！";
		TSocialSoldierLog socialLog;
		List<TSocialSoldierLog> logList = new ArrayList<>();
		if (ygsAddlist != null && !ygsAddlist.isEmpty()) {
			MultipartFile file = this.getFileByAudit(ygsAddByGroupBylist, null, sheetName);
			if (Common.isNotNull(file)) {
				List<TSocialInfo> socialIdList = new ArrayList<>();
				TSocialInfo socialInfo;
				for (SocialSoldierYgsAuditVo vo : ygsAddlist) {
					socialInfo = new TSocialInfo();
					socialInfo.setId(vo.getSocialId());
					socialIdList.add(socialInfo);

					// 组装日志
					socialLog = tSocialSoldierLogService.getYgsSoldierAuditLog(vo, type, remark);
					if (socialLog != null) {
						logList.add(socialLog);
					}
				}
				// 保存
				if (!logList.isEmpty()) {
					tSocialSoldierLogService.saveBatch(logList);
				}
				try {
					this.getOneAppGetModuleDetailByAudit(socialIdList, file, sheetName);
				} catch (Exception e) {
					log.error(errorRemark +"2：",e);
					if (!logList.isEmpty()) {
						// 异常时，更新日志
						for (TSocialSoldierLog logTemp : logList) {
							logTemp.setRemark(errorRemark);
						}
						tSocialSoldierLogService.updateBatchById(logList);
					}
				}
			}
		}
		// 医生大【续保】待审核列表
		List<SocialSoldierYsdAuditVo> ysdXuBaolist = baseMapper.getSocialSoldierYsdAuditVoList();
		List<SocialSoldierYsdAuditVo> ysdXuBaoByGroupBylist = baseMapper.getSocialSoldierYsdAuditVoListByGroupBy();
		sheetName = "审核数据信息查询";
		logList = new ArrayList<>();
		if (ysdXuBaolist != null && !ysdXuBaolist.isEmpty()) {
			MultipartFile file = this.getFileByAudit(null, ysdXuBaoByGroupBylist, sheetName);
			if (Common.isNotNull(file)) {
				List<TSocialInfo> socialIdList = new ArrayList<>();
				TSocialInfo socialInfo;
				for (SocialSoldierYsdAuditVo vo : ysdXuBaolist) {
					socialInfo = new TSocialInfo();
					socialInfo.setId(vo.getSocialId());
					socialIdList.add(socialInfo);

					// 组装日志
					socialLog = tSocialSoldierLogService.getYsdSoldierAuditLog(vo, type, remark);
					if (socialLog != null) {
						logList.add(socialLog);
					}
				}
				// 保存
				if (!logList.isEmpty()) {
					tSocialSoldierLogService.saveBatch(logList);
				}
				try {
					this.getOneAppGetModuleDetailByAudit(socialIdList, file, sheetName);
				} catch (Exception e) {
					log.error(errorRemark +"1：",e);
					if (!logList.isEmpty()) {
						// 异常时，更新日志
						for (TSocialSoldierLog logTemp : logList) {
							logTemp.setRemark(errorRemark);
						}
						tSocialSoldierLogService.updateBatchById(logList);
					}
				}
			}
		}
		// 医生大【新增】待审核列表
		List<SocialSoldierYsdAuditVo> ysdAddlist = baseMapper.getSocialSoldierYsdAddAuditVoList();
		List<SocialSoldierYsdAuditVo> ysdAddByGroupBylist = baseMapper.getSocialSoldierYsdAddAuditVoListByGroupBy();
		logList = new ArrayList<>();
		if (ysdAddlist != null && !ysdAddlist.isEmpty()) {

			MultipartFile file = this.getFileByAudit(null, ysdAddByGroupBylist, sheetName);
			if (Common.isNotNull(file)) {
				List<TSocialInfo> socialIdList = new ArrayList<>();
				TSocialInfo socialInfo;
				for (SocialSoldierYsdAuditVo vo : ysdAddlist) {
					socialInfo = new TSocialInfo();
					socialInfo.setId(vo.getSocialId());
					socialIdList.add(socialInfo);

					// 组装日志
					socialLog = tSocialSoldierLogService.getYsdSoldierAuditLog(vo, type, remark);
					if (socialLog != null) {
						logList.add(socialLog);
					}
				}

				// 保存
				if (!logList.isEmpty()) {
					tSocialSoldierLogService.saveBatch(logList);
				}
				try {
					this.getOneAppGetModuleDetailByAudit(socialIdList, file, sheetName);
				} catch (Exception e) {
					log.error(errorRemark +"3：",e);
					if (!logList.isEmpty()) {
						// 异常时，更新日志
						for (TSocialSoldierLog logTemp : logList) {
							logTemp.setRemark(errorRemark);
						}
						tSocialSoldierLogService.updateBatchById(logList);
					}
				}
			}
		}
		if (ygsAddlist == null && ysdXuBaolist == null && ysdAddlist == null) {
			return R.failed("无数据，推送结束！");
		}
		return R.ok("推送成功！！");
	}

	/**
	 * @Description: 推送审核结果的查询
	 * @Author: hgw
	 * @Date: 2024/5/23 18:09
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	public R<String> getOneAppGetModuleDetailByShenBao(TSocialSoldierShenBaoTask task, MultipartFile file, String type) {
		// 1获取模板id——社保增员、社保减员、医保增员、医保减员
		Map<String, String> moduleDetailMap = socialConfig.getOneModuleDetailMap(restTemplate);
		if (moduleDetailMap != null && !moduleDetailMap.isEmpty() && moduleDetailMap.get(type) != null) {
			// 2获取机器id
			String terminalId = socialConfig.getTwoTerminalId(restTemplate, moduleDetailMap.get(type));
			if (Common.isNotNull(terminalId)) {
				// 3上传文件，获取文件地址
				String fileAddUrl = socialConfig.getThreeTerminalId(restTemplate, file);
				// 4 推送办理任务，返回任务id：
				String addId = socialConfig.getFourAppAdd(restTemplate, fileAddUrl, moduleDetailMap.get(type), terminalId);
				task.setAddId(addId);
				tSocialSoldierShenBaoTaskService.save(task);
			}
		}
		return R.ok("推送成功！");
	}

	/**
	 * @Description: 推送审核结果的查询
	 * @Author: hgw
	 * @Date: 2024/5/23 18:09
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	public R<String> getOneAppGetModuleDetailByAudit(List<TSocialInfo> socialList, MultipartFile file, String type) {
		// 1获取模板id——社保增员、社保减员、医保增员、医保减员
		Map<String, String> moduleDetailMap = socialConfig.getOneModuleDetailMap(restTemplate);
		if (moduleDetailMap != null && !moduleDetailMap.isEmpty() && moduleDetailMap.get(type) != null) {
			// 2获取机器id
			String terminalId = socialConfig.getTwoTerminalId(restTemplate, moduleDetailMap.get(type));
			if (Common.isNotNull(terminalId)) {
				// 3上传文件，获取文件地址
				String fileAddUrl = socialConfig.getThreeTerminalId(restTemplate, file);
				// 4 推送办理任务，返回任务id：
				String addId = socialConfig.getFourAppAdd(restTemplate, fileAddUrl, moduleDetailMap.get(type), terminalId);
				for (TSocialInfo socialInfo : socialList) {
					if ("审核数据查询".equals(type)) {
						socialInfo.setYgsAddId(addId);
					} else {
						socialInfo.setYsdAddId(addId);
					}
				}
				tSocialInfoService.updateBatchById(socialList);
			}
		}
		return R.ok("推送成功！");
	}

	/**
	 * @Description: 组装社保与医保的文件流
	 * @Author: hgw
	 * @Date: 2024/5/23 17:59
	 * @return: org.springframework.web.multipart.MultipartFile
	 **/
	public MultipartFile getFile(List list, Class clazz, String sheetName) {
		String fileName = "soldierFile" + DateUtil.getThisTime() + new Date().getTime() + CommonConstants.XLSX;
		if (list != null) {
			EasyExcelFactory.write(fileName, clazz).sheet(sheetName).doWrite(list);
			File file = new File(fileName);
			return getMultipartFile(file);
		}
		return null;
	}

	/**
	 * @Description: 组装社保与医保的文件流
	 * @Author: hgw
	 * @Date: 2024/5/23 17:59
	 * @return: org.springframework.web.multipart.MultipartFile
	 **/
	public MultipartFile getFileByAudit(List<SocialSoldierYgsAuditVo> listYgs, List<SocialSoldierYsdAuditVo> listYsd, String sheetName) {
		String fileName = "soldierAuditFile" + DateUtil.getThisTime() + new Date().getTime() + CommonConstants.XLSX;
		if (listYgs != null) {
			EasyExcelFactory.write(fileName, SocialSoldierYgsAuditVo.class).sheet(sheetName).doWrite(listYgs);
		} else {
			EasyExcelFactory.write(fileName, SocialSoldierYsdAuditVo.class).sheet(sheetName).doWrite(listYsd);
		}
		File file = new File(fileName);
		return getMultipartFile(file);
	}

	/**
	 * @Description: 推送社保士兵工资申报、调整
	 * @Author: hgw
	 * @Date: 2024-5-23 18:02:27
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> pushSalaryByShenBao() {
		// 工资申报
		List<SocialSoldierSalaryShenBaoVo> shenBaolist = baseMapper.getSoldierSalaryByShenBaoList();
		log.info("工资申报列表=" + shenBaolist);
		String sheetName = "年度缴费工资申报";
		if (shenBaolist != null && !shenBaolist.isEmpty()) {
			MultipartFile file = this.getFile(shenBaolist, SocialSoldierSalaryShenBaoVo.class, sheetName);
			if (Common.isNotNull(file)) {
				TSocialSoldierShenBaoTask task = new TSocialSoldierShenBaoTask();
				task.setType(CommonConstants.ONE_STRING);
				task.setDataStatus(CommonConstants.ZERO_STRING);
				this.getOneAppGetModuleDetailByShenBao(task, file, sheetName);
			}
		}
		// 工资调整
		List<SocialSoldierSalaryTiaoZhengVo> tiaoZhenglist = baseMapper.getSoldierSalaryByTiaoZhengList();
		log.info("工资调整列表=" + tiaoZhenglist);
		sheetName = "年度缴费工资调整";
		if (tiaoZhenglist != null && !tiaoZhenglist.isEmpty()) {
			MultipartFile file = this.getFile(tiaoZhenglist, SocialSoldierSalaryTiaoZhengVo.class, sheetName);
			if (Common.isNotNull(file)) {
				TSocialSoldierShenBaoTask task = new TSocialSoldierShenBaoTask();
				task.setType(CommonConstants.TWO_STRING);
				task.setDataStatus(CommonConstants.ZERO_STRING);
				this.getOneAppGetModuleDetailByShenBao(task, file, sheetName);
			}
		}
		if (shenBaolist == null && tiaoZhenglist == null) {
			return R.failed("无数据，推送结束！");
		}
		return R.ok("推送成功！！");
	}

	/**
	 * @param : isReHandle true:是重新办理
	 * @Description: 6每月6号推送实缴3张表查询
	 * @Author: hgw
	 * @Date: 2024-5-31 16:04:47
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> pushPaymentThree(String parentId, boolean isReHandle) {

		// 先删除推送任务
		int type = 3;
		if (isReHandle) {
			int count = tAutoPaymentDetailService.getCountByParentId(parentId);
			if (count == 0) {
				return R.failed("请先标记！");
			}
			type = 7;
			List<TSocialSoldierShenBaoTask> taskList = tSocialSoldierShenBaoTaskService.getTSocialSoldierTaskListByRe();
			boolean canReTask = false;
			if (taskList != null && !taskList.isEmpty()) {
				for (TSocialSoldierShenBaoTask task : taskList) {
					// 表示已经有过反馈了
					if (CommonConstants.ONE_STRING.equals(task.getDataStatus())) {
						canReTask = true;
						break;
					}
				}
				if (!canReTask) {
					return R.failed("上一次推送的还未获取结果，请先获取复核结果！");
				} else {
					// 清空原表url
					if (Common.isNotNull(parentId)) {
						tAutoPaymentErrorService.deleteByParentId(parentId);
						tAutoPaymentInfoService.setUrlToNullByRePayment(parentId);
					}
				}
			} else {
				if (Common.isNotNull(parentId)) {
					tAutoPaymentErrorService.deleteByParentId(parentId);
				}
				tSocialSoldierShenBaoTaskService.deleteByRePayment();
			}
		} else {
			tSocialSoldierShenBaoTaskService.deleteByPayment();
		}
		// 实缴3张表之1：日常申报
		List<SocialSoldierPaymentSelectOneVo> shenBaolist = baseMapper.getSoldierPaymentSelectOneList();
		log.info("实缴3张表之1：日常申报list=" + shenBaolist);
		String sheetName = "日常申报导出";
		if (shenBaolist != null && !shenBaolist.isEmpty()) {
			MultipartFile file = this.getFile(shenBaolist, SocialSoldierPaymentSelectOneVo.class, sheetName);
			if (Common.isNotNull(file)) {
				TSocialSoldierShenBaoTask task = new TSocialSoldierShenBaoTask();
				// 1申报；2调整；3：实缴1日常申报导出；4：实缴2人员缴费明细打印；5：实缴3单位缴费明细查询
				task.setType(String.valueOf(type));
				type++;
				task.setDataStatus(CommonConstants.ZERO_STRING);
				this.getOneAppGetModuleDetailByShenBao(task, file, sheetName);
			}
		}
		// 实缴3张表之2：人员缴费明细打印
		List<SocialSoldierPaymentSelectTwoVo> shenBaoTwolist = baseMapper.getSoldierPaymentSelectTwoList();
		log.info("实缴3张表之2：单位个人缴费信息查询list=" + shenBaoTwolist);
		sheetName = "单位个人缴费信息查询";
		if (shenBaoTwolist != null && !shenBaoTwolist.isEmpty()) {
			MultipartFile file = this.getFile(shenBaoTwolist, SocialSoldierPaymentSelectTwoVo.class, sheetName);
			if (Common.isNotNull(file)) {
				TSocialSoldierShenBaoTask task = new TSocialSoldierShenBaoTask();
				// 1申报；2调整；3：实缴1日常申报导出；4：实缴2人员缴费明细打印；5：实缴3单位缴费明细查询
				task.setType(String.valueOf(type));
				type++;
				task.setDataStatus(CommonConstants.ZERO_STRING);
				this.getOneAppGetModuleDetailByShenBao(task, file, sheetName);
			}
		}
		// 实缴3张表之3：单位缴费明细查询
		List<SocialSoldierPaymentSelectThreeVo> shenBaoThreelist = baseMapper.getSoldierPaymentSelectThreeList();
		log.info("实缴3张表之3：单位缴费明细查询list=" + shenBaoThreelist);
		sheetName = "单位缴费明细查询";
		if (shenBaoThreelist != null && !shenBaoThreelist.isEmpty()) {
			MultipartFile file = this.getFile(shenBaoThreelist, SocialSoldierPaymentSelectThreeVo.class, sheetName);
			if (Common.isNotNull(file)) {
				TSocialSoldierShenBaoTask task = new TSocialSoldierShenBaoTask();
				// 1申报；2调整；3：实缴1日常申报导出；4：实缴2人员缴费明细打印；5：实缴3单位缴费明细查询
				task.setType(String.valueOf(type));
				type++;
				task.setDataStatus(CommonConstants.ZERO_STRING);
				this.getOneAppGetModuleDetailByShenBao(task, file, sheetName);
			}
		}
		// 实缴3张表之3-2：单位缴费明细下载
		List<SocialSoldierPaymentSelectThreeVo> shenBaoFourlist = baseMapper.getSoldierPaymentSelectThreeList();
		log.info("实缴3张表之3-2：单位缴费明细下载list=" + shenBaoFourlist);
		sheetName = "单位缴费明细下载";
		if (shenBaoFourlist != null && !shenBaoFourlist.isEmpty()) {
			MultipartFile file = this.getFile(shenBaoFourlist, SocialSoldierPaymentSelectThreeVo.class, sheetName);
			if (Common.isNotNull(file)) {
				TSocialSoldierShenBaoTask task = new TSocialSoldierShenBaoTask();
				// 1申报；2调整；3：实缴1日常申报导出；4：实缴2人员缴费明细打印；5：实缴3单位缴费明细查询；6：实缴3单位缴费明细下载
				task.setType(String.valueOf(type));
				type++;
				task.setDataStatus(CommonConstants.ZERO_STRING);
				this.getOneAppGetModuleDetailByShenBao(task, file, sheetName);
			}
		}
		if (shenBaolist == null && shenBaoTwolist == null && shenBaoThreelist == null && shenBaoFourlist == null) {
			return R.failed("无数据，推送结束！");
		}
		return R.ok("推送成功！！");
	}

}
