/*
 *    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 cn.hutool.core.util.CharsetUtil;
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.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
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.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.TSocialSoldierReturnAuditErrorVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialSoldierReturnErrorVo;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

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

	private RestTemplate restTemplate = new RestTemplate();
	private final SocialConfig socialConfig;
	private final TDispatchInfoService tDispatchInfoService;
	private final TSocialInfoService tSocialInfoService;
	private final FailReasonConfigService failReasonConfigService;
	private final TAuditInfoService tAuditInfoService;
	private final TSocialSoldierShenBaoTaskService tSocialSoldierShenBaoTaskService;
	private final TAutoPaymentInfoService tAutoPaymentInfoService;
	private final TAutoPaymentDetailService tAutoPaymentDetailService;

	private final OSSUtil ossUtil;
	// 附件
	private final String RESULT_ANNEX = "resultAnnex";

	/**
	 * @Description: 6每月6号定时任务获取社保士兵实缴3张表
	 * @Author: hgw
	 * @Date: 2024-5-30 18:01:11
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	@Async
	public R<String> getReHandle(String parentId) {
		TAutoPaymentInfo mainAuto = tAutoPaymentInfoService.getById(parentId);
		if (mainAuto == null || Common.isEmpty(mainAuto.getId())) {
			return R.failed("未找到主表");
		} else {
			mainAuto.setRepeatReviewFlag(CommonConstants.ZERO_STRING);
			tAutoPaymentInfoService.updateById(mainAuto);
		}
		// 3：实缴1日常申报导出；4：实缴2单位个人缴费信息查询；5：实缴3单位缴费明细查询
		int type = 7;
		TSocialSoldierShenBaoTask addIdOneTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(String.valueOf(type));
		type++;
		TSocialSoldierShenBaoTask addIdTwoTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(String.valueOf(type));
		type++;
		TSocialSoldierShenBaoTask addIdThreeTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(String.valueOf(type));
		type++;
		TSocialSoldierShenBaoTask addIdSixTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(String.valueOf(type));
		String addIdOne = null;
		String addIdOTwo = null;
		String addIdThree = null;
		String addIdSix = null;
		if (addIdOneTask != null && Common.isNotNull(addIdOneTask.getId())) {
			addIdOne = addIdOneTask.getAddId();
		}
		if (addIdTwoTask != null && Common.isNotNull(addIdTwoTask.getId())) {
			addIdOTwo = addIdTwoTask.getAddId();
		}
		if (addIdThreeTask != null && Common.isNotNull(addIdThreeTask.getId())) {
			addIdThree = addIdThreeTask.getAddId();
		}
		if (addIdSixTask != null && Common.isNotNull(addIdSixTask.getId())) {
			addIdSix = addIdSixTask.getAddId();
		}
		HttpURLConnection conn;
		InputStream inRiChang = null;
		InputStream inRenYuan = null;
		InputStream inDanWei = null;
		InputStream inDanWeiXiaZai = null;
		// 1日常申报导出；2单位个人缴费信息查询；3单位缴费明细查询
		R<String> resultFile = socialConfig.getFiveJob(restTemplate, addIdOne, RESULT_ANNEX);
		R<String> resultFileTwo = socialConfig.getFiveJob(restTemplate, addIdOTwo, RESULT_ANNEX);
		R<String> resultFileThree = socialConfig.getFiveJob(restTemplate, addIdThree, RESULT_ANNEX);
		R<String> resultFileFour = socialConfig.getFiveJob(restTemplate, addIdSix, RESULT_ANNEX);
		if (Common.isNotNull(resultFile) || Common.isNotNull(resultFileTwo)
				|| Common.isNotNull(resultFileThree) || Common.isNotNull(resultFileFour)) {

			// 获取需要更新的标记文件：
			List<TAutoPaymentDetail> detailList = tAutoPaymentDetailService.getListByParentId(parentId);
			if (detailList == null || detailList.isEmpty()) {
				return R.failed("未找到标记数据！");
			}
			Map<String, TAutoPaymentDetail> oneMap = new HashMap<>();
			Map<String, TAutoPaymentDetail> twoMap = new HashMap<>();
			Map<String, TAutoPaymentDetail> threeMap = new HashMap<>();
			Map<String, TAutoPaymentDetail> fourMap = new HashMap<>();
			for (TAutoPaymentDetail detail : detailList) {
				if (CommonConstants.ONE_STRING.equals(detail.getSourceType())) {
					oneMap.put(detail.getCertNum() + CommonConstants.DOWN_LINE_STRING + detail.getSocialSecurityAccount() + CommonConstants.DOWN_LINE_STRING + detail.getInsuranceType(), detail);
				}
				if (CommonConstants.TWO_STRING.equals(detail.getSourceType())) {
					twoMap.put(detail.getCertNum() + CommonConstants.DOWN_LINE_STRING + detail.getSocialSecurityAccount() + CommonConstants.DOWN_LINE_STRING + detail.getInsuranceType(), detail);
				}
				if (CommonConstants.THREE_STRING.equals(detail.getSourceType())) {
					threeMap.put(detail.getCertNum() + CommonConstants.DOWN_LINE_STRING + detail.getSocialSecurityAccount() + CommonConstants.DOWN_LINE_STRING + detail.getInsuranceType(), detail);
				}
				if (CommonConstants.FOUR_STRING.equals(detail.getSourceType())) {
					fourMap.put(detail.getCertNum() + CommonConstants.DOWN_LINE_STRING + detail.getSocialSecurityAccount() + CommonConstants.DOWN_LINE_STRING + detail.getInsuranceType(), detail);
				}
			}
			try {

				boolean reFlag = true;
				List<TAutoPaymentDetail> detailListOne = null;
				List<TAutoPaymentDetail> detailListTwo = null;
				List<TAutoPaymentDetail> detailListThree = null;
				List<TAutoPaymentDetail> detailListFour = null;
				URL url;
				String fileTeturnUrl;

				// 解决中文文件名的乱码问题
				if (Common.isNotNull(resultFile)) {
					fileTeturnUrl = resultFile.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inRiChang = conn.getInputStream();
						// 原表ZIP-1日常申报流
						mainAuto.setAttaUrlOne(fileTeturnUrl);
						// 实际读取文件内容
						R<List<TAutoPaymentDetail>> detailROne = this.readZipByPayment(reFlag, oneMap, inRiChang, 1, mainAuto);
						if (detailROne != null && CommonConstants.SUCCESS.equals(detailROne.getCode())) {
							if (detailROne.getData() != null && !detailROne.getData().isEmpty()) {
								detailListOne = detailROne.getData();
								if (detailListOne != null && !detailListOne.isEmpty()) {
									tAutoPaymentDetailService.updateBatchById(detailListOne);
								}
							}
							mainAuto.setRepeatReviewFlag(CommonConstants.TWO_STRING);
							addIdOneTask.setDataStatus(CommonConstants.ONE_STRING);
							tSocialSoldierShenBaoTaskService.updateById(addIdOneTask);
						}
					}
				}
				if (Common.isNotNull(resultFileTwo)) {
					fileTeturnUrl = resultFileTwo.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inRenYuan = conn.getInputStream();

						// 原表ZIP-2单位个人缴费信息查询；
						mainAuto.setAttaUrlTwo(fileTeturnUrl);
						// 实际读取文件内容
						R<List<TAutoPaymentDetail>> detailRTwo = this.readZipByPayment(reFlag, twoMap, inRenYuan, 2, mainAuto);
						if (detailRTwo != null && CommonConstants.SUCCESS.equals(detailRTwo.getCode())) {
							if (detailRTwo.getData() != null && !detailRTwo.getData().isEmpty()) {
								detailListTwo = detailRTwo.getData();
								if (detailListTwo != null && !detailListTwo.isEmpty()) {
									tAutoPaymentDetailService.updateBatchById(detailListTwo);
								}
							}
							mainAuto.setRepeatReviewFlag(CommonConstants.TWO_STRING);
							addIdTwoTask.setDataStatus(CommonConstants.ONE_STRING);
							tSocialSoldierShenBaoTaskService.updateById(addIdTwoTask);
						}
					}
				}
				if (Common.isNotNull(resultFileThree)) {
					fileTeturnUrl = resultFileThree.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inDanWei = conn.getInputStream();
						// 原表ZIP-3单位缴费明细查询
						mainAuto.setAttaUrlThree(fileTeturnUrl);
						// 实际读取文件内容
						R<List<TAutoPaymentDetail>> detailRThree = this.readZipByPayment(reFlag, threeMap, inDanWei, 3, mainAuto);
						if (detailRThree != null && CommonConstants.SUCCESS.equals(detailRThree.getCode())) {
							if (detailRThree.getData() != null && !detailRThree.getData().isEmpty()) {
								detailListThree = detailRThree.getData();
								if (detailListThree != null && !detailListThree.isEmpty()) {
									tAutoPaymentDetailService.updateBatchById(detailListThree);
								}
							}
							mainAuto.setRepeatReviewFlag(CommonConstants.TWO_STRING);
							addIdThreeTask.setDataStatus(CommonConstants.ONE_STRING);
							tSocialSoldierShenBaoTaskService.updateById(addIdThreeTask);
						}
					}
				}
				if ((detailListThree == null || detailListThree.isEmpty()) && Common.isNotNull(resultFileFour)) {
					fileTeturnUrl = resultFileFour.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inDanWeiXiaZai = conn.getInputStream();
						// 原表ZIP-4单位缴费明细下载
						mainAuto.setAttaUrlFour(fileTeturnUrl);
						// 实际读取文件内容
						R<List<TAutoPaymentDetail>> detailRFour = this.readZipByPayment(reFlag, fourMap, inDanWeiXiaZai, 4, mainAuto);
						if (detailRFour != null && CommonConstants.SUCCESS.equals(detailRFour.getCode())) {

							if (detailRFour.getData() != null && !detailRFour.getData().isEmpty()) {
								detailListFour = detailRFour.getData();
								if (detailListFour != null && !detailListFour.isEmpty()) {
									tAutoPaymentDetailService.updateBatchById(detailListFour);
								}
							}
							mainAuto.setRepeatReviewFlag(CommonConstants.TWO_STRING);

							addIdSixTask.setDataStatus(CommonConstants.ONE_STRING);
							tSocialSoldierShenBaoTaskService.updateById(addIdSixTask);
						}
					}
				}
				tAutoPaymentInfoService.updateById(mainAuto);
				// 核验
				if (detailListOne != null && !detailListOne.isEmpty()
						|| detailListTwo != null && !detailListTwo.isEmpty()
						|| detailListThree != null && !detailListThree.isEmpty()
						|| detailListFour != null && !detailListFour.isEmpty()
				) {

					// 复核-核验1：
					baseMapper.getSoldierPaymentErrorInfoOneByRe(mainAuto.getId());
					// 复核-核验2：
					baseMapper.getSoldierPaymentErrorInfoTwoByRe(mainAuto.getId());

					// 重新复核状态
					mainAuto.setRepeatReviewFlag(CommonConstants.TWO_STRING);
					tAutoPaymentInfoService.updateById(mainAuto);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (inRiChang != null) {
						inRiChang.close();
					}
					if (inRenYuan != null) {
						inRenYuan.close();
					}
					if (inDanWei != null) {
						inDanWei.close();
					}
					if (inDanWeiXiaZai != null) {
						inDanWeiXiaZai.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			return R.failed("未找到推送任务，请先推送！");
		}
		return R.ok();
	}

	/**
	 * @Description: 6每月6号定时任务获取社保士兵实缴3张表
	 * @Author: hgw
	 * @Date: 2024-5-30 18:01:11
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> doInnerGetPaymentThree() {
		// 3：实缴1日常申报导出；4：实缴2单位个人缴费信息查询；5：实缴3单位缴费明细查询
		int type = 3;
		TSocialSoldierShenBaoTask addIdOneTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(String.valueOf(type));
		type++;
		TSocialSoldierShenBaoTask addIdTwoTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(String.valueOf(type));
		type++;
		TSocialSoldierShenBaoTask addIdThreeTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(String.valueOf(type));
		type++;
		TSocialSoldierShenBaoTask addIdSixTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(String.valueOf(type));
		String addIdOne = null;
		String addIdOTwo = null;
		String addIdThree = null;
		String addIdSix = null;
		if (addIdOneTask != null && Common.isNotNull(addIdOneTask.getId())) {
			addIdOne = addIdOneTask.getAddId();
		}
		if (addIdTwoTask != null && Common.isNotNull(addIdTwoTask.getId())) {
			addIdOTwo = addIdTwoTask.getAddId();
		}
		if (addIdThreeTask != null && Common.isNotNull(addIdThreeTask.getId())) {
			addIdThree = addIdThreeTask.getAddId();
		}
		if (addIdSixTask != null && Common.isNotNull(addIdSixTask.getId())) {
			addIdSix = addIdSixTask.getAddId();
		}
		HttpURLConnection conn;
		InputStream inRiChang = null;
		InputStream inRenYuan = null;
		InputStream inDanWei = null;
		InputStream inDanWeiXiaZai = null;
		// 1日常申报导出；2单位个人缴费信息查询；3单位缴费明细查询
		R<String> resultFile = socialConfig.getFiveJob(restTemplate, addIdOne, RESULT_ANNEX);
		R<String> resultFileTwo = socialConfig.getFiveJob(restTemplate, addIdOTwo, RESULT_ANNEX);
		R<String> resultFileThree = socialConfig.getFiveJob(restTemplate, addIdThree, RESULT_ANNEX);
		R<String> resultFileFour = socialConfig.getFiveJob(restTemplate, addIdSix, RESULT_ANNEX);
		if (Common.isNotNull(resultFile) || Common.isNotNull(resultFileTwo)
				|| Common.isNotNull(resultFileThree) || Common.isNotNull(resultFileFour)) {
			boolean reFlag = false;
			try {
				// 1查询主表
				TAutoPaymentInfo mainAuto = tAutoPaymentInfoService.getThisMonthMainAuto();
				if (mainAuto == null || Common.isEmpty(mainAuto.getId())) {
					mainAuto = new TAutoPaymentInfo();
					mainAuto.setCreateBy(CommonConstants.ONE_STRING);
					mainAuto.setCreateName("定时任务生成");
					mainAuto.setCreateTime(LocalDateTime.now());
					mainAuto.setSystemReviewFlag(CommonConstants.ZERO_STRING);
					mainAuto.setRepeatReviewFlag(CommonConstants.ZERO_STRING);
					mainAuto.setCreateMonth(DateUtil.getThisMonth());
					mainAuto.setDataOneFlag(CommonConstants.ZERO_STRING);
					mainAuto.setDataTwoFlag(CommonConstants.ZERO_STRING);
					mainAuto.setDataThreeFlag(CommonConstants.ZERO_STRING);
					tAutoPaymentInfoService.save(mainAuto);
				}

				List<TAutoPaymentDetail> detailListOne = null;
				List<TAutoPaymentDetail> detailListTwo = null;
				List<TAutoPaymentDetail> detailListThree = null;
				List<TAutoPaymentDetail> detailListFour = null;
				URL url;
				String fileTeturnUrl;
				// 解决中文文件名的乱码问题
				if (Common.isNotNull(resultFile)) {
					fileTeturnUrl = resultFile.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inRiChang = conn.getInputStream();
						// 原表ZIP-1日常申报流
						mainAuto.setAttaUrlOne(fileTeturnUrl);
						mainAuto.setDataOneFlag(CommonConstants.ONE_STRING);
						// 清空明细表
						tAutoPaymentDetailService.deleteByParentId(mainAuto.getId(), 1);
						// 实际读取文件内容
						R<List<TAutoPaymentDetail>> detailROne = this.readZipByPayment(reFlag, null, inRiChang, 1, mainAuto);
						if (detailROne != null && CommonConstants.SUCCESS.equals(detailROne.getCode())) {
							if (detailROne.getData() != null && !detailROne.getData().isEmpty()) {
								detailListOne = detailROne.getData();
								if (detailListOne != null && !detailListOne.isEmpty()) {
									tAutoPaymentDetailService.saveBatch(detailListOne);
								}
							}
							addIdOneTask.setDataStatus(CommonConstants.ONE_STRING);
							tSocialSoldierShenBaoTaskService.updateById(addIdOneTask);
							mainAuto.setDataOneFlag(CommonConstants.TWO_STRING);
						} else {
							mainAuto.setDataOneFlag(CommonConstants.THREE_STRING);
						}
					}
				}
				if (Common.isNotNull(resultFileTwo)) {
					fileTeturnUrl = resultFileTwo.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inRenYuan = conn.getInputStream();
						// 原表ZIP-2单位个人缴费信息查询；
						mainAuto.setAttaUrlTwo(fileTeturnUrl);
						mainAuto.setDataTwoFlag(CommonConstants.ONE_STRING);
						// 清空明细表
						tAutoPaymentDetailService.deleteByParentId(mainAuto.getId(), 2);
						// 实际读取文件内容
						R<List<TAutoPaymentDetail>> detailRTwo = this.readZipByPayment(reFlag, null, inRenYuan, 2, mainAuto);

						if (detailRTwo != null && CommonConstants.SUCCESS.equals(detailRTwo.getCode())) {
							if (detailRTwo.getData() != null && !detailRTwo.getData().isEmpty()) {
								detailListTwo = detailRTwo.getData();
								if (detailListTwo != null && !detailListTwo.isEmpty()) {
									tAutoPaymentDetailService.saveBatch(detailListTwo);
								}
							}
							addIdTwoTask.setDataStatus(CommonConstants.ONE_STRING);
							tSocialSoldierShenBaoTaskService.updateById(addIdTwoTask);
							mainAuto.setDataTwoFlag(CommonConstants.TWO_STRING);
						} else {
							mainAuto.setDataTwoFlag(CommonConstants.THREE_STRING);
						}
					}
				}
				if (Common.isNotNull(resultFileThree)) {
					fileTeturnUrl = resultFileThree.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inDanWei = conn.getInputStream();
						// 原表ZIP-3单位缴费明细查询
						mainAuto.setAttaUrlThree(fileTeturnUrl);
						mainAuto.setDataThreeFlag(CommonConstants.ONE_STRING);
						// 清空明细表
						tAutoPaymentDetailService.deleteByParentId(mainAuto.getId(), 3);
						// 实际读取文件内容
						R<List<TAutoPaymentDetail>> detailRThree = this.readZipByPayment(reFlag, null, inDanWei, 3, mainAuto);

						if (detailRThree != null && CommonConstants.SUCCESS.equals(detailRThree.getCode())) {
							if (detailRThree.getData() != null && !detailRThree.getData().isEmpty()) {
								detailListThree = detailRThree.getData();
								if (detailListThree != null && !detailListThree.isEmpty()) {
									tAutoPaymentDetailService.saveBatch(detailListThree);
								}
							}
							addIdThreeTask.setDataStatus(CommonConstants.ONE_STRING);
							tSocialSoldierShenBaoTaskService.updateById(addIdThreeTask);
							mainAuto.setDataThreeFlag(CommonConstants.TWO_STRING);
						} else {
							mainAuto.setDataThreeFlag(CommonConstants.THREE_STRING);
						}
					}
				}
				if ((detailListThree == null || detailListThree.isEmpty()) && Common.isNotNull(resultFileFour)) {
					fileTeturnUrl = resultFileFour.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inDanWeiXiaZai = conn.getInputStream();
						// 原表ZIP-4单位缴费明细下载
						mainAuto.setAttaUrlFour(fileTeturnUrl);
						mainAuto.setDataThreeFlag(CommonConstants.ONE_STRING);
						// 清空明细表
						tAutoPaymentDetailService.deleteByParentId(mainAuto.getId(), 4);
						// 实际读取文件内容
						R<List<TAutoPaymentDetail>> detailRFour = this.readZipByPayment(reFlag, null, inDanWeiXiaZai, 4, mainAuto);
						if (detailRFour != null && CommonConstants.SUCCESS.equals(detailRFour.getCode())) {
							if (detailRFour.getData() != null && !detailRFour.getData().isEmpty()) {
								detailListFour = detailRFour.getData();
								if (detailListFour != null && !detailListFour.isEmpty()) {
									tAutoPaymentDetailService.saveBatch(detailListFour);
								}
							}
							addIdSixTask.setDataStatus(CommonConstants.ONE_STRING);
							tSocialSoldierShenBaoTaskService.updateById(addIdSixTask);
							mainAuto.setDataThreeFlag(CommonConstants.TWO_STRING);
						} else {
							mainAuto.setDataThreeFlag(CommonConstants.THREE_STRING);
						}
					}
				}
				tAutoPaymentInfoService.updateById(mainAuto);
				// 核验
				if (detailListOne != null && !detailListOne.isEmpty()
						|| detailListTwo != null && !detailListTwo.isEmpty()
						|| detailListThree != null && !detailListThree.isEmpty()
						|| detailListFour != null && !detailListFour.isEmpty()
				) {
					// 核验1：
					baseMapper.getSoldierPaymentErrorInfoOne(mainAuto.getId());
					// 核验2：
					baseMapper.getSoldierPaymentErrorInfoTwo(mainAuto.getId());
					mainAuto.setSystemReviewFlag(CommonConstants.TWO_STRING);
					tAutoPaymentInfoService.updateById(mainAuto);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (inRiChang != null) {
						inRiChang.close();
					}
					if (inRenYuan != null) {
						inRenYuan.close();
					}
					if (inDanWei != null) {
						inDanWei.close();
					}
					if (inDanWeiXiaZai != null) {
						inDanWeiXiaZai.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return R.ok();
	}

	@Override
	public R<String> getZip(MultipartFile zipFile) {
		// 3：实缴1日常申报导出；4：实缴2单位个人缴费信息查询；5：实缴3单位缴费明细查询
		TSocialSoldierShenBaoTask addIdOneTask = tSocialSoldierShenBaoTaskService.getSoldierTaskAddIdByType(CommonConstants.THREE_STRING);
		String addIdOne = null;
		if (addIdOneTask != null && Common.isNotNull(addIdOneTask.getId())) {
			addIdOne = addIdOneTask.getAddId();
		}
		HttpURLConnection conn;
		InputStream inRiChang = null;
		// 1日常申报导出；2单位个人缴费信息查询；3单位缴费明细查询
		R<String> resultFile = socialConfig.getFiveJob(restTemplate, addIdOne, RESULT_ANNEX);
		if (Common.isNotNull(resultFile)) {
			try {
				URL url;
				String fileTeturnUrl;
				// 解决中文文件名的乱码问题
				if (Common.isNotNull(resultFile)) {
					fileTeturnUrl = resultFile.getData();
					if (Common.isNotNull(fileTeturnUrl)) {
						fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
						url = new URL(fileTeturnUrl);
						conn = (HttpURLConnection) url.openConnection();
						//设置超时间为30秒
						conn.setConnectTimeout(30 * 1000);
						inRiChang = conn.getInputStream();
						// 原表ZIP-1日常申报流
						this.readZipByPayment(inRiChang, zipFile);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return R.ok();
	}

	/**
	 * @Description: 实验接口使用的，不删除
	 * @Author: hgw
	 * @Date: 2024/6/13 17:45
	 * @return: void
	 **/
	public void readZipByPayment(InputStream inputStream, MultipartFile zipFileOld) {
		ZipFile zipFile = null;
		Workbook workbook = null;
		InputStream is = null;
		try {
			String pathName = System.getProperty("java.io.tmpdir");
			String dec = System.getProperty("java.io.tmpdir");
			String pname = System.currentTimeMillis() + "_实缴4张表";
			pathName = pathName + pname;
			File file = new File(pathName);
			FileUtils.copyInputStreamToFile(inputStream, file);
			/*String fileName = System.currentTimeMillis() + "_" + file.getName()
			boolean flag = ossUtil.uploadFileByFile(file, fileName, null)*/
			zipFile = new ZipFile(file, CharsetUtil.CHARSET_GBK);
			Enumeration<?> entries = zipFile.entries();

			ZipEntry entry;
			String empInfo;
			while (entries.hasMoreElements()) {
				entry = (ZipEntry) entries.nextElement();
				// 如果是文件夹，就创建个文件夹
				if (!entry.isDirectory()) {
					//添加进filesName
					empInfo = entry.getName();
					// 将压缩文件内容写入到这个文件中
					is = zipFile.getInputStream(entry);

					workbook = WorkbookFactory.create(is);
					Sheet sheet = workbook.getSheetAt(0);
					Row row;
					String cellValue;
					int nameNum = 0;

					// 循环每个sheet
					if (sheet != null && Common.isNotNull(sheet.getSheetName())) {
						for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
							row = sheet.getRow(rowNum);
							// 循环当前行的内容
							if (rowNum == 0) {
								for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
									cellValue = this.getCellValue(row, cellNum);
									if ("姓名".equals(cellValue)) {
										nameNum = cellNum;
									}
								}
							} else if (rowNum < 10) {
								cellValue = this.getCellValue(row, nameNum);
							}
						}
					}
					// 关流顺序，先打开的后关闭
					is.close();
				}
			}

			//解析完成删除本次解析中生成的文件  删除此目录下的所有文件
			deleteFolder(dec);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (workbook != null) {
					workbook.close();
				}
				if (is != null) {
					is.close();
				}
				if (zipFile != null) {
					zipFile.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 根据路径删除指定的目录或文件，无论存在与否
	 *
	 * @param path 要删除的目录或文件路径
	 * @return 删除成功返回 true，否则返回 false
	 */
	public static void deleteFolder(String path) {
		File file = new File(path);
		// 判断目录或文件是否存在
		if (file.exists()) {
			// 判断是否为文件
			if (file.isFile()) {  // 为文件时调用删除文件方法
				deleteFile(path);
			} else {  // 为目录时调用删除目录方法
				deleteDirectory(path);
			}
		}
	}

	/**
	 * 删除单个文件
	 */
	private static boolean deleteFile(String path) {
		File file = new File(path);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			return true;
		}
		return false;
	}

	/**
	 * 删除目录（文件夹）以及目录下的文件
	 */
	private static boolean deleteDirectory(String path) {
		//如果path不以文件分隔符结尾，自动添加文件分隔符
		if (!path.endsWith(File.separator)) {
			path = path + File.separator;
		}
		File dirFile = new File(path);
		//如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		//删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (File file : files) {
			//删除子文件
			if (file.isFile()) {
				flag = deleteFile(file.getAbsolutePath());
			} //删除子目录
			else {
				flag = deleteDirectory(file.getAbsolutePath());
			}
			if (!flag) {
				break;
			}
		}
		if (!flag) {
			return false;
		}
		//删除当前目录
		return dirFile.delete();
	}

	/**
	 * @param reFlag true :复核
	 * @param oldMap 被标记的map
	 * @param type   1日常申报导出；2单位个人缴费信息查询；3单位缴费明细查询
	 * @Description: 读取实缴3张表
	 * @Author: hgw
	 * @Date: 2024/6/3 18:17
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.List < com.yifu.cloud.plus.v1.yifu.social.entity.TAutoPaymentDetail>>
	 **/
	public R<List<TAutoPaymentDetail>> readZipByPayment(boolean reFlag, Map<String, TAutoPaymentDetail> oldMap
			, InputStream inputStream, int type, TAutoPaymentInfo mainAuto) {
		TAutoPaymentDetail oldDetail;
		TAutoPaymentDetail detail;
		TAutoPaymentDetail detailPerson;
		List<TAutoPaymentDetail> voList = new ArrayList<>();
		ZipFile zipFile = null;
		Workbook workbook = null;
		InputStream is = null;
		Sheet sheet = null;
		Row row;
		// 塞生成月份所用
		String nowMonth = DateUtil.getThisMonth();
		// 资源类型：1日常申报导出；2单位个人缴费信息查询；3单位缴费明细查询
		String sourceType = String.valueOf(type);
		String dec = System.getProperty("java.io.tmpdir");
		try {
			String pathName = dec;
			String pname = System.currentTimeMillis() + "_实缴4张表";
			pathName = pathName + pname;
			File file = new File(pathName);
			FileUtils.copyInputStreamToFile(inputStream, file);
			/*String fileName =
			System.currentTimeMillis() + "_" + file.getName()
			boolean flag = ossUtil.uploadFileByFile(file, fileName, null)*/
			zipFile = new ZipFile(file, CharsetUtil.CHARSET_GBK);
			Enumeration<?> entries = zipFile.entries();

			ZipEntry entry;
			String name;
			while (entries.hasMoreElements()) {
				entry = (ZipEntry) entries.nextElement();
				// 如果是文件夹，就创建个文件夹
				if (!entry.isDirectory()) {
					name = entry.getName();
					if (Common.isNotNull(name) && (name.endsWith(".xls") || name.endsWith(".xlsx")) &&
							((type != 2 && (name.contains("全部") || name.contains("汇总"))) || (type == 2 && name.contains("单位个人缴费信息")))) {
						is = zipFile.getInputStream(entry);
						workbook = WorkbookFactory.create(is);
						sheet = workbook.getSheetAt(0);
						// 每个单元格内容
						String cellValue;
						// 错误信息 所在列
						Integer errorInfoNum = null;
						// 1、2姓名3人员姓名 所在列
						Integer empNameNum = null;
						// 1证件号码2社会保障号码 所在列
						Integer certNumNum = null;
						// 1缴费基数2个人缴费基数 所在列
						Integer paymentBaseNum = null;
						// 应缴费额 所在列
						Integer payLimitNum = null;
						// 单位缴费额 所在列
						Integer unitLimitNum = null;
						// 单位利息 所在列
						Integer unitLiXiNum = null;
						// 单位滞纳金 所在列
						Integer unitZhiNaJinNum = null;
						// 个人缴费额 所在列
						Integer personLimitNum = null;
						// 单位利息 所在列
						Integer personLiXiNum = null;
						// 单位滞纳金 所在列
						Integer personZhiNaJinNum = null;
						// 1险种2参保险种3险种类型 所在列
						Integer insuranceTypeNum = null;
						// 单位名称（社保户） 所在列
						Integer socialSecurityAccountNum = null;
						// 1费款所属期2缴费年月3起始费款所属期（社保缴纳月份） 所在列
						Integer payMonthNum = null;
						// 2生成月份3对应费款所属期
						Integer createMonthNum = null;
						// 3缴费总金额
						Integer allMoneyNum = null;
						// 3参保身份
						Integer shenFenNum = null;

						// 错误信息
						String errorInfo;
						// 姓名
						String empName;
						// 证件号码
						String certNum;
						// 缴费基数
						String paymentBase;
						// 应缴费额
						String payLimit;

						// 单位缴费额
						String unitLimit;
						// 单位利息
						String unitLiXi;
						// 单位滞纳金
						String unitZhiNaJin;
						// 个人缴费额
						String personLimit;
						// 单位利息
						String personLiXi;
						// 单位滞纳金
						String personZhiNaJin;

						// 1险种2参保险种
						String insuranceType;
						// 单位名称（社保户）
						String socialSecurityAccount;
						// 费款所属期（社保缴纳月份）
						String payMonth;
						// 2业务年月（社保生成月份）
						String createMonth;
						// 3缴费总金额
						String allMoney;
						// 3参保身份
						String shenFen;
						// 金额累计使用
						BigDecimal money;

						// 循环每个sheet
						if (sheet != null && Common.isNotNull(sheet.getSheetName())) {
							for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
								row = sheet.getRow(rowNum);
								if (row != null) {
									// 初始化
									empName = null;
									certNum = null;
									paymentBase = null;
									payLimit = null;
									insuranceType = null;
									socialSecurityAccount = null;
									payMonth = null;
									createMonth = null;
									unitLimit = null;
									unitLiXi = null;
									unitZhiNaJin = null;
									personLimit = null;
									personLiXi = null;
									personZhiNaJin = null;
									allMoney = null;
									shenFen = null;
									money = null;
									// 循环当前行的内容
									if (rowNum == 0) {
										for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
											cellValue = this.getCellValue(row, cellNum);
											if ("错误信息".equals(cellValue)) {
												errorInfoNum = cellNum;
											} else if ("姓名".equals(cellValue) || "人员姓名".equals(cellValue)) {
												empNameNum = cellNum;
											} else if ("证件号码".equals(cellValue) || "社会保障号码".equals(cellValue)) {
												certNumNum = cellNum;
											} else if ("缴费基数".equals(cellValue) || "个人缴费基数".equals(cellValue)) {
												paymentBaseNum = cellNum;
											} else if ("应缴费额".equals(cellValue)) {
												payLimitNum = cellNum;
											} else if ("缴费总金额".equals(cellValue)) {
												allMoneyNum = cellNum;
											} else if ("参保身份".equals(cellValue)) {
												shenFenNum = cellNum;
											}
											// 2单位个人缴费信息查询 独有
											else if ("单位缴费额".equals(cellValue) || "单位实缴金额".equals(cellValue)) {
												unitLimitNum = cellNum;
											} else if ("单位利息".equals(cellValue)) {
												unitLiXiNum = cellNum;
											} else if ("单位滞纳金".equals(cellValue)) {
												unitZhiNaJinNum = cellNum;
											} else if ("个人缴费额".equals(cellValue) || "个人实缴金额".equals(cellValue)) {
												personLimitNum = cellNum;
											} else if ("个人利息".equals(cellValue)) {
												personLiXiNum = cellNum;
											} else if ("个人滞纳金".equals(cellValue)) {
												personZhiNaJinNum = cellNum;
											} else if ("险种".equals(cellValue) || "参保险种".equals(cellValue) || "险种类型".equals(cellValue)) {
												insuranceTypeNum = cellNum;
											} else if ("单位名称".equals(cellValue)) {
												socialSecurityAccountNum = cellNum;
											} else if ("费款所属期".equals(cellValue) || "缴费年月".equals(cellValue) || "起始费款所属期".equals(cellValue)) {
												payMonthNum = cellNum;
											} else if ("业务年月".equals(cellValue) || "对应费款所属期".equals(cellValue)) {
												createMonthNum = cellNum;
											}
										}
									} else {
										if (Common.isEmpty(errorInfoNum) && Common.isEmpty(certNumNum)) {
											return R.failed("未找到对应表头！");
										} else {
											if (Common.isNotNull(errorInfoNum)) {
												errorInfo = getCellValue(row, errorInfoNum);
												return R.failed("数据错误：" + errorInfo);
											} else {
												// 参保身份类别为退休和缴费总金额为0,2者有其一则不合并
												if (Common.isNotNull(allMoneyNum)) {
													allMoney = getCellValue(row, allMoneyNum);
													if (Common.isNotNull(allMoney) && BigDecimal.ZERO.equals(this.getBigDecimal(allMoney))) {
														continue;
													}
												}
												if (Common.isNotNull(shenFenNum)) {
													shenFen = getCellValue(row, shenFenNum);
													if (Common.isNotNull(shenFen) && "退休".equals(shenFen.trim())) {
														continue;
													}
												}
												if (Common.isNotNull(empNameNum)) {
													empName = getCellValue(row, empNameNum);
												}
												if (Common.isNotNull(certNumNum)) {
													certNum = getCellValue(row, certNumNum);
													if (Common.isEmpty(certNum) || certNum.contains("合计")) {
														break;
													}
												} else {
													break;
												}
												if (Common.isNotNull(paymentBaseNum)) {
													paymentBase = getCellValue(row, paymentBaseNum);
												}
												if (Common.isNotNull(payLimitNum)) {
													payLimit = getCellValue(row, payLimitNum);
												}

												if (Common.isNotNull(unitLimitNum)) {
													unitLimit = getCellValue(row, unitLimitNum);
												}
												if (Common.isNotNull(unitLiXiNum)) {
													unitLiXi = getCellValue(row, unitLiXiNum);
												}
												if (Common.isNotNull(unitZhiNaJinNum)) {
													unitZhiNaJin = getCellValue(row, unitZhiNaJinNum);
												}
												if (Common.isNotNull(personLimitNum)) {
													personLimit = getCellValue(row, personLimitNum);
												}
												if (Common.isNotNull(personLiXiNum)) {
													personLiXi = getCellValue(row, personLiXiNum);
												}
												if (Common.isNotNull(personZhiNaJinNum)) {
													personZhiNaJin = getCellValue(row, personZhiNaJinNum);
												}
												if (Common.isNotNull(insuranceTypeNum)) {
													insuranceType = getCellValue(row, insuranceTypeNum);
												}
												if (Common.isNotNull(socialSecurityAccountNum)) {
													socialSecurityAccount = getCellValue(row, socialSecurityAccountNum);
												}
												if (Common.isNotNull(payMonthNum)) {
													payMonth = getCellValue(row, payMonthNum);
													if (Common.isNotNull(payMonth)) {
														payMonth = payMonth.replace("-", "");
													}
												}
												if (Common.isNotNull(createMonthNum)) {
													createMonth = getCellValue(row, createMonthNum);
												}
												detail = new TAutoPaymentDetail();
												detail.setParentId(mainAuto.getId());
												detail.setSourceType(sourceType);
												detail.setEmpName(empName);
												detail.setCertNum(certNum);
												if (Common.isNotNull(paymentBase)) {
													detail.setPaymentBase(this.getBigDecimal(paymentBase));
												}
												if (Common.isNotNull(payLimit)) {
													detail.setPayLimit(this.getBigDecimal(payLimit));
												}
												if (Common.isNotNull(unitLimit)) {
													money = this.getBigDecimal(unitLimit);
													if (Common.isNotNull(unitLiXi)) {
														money = BigDecimalUtils.safeAdd(money, this.getBigDecimal(unitLiXi));
													}
													if (Common.isNotNull(unitZhiNaJin)) {
														money = BigDecimalUtils.safeAdd(money, this.getBigDecimal(unitZhiNaJin));
													}
													detail.setPayLimit(money);
												}
												detail.setInsuranceType(insuranceType);
												if (Common.isNotNull(unitLimit)) {
													detail.setInsuranceType("单位" + insuranceType);
												}
												detail.setSocialSecurityAccount(socialSecurityAccount);
												detail.setPayMonth(payMonth);
												if (Common.isNotNull(createMonth)) {
													detail.setCreateMonth(createMonth);
												} else {
													detail.setCreateMonth(nowMonth);
												}
												if (reFlag) {
													if (oldMap != null) {
														// 复核使用的
														oldDetail = oldMap.get(detail.getCertNum() + CommonConstants.DOWN_LINE_STRING
																+ detail.getSocialSecurityAccount() + CommonConstants.DOWN_LINE_STRING
																+ detail.getInsuranceType());
														if (oldDetail != null) {
															detail.setId(oldDetail.getId());
															voList.add(detail);
														}
													}
												} else {
													voList.add(detail);
												}
												// 个人的拆为第二条
												if (Common.isNotNull(personLimit)) {
													money = this.getBigDecimal(personLimit);
													if (Common.isNotNull(personLiXi)) {
														money = BigDecimalUtils.safeAdd(money, this.getBigDecimal(personLiXi));
													}
													if (Common.isNotNull(personZhiNaJin)) {
														money = BigDecimalUtils.safeAdd(money, this.getBigDecimal(personZhiNaJin));
													}
													detailPerson = new TAutoPaymentDetail();
													detailPerson.setParentId(mainAuto.getId());
													detailPerson.setSourceType(sourceType);
													detailPerson.setPayLimit(money);
													detailPerson.setEmpName(empName);
													detailPerson.setCertNum(certNum);
													if (Common.isNotNull(paymentBase)) {
														detailPerson.setPaymentBase(this.getBigDecimal(paymentBase));
													}
													detailPerson.setInsuranceType("个人" + insuranceType);
													detailPerson.setSocialSecurityAccount(socialSecurityAccount);
													detailPerson.setPayMonth(payMonth);
													if (Common.isNotNull(createMonth)) {
														detailPerson.setCreateMonth(createMonth);
													} else {
														detailPerson.setCreateMonth(nowMonth);
													}
													if (reFlag) {
														if (oldMap != null) {
															// 复核使用的
															oldDetail = oldMap.get(detailPerson.getCertNum() + CommonConstants.DOWN_LINE_STRING
																	+ detailPerson.getSocialSecurityAccount() + CommonConstants.DOWN_LINE_STRING
																	+ detailPerson.getInsuranceType());
															if (oldDetail != null) {
																detailPerson.setId(oldDetail.getId());
																voList.add(detailPerson);
															}
														}
													} else {
														voList.add(detailPerson);
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				//解析完成删除本次解析中生成的文件  删除此目录下的所有文件
				deleteFolder(dec);
				if (workbook != null) {
					workbook.close();
				}
				if (is != null) {
					is.close();
				}
				if (zipFile != null) {
					zipFile.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return R.ok(voList);
	}

	private BigDecimal getBigDecimal(String paymentBase) {
		if (paymentBase.contains(",")) {
			paymentBase = paymentBase.replace(",", "");
		}
		try {
			return new BigDecimal(paymentBase);
		} catch (Exception e) {
			log.error("社保士兵的文件里有错误的数字，需要调整代码：" + paymentBase);
			return new BigDecimal("-1");
		}
	}

	/**
	 * @Description: 解码URL
	 * @Author: hgw
	 * @Date: 2024/6/3 11:01
	 * @return: java.lang.String
	 **/
	private String getEncodeUrl(String fileTeturnUrl) {
		String dowloadUrl = fileTeturnUrl;
		int indexOf = fileTeturnUrl.lastIndexOf("/") + 1;
		fileTeturnUrl = fileTeturnUrl.substring(indexOf);
		try {
			fileTeturnUrl = URLEncoder.encode(fileTeturnUrl, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.info("编码异常！");
		}
		dowloadUrl = dowloadUrl.substring(0, indexOf) + fileTeturnUrl;
		return dowloadUrl;
	}

	/**
	 * @Description: 6 查看社保士兵审核结果查询的反馈情况
	 * @Author: hgw
	 * @Date: 2024/5/11 15:08
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> getSixJobByAudit() {
		// 获取所有需要反馈的任务id
		List<TSocialInfo> socialList = tSocialInfoService.getSocialSoldierYgsByAudit();
		List<TSocialInfo> socialYsdList = tSocialInfoService.getSocialSoldierYsdByAudit();
		if (socialYsdList != null && !socialYsdList.isEmpty()) {
			if (socialList != null && !socialList.isEmpty()) {
				socialList.addAll(socialYsdList);
			} else {
				socialList = socialYsdList;
			}
		}

		if (socialList != null && !socialList.isEmpty()) {
			Map<String, TSocialInfo> idCardMap = new HashMap<>();
			Set<String> addIdSet = new HashSet<>();
			for (TSocialInfo socialInfo : socialList) {
				if (Common.isNotNull(socialInfo.getYgsAddId())) {
					addIdSet.add(socialInfo.getYgsAddId());
					idCardMap.put(socialInfo.getYgsAddId() + CommonConstants.DOWN_LINE_STRING + socialInfo.getEmpIdcard(), socialInfo);
				}
				if (Common.isNotNull(socialInfo.getYsdAddId())) {
					addIdSet.add(socialInfo.getYsdAddId());
					idCardMap.put(socialInfo.getYsdAddId() + CommonConstants.DOWN_LINE_STRING + socialInfo.getEmpIdcard(), socialInfo);
				}
			}
			HttpURLConnection conn;
			InputStream in = null;
			Map<String, FailReasonConfig> errorMap = failReasonConfigService.getFailReasonMap();
			if (!addIdSet.isEmpty()) {
				for (String doAddId : addIdSet) {
					R<String> resultFile = socialConfig.getFiveJob(restTemplate, doAddId, RESULT_ANNEX);
					log.info("resultFileByAudit=" + resultFile);
					try {
						// 解决中文文件名的乱码问题
						String fileTeturnUrl = resultFile.getData();
						if (Common.isNotNull(fileTeturnUrl)) {
							fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
							URL url = new URL(fileTeturnUrl);
							conn = (HttpURLConnection) url.openConnection();
							//设置超时间为30秒
							conn.setConnectTimeout(30 * 1000);
							in = conn.getInputStream();
							// 实际读取文件内容
							this.readZip(in, idCardMap, errorMap, doAddId);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (in != null) {
							try {
								in.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
		return R.ok();
	}

	public R<List<TSocialSoldierReturnAuditErrorVo>> readZip(InputStream inputStream, Map<String, TSocialInfo> idCardMap
			, Map<String, FailReasonConfig> errorMap, String doAddId) {
		TSocialSoldierReturnAuditErrorVo vo;
		List<TSocialSoldierReturnAuditErrorVo> voList = new ArrayList<>();
		XSSFWorkbook sheets = null;
		ZipInputStream zin = null;
		BufferedInputStream bs = null;
		try {
			zin = new ZipInputStream(inputStream, CharsetUtil.CHARSET_GBK);
			bs = new BufferedInputStream(zin);
			byte[] bytes;
			ZipEntry ze;
			//循环读取压缩包里面的文件
			while ((ze = zin.getNextEntry()) != null) {
				String name = ze.getName();
				if ((ze.toString().endsWith(".xls") || ze.toString().endsWith(".xlsx")) && Common.isNotNull(name) && name.contains("汇总")) {
					//读取每个文件的字节，并放进数组
					bytes = new byte[(int) ze.getSize()];
					bs.read(bytes, 0, (int) ze.getSize());
					//将文件转成流
					InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
					sheets = new XSSFWorkbook(byteArrayInputStream);
					// sheet
					XSSFSheet sheetAt = sheets.getSheetAt(0);
					XSSFRow row;
					// 每个单元格内容
					String cellValue;
					XSSFCell cell;

					// 循环每个sheet
					if (sheetAt != null && Common.isNotNull(sheetAt.getSheetName())) {
						// 错误信息 所在列
						Integer errorInfoNum = null;
						// 企业名称 所在列
						Integer companyNameNum = null;
						// 证件号码 所在列
						Integer idCardNum = null;
						// 姓名 所在列
						Integer empNameNum = null;
						// 审核状态 所在列
						Integer auditStatusNum = null;
						// 审核意见 所在列
						Integer ysdRemarkNum = null;
						// 操作 所在列
						Integer ygsOperationNum = null;

						// 错误信息
						String errorInfo;
						// 企业名称
						String companyName;
						// 证件号码
						String idCard;
						// 姓名
						String empName;
						// 审核状态 ： // 空、待审核、撤回或作废数据、审核不通过、审核通过
						String auditStatus;
						// 审核意见
						String ysdRemark;
						// 操作
						String ygsOperation;

						for (int rowNum = 0; rowNum <= sheetAt.getLastRowNum(); rowNum++) {
							row = sheetAt.getRow(rowNum);
							if (row != null) {
								// 初始化
								ysdRemark = null;
								ygsOperation = null;
								// 循环当前行的内容
								if (rowNum == 0) {
									for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
										// 标题行
										cellValue = this.getCellValue(row, cellNum);
										if ("错误信息".equals(cellValue)) {
											errorInfoNum = cellNum;
										} else if ("企业名称".equals(cellValue)) {
											companyNameNum = cellNum;
										} else if ("证件号码".equals(cellValue)) {
											idCardNum = cellNum;
										} else if ("姓名".equals(cellValue)) {
											empNameNum = cellNum;
										} else if ("审核状态".equals(cellValue)) {
											auditStatusNum = cellNum;
										} else if ("审核意见".equals(cellValue)) {
											// 医保
											ysdRemarkNum = cellNum;
										} else if ("操作".equals(cellValue)) {
											// 社保
											ygsOperationNum = cellNum;
										}
									}
								} else {
									if (Common.isEmpty(auditStatusNum) && Common.isEmpty(idCardNum)) {
										return R.failed("未找到对应表头！");
									} else {
										if (Common.isNotNull(errorInfoNum)) {
											errorInfo = getCellValue(row, errorInfoNum);
											vo = new TSocialSoldierReturnAuditErrorVo();
											vo.setErrorInfo(errorInfo);
											voList.add(vo);
											return R.failed("数据错误！！");
										} else {
											if (Common.isNotNull(idCardNum) && Common.isNotNull(companyNameNum)
													&& Common.isNotNull(empNameNum) && Common.isNotNull(auditStatusNum)) {
												companyName = getCellValue(row, companyNameNum);
												idCard = getCellValue(row, idCardNum);
												empName = getCellValue(row, empNameNum);
												auditStatus = getCellValue(row, auditStatusNum);
												if (Common.isNotNull(ysdRemarkNum)) {
													ysdRemark = getCellValue(row, ysdRemarkNum);
												}
												if (Common.isNotNull(ygsOperationNum)) {
													ygsOperation = getCellValue(row, ygsOperationNum);
												}
												vo = new TSocialSoldierReturnAuditErrorVo();
												vo.setCompanyName(companyName);
												vo.setIdCard(idCard);
												vo.setEmpName(empName);
												vo.setAuditStatus(auditStatus);
												vo.setYsdRemark(ysdRemark);
												vo.setYgsOperation(ygsOperation);
												voList.add(vo);
											}
										}
									}
								}
							}
						}
					}
				}
			}
			zin.closeEntry();
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			if (sheets != null) {
				try {
					sheets.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		} finally {
			try {
				if (sheets != null) {
					sheets.close();
				}
				if (zin != null) {
					zin.close();
				}
				if (bs != null) {
					bs.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		if (!voList.isEmpty()) {
			importTSocialSoldierByAudit(voList, idCardMap, errorMap, doAddId);
		}
		return R.ok(voList);
	}

	/**
	 * @param addId
	 * @Description: 5 查看任务进度
	 * @Author: hgw
	 * @Date: 2024/5/11 15:08
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> getFiveJob(String addId) {
		List<TSocialInfo> socialList;
		if (Common.isEmpty(addId)) {
			// 获取所有需要反馈的任务id
			socialList = tSocialInfoService.getSocialSoldierYgsAll();
			List<TSocialInfo> socialYsdList = tSocialInfoService.getSocialSoldierYsdAll();
			if (socialYsdList != null && !socialYsdList.isEmpty()) {
				if (socialList != null && !socialList.isEmpty()) {
					socialList.addAll(socialYsdList);
				} else {
					socialList = socialYsdList;
				}
			}
		} else {
			socialList = tSocialInfoService.getSocialSoldierByAddId(addId);
		}
		if (socialList != null && !socialList.isEmpty()) {
			Map<String, TSocialInfo> idCardMap = new HashMap<>();
			Set<String> addIdSet = new HashSet<>();
			for (TSocialInfo socialInfo : socialList) {
				if (Common.isNotNull(socialInfo.getYgsAddId())) {
					addIdSet.add(socialInfo.getYgsAddId());
					idCardMap.put(socialInfo.getYgsAddId() + CommonConstants.DOWN_LINE_STRING + socialInfo.getEmpIdcard(), socialInfo);
				}
				if (Common.isNotNull(socialInfo.getYsdAddId())) {
					addIdSet.add(socialInfo.getYsdAddId());
					idCardMap.put(socialInfo.getYsdAddId() + CommonConstants.DOWN_LINE_STRING + socialInfo.getEmpIdcard(), socialInfo);
				}
			}
			HttpURLConnection conn;
			InputStream in = null;
			Map<String, FailReasonConfig> errorMap = failReasonConfigService.getFailReasonMap();
			if (!addIdSet.isEmpty()) {
				for (String doAddId : addIdSet) {
					R<String> resultFile = socialConfig.getFiveJob(restTemplate, doAddId, "resultFile");
					log.info("resultFile=" + resultFile);
					try {
						// 解决中文文件名的乱码问题
						String fileTeturnUrl = resultFile.getData();
						if (Common.isNotNull(fileTeturnUrl)) {
							fileTeturnUrl = this.getEncodeUrl(fileTeturnUrl);
							URL url = new URL(fileTeturnUrl);
							conn = (HttpURLConnection) url.openConnection();
							//设置超时间为30秒
							conn.setConnectTimeout(30 * 1000);
							in = conn.getInputStream();
							// 实际读取文件内容
							this.readXls(in, idCardMap, errorMap, doAddId);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (in != null) {
							try {
								in.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
		return R.ok();
	}

	public R<List<TSocialSoldierReturnErrorVo>> readXls(InputStream inputStream, Map<String, TSocialInfo> idCardMap
			, Map<String, FailReasonConfig> errorMap, String doAddId) {
		TSocialSoldierReturnErrorVo vo;
		List<TSocialSoldierReturnErrorVo> voList = new ArrayList<>();
		HSSFWorkbook sheets = null;
		try {
			sheets = new HSSFWorkbook(inputStream);
			// sheet
			HSSFSheet sheetAt = sheets.getSheetAt(0);
			HSSFRow row;
			// 每个单元格内容
			String cellValue;
			// 内容行
			int dataRow;
			HSSFCell cell;
			// 循环每个sheet
			if (sheetAt != null && Common.isNotNull(sheetAt.getSheetName())) {
				// 初始化每个sheet的数据行
				dataRow = 0;

				// 错误信息 所在列
				Integer errorInfoNum = null;
				// 是否处理完成 所在列
				Integer isDoCompletedNum = null;
				// 是否成功 所在列
				Integer isSuccessNum = null;
				// 反馈结果 所在列
				Integer msgNum = null;
				// 身份证号码 所在列
				Integer idCardNum = null;
				// 证件号码 所在列
				Integer empIdCardNum = null;

				// 错误信息
				String errorInfo = null;
				// 是否处理完成
				String isDoCompleted = null;
				// 是否成功
				String isSuccess = null;
				// 反馈结果
				String msg = null;
				// 身份证号码
				String idCard = null;
				// 证件号码
				String empIdCard = null;

				for (int rowNum = 0; rowNum <= sheetAt.getLastRowNum(); rowNum++) {
					row = sheetAt.getRow(rowNum);
					if (row != null) {
						// 循环当前行的内容
						if (rowNum == 0) {
							for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
								// 标题行
								cell = row.getCell(cellNum);
								cellValue = "";
								try {
									if (cell != null) {
										if (CellType.STRING == cell.getCellType()) {
											cellValue = row.getCell(cellNum).getStringCellValue();
										} else if (CellType.NUMERIC == cell.getCellType()) {
											cellValue = String.valueOf(row.getCell(cellNum).getNumericCellValue());
											if (cellValue.contains("E")) {
												cellValue = String.valueOf(new DecimalFormat("#").format(row.getCell(cellNum).getNumericCellValue()));
											}
										}
									}
								} catch (NumberFormatException e) {
									cell.setCellType(CellType.STRING);
									cellValue = String.valueOf(row.getCell(cellNum).getStringCellValue());
								}
								if ("错误信息".equals(cellValue)) {
									errorInfoNum = cellNum;
								} else if ("是否处理完成".equals(cellValue)) {
									isDoCompletedNum = cellNum;
								} else if ("是否成功".equals(cellValue)) {
									isSuccessNum = cellNum;
								} else if ("反馈结果".equals(cellValue)) {
									msgNum = cellNum;
								} else if ("身份证号码".equals(cellValue)) {
									idCardNum = cellNum;
								} else if ("证件号码".equals(cellValue)) {
									empIdCardNum = cellNum;
								}
							}
						} else {
							if (Common.isEmpty(errorInfoNum) && Common.isEmpty(isDoCompletedNum)) {
								return R.failed("未找到对应表头！");
							} else {
								if (Common.isNotNull(errorInfoNum)) {
									errorInfo = getCellValue(row, errorInfoNum);
									vo = new TSocialSoldierReturnErrorVo();
									vo.setErrorInfo(errorInfo);
									voList.add(vo);
									return R.failed("数据错误！！");
								} else {
									if (Common.isNotNull(isDoCompletedNum) && Common.isNotNull(isSuccessNum)
											&& Common.isNotNull(msgNum)) {
										isDoCompleted = getCellValue(row, isDoCompletedNum);
										isSuccess = getCellValue(row, isSuccessNum);
										msg = getCellValue(row, msgNum);
										if (Common.isNotNull(idCardNum)) {
											idCard = getCellValue(row, idCardNum);
										} else if (Common.isNotNull(empIdCardNum)) {
											empIdCard = getCellValue(row, empIdCardNum);
										}
										vo = new TSocialSoldierReturnErrorVo();
										vo.setIsDoCompleted(isDoCompleted);
										vo.setIsSuccess(isSuccess);
										vo.setMsg(msg);
										vo.setIdCard(idCard);
										vo.setEmpIdCard(empIdCard);
										voList.add(vo);
									}
								}
							}
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			if (sheets != null) {
				try {
					sheets.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		} finally {
			if (sheets != null) {
				try {
					sheets.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if (!voList.isEmpty()) {
			importTSocialInfo(voList, idCardMap, errorMap, doAddId);
		}
		return R.ok(voList);
	}

	/**
	 * @Description: 获取单元格内容
	 * @Author: hgw
	 * @Date: 2024/5/13 16:34
	 * @return: java.lang.String
	 **/
	private String getCellValue(HSSFRow row, int cellNum) {
		HSSFCell cell = row.getCell(cellNum);
		String cellValue = "";
		try {
			if (cell != null) {
				if (CellType.STRING == cell.getCellType()) {
					cellValue = row.getCell(cellNum).getStringCellValue();
				} else if (CellType.NUMERIC == cell.getCellType()) {
					cellValue = String.valueOf(row.getCell(cellNum).getNumericCellValue());
					if (cellValue.contains("E")) {
						cellValue = String.valueOf(new DecimalFormat("#").format(row.getCell(cellNum).getNumericCellValue()));
					}
				}
			}
		} catch (NumberFormatException e) {
			cell.setCellType(CellType.STRING);
			cellValue = String.valueOf(row.getCell(cellNum).getStringCellValue());
		}
		return cellValue;
	}

	private String getCellValue(Row row, int cellNum) {
		Cell cell = row.getCell(cellNum);
		String cellValue = "";
		try {
			if (cell != null) {
				if (CellType.STRING == cell.getCellType()) {
					cellValue = row.getCell(cellNum).getStringCellValue();
				} else if (CellType.NUMERIC == cell.getCellType()) {
					cellValue = String.valueOf(row.getCell(cellNum).getNumericCellValue());
					if (cellValue.contains("E")) {
						cellValue = String.valueOf(new DecimalFormat("#").format(row.getCell(cellNum).getNumericCellValue()));
					}
				}
			}
		} catch (NumberFormatException e) {
			cell.setCellType(CellType.STRING);
			cellValue = String.valueOf(row.getCell(cellNum).getStringCellValue());
		}
		return cellValue;
	}

	private String getCellValue(XSSFRow row, int cellNum) {
		XSSFCell cell = row.getCell(cellNum);
		String cellValue = "";
		try {
			if (cell != null) {
				if (CellType.STRING == cell.getCellType()) {
					cellValue = row.getCell(cellNum).getStringCellValue();
				} else if (CellType.NUMERIC == cell.getCellType()) {
					cellValue = String.valueOf(row.getCell(cellNum).getNumericCellValue());
					if (cellValue.contains("E")) {
						cellValue = String.valueOf(new DecimalFormat("#").format(row.getCell(cellNum).getNumericCellValue()));
					}
				}
			}
		} catch (NumberFormatException e) {
			cell.setCellType(CellType.STRING);
			cellValue = String.valueOf(row.getCell(cellNum).getStringCellValue());
		}
		return cellValue;
	}

	/**
	 * @Description: 社保士兵审核结果的处理
	 * @Author: hgw
	 * @Date: 2024/5/27 11:30
	 * @return: void
	 **/
	private void importTSocialSoldierByAudit(List<TSocialSoldierReturnAuditErrorVo> excelVOList, Map<String, TSocialInfo> idCardMap
			, Map<String, FailReasonConfig> errorMap, String doAddId) {
		// 个性化校验逻辑
		// 执行数据插入操作 组装
		TSocialSoldierReturnAuditErrorVo excel;
		String empIdCard;
		String auditRemark;
		TSocialInfo socialInfo;
		List<TSocialInfo> updateSocialList = new ArrayList<>();
		TSocialInfo updateSocial;
		// true养工失 false 医生大
		boolean typeFlag = true;
		FailReasonConfig failConfig;
		String ygsHandleStatus;
		String ysdHandleStatus;
		// 养工失办理成功的单子
		List<String> ygsList = new ArrayList<>();
		// 养工失办理失败的单子
		List<String> ygsFailList = new ArrayList<>();
		// 医生大办理成功的单子
		List<String> ysdList = new ArrayList<>();
		// 医生大办理失败的单子
		List<String> ysdFailList = new ArrayList<>();
		Map<String, TSocialInfo> socialMap = new HashMap<>();

		// 处理社保办理成功后的状态同步-成功
		String typeSub = CommonConstants.ZERO_STRING;
		String handleStatus;
		String title = null;
		String handleRemark = null;
		String remark = null;
		String socialType;
		Set<String> dbAuthsSet = new HashSet<>();
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		YifuUser user = new YifuUser("1", 1L, "", "社保士兵",
				"社保士兵", "0", SecurityConstants.BCRYPT + "123456",
				"12345678911", true, true, true,
				true,
				"1", authorities, "1",
				null, null,
				null);
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			empIdCard = excel.getIdCard();
			auditRemark = excel.getYgsOperation();
			if (Common.isEmpty(auditRemark)) {
				auditRemark = excel.getYsdRemark();
				typeFlag = false;
			}
			if (Common.isNotNull(empIdCard)) {
				title = "社保";
				socialInfo = idCardMap.get(doAddId + CommonConstants.DOWN_LINE_STRING + empIdCard);
				if (socialInfo != null) {

					if (typeFlag && CommonConstants.SEVEN_STRING.equals(socialInfo.getYgsHandleStatus())) {
						updateSocial = socialMap.get(socialInfo.getId());
						if (updateSocial == null) {
							updateSocial = new TSocialInfo();
							updateSocial.setId(socialInfo.getId());
						}
						// 空、待审核、撤回或作废数据、审核不通过、审核通过
						if ("审核通过".equals(excel.getAuditStatus())) {
							ygsHandleStatus = CommonConstants.SIX_STRING;
							ygsList = new ArrayList<>();
							ygsList.add(socialInfo.getDispatchId());
							handleRemark = "社保士兵自动办理成功！";
							remark = handleRemark;
							updateSocial.setYgsRemark(handleRemark);
							updateSocial.setYgsRemarkOld(auditRemark);
						} else if ("审核不通过".equals(excel.getAuditStatus())) {
							handleRemark = "社保士兵审核不通过转人工处理！";
							remark = auditRemark;
							handleRemark += remark;
							updateSocial.setYgsRemark(handleRemark);
							updateSocial.setYgsRemarkOld(auditRemark);
							ygsHandleStatus = CommonConstants.FIVE_STRING;
							// 新增流程进展明细
							if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
								title += "派增";
							} else {
								title += "派减";
							}
							title += "养老、工伤、失业" + handleRemark;
							this.doSocialTAuditInfo(socialInfo, title, title, title, user);
						} else {
							updateSocial.setYgsRemark(auditRemark);
							updateSocial.setYgsRemarkOld(auditRemark);
							handleRemark = "社保士兵审核结果：" + excel.getAuditStatus();
							remark = auditRemark;
							handleRemark += remark;
							updateSocial.setYgsRemark(handleRemark);
							updateSocial.setYgsRemarkOld(handleRemark);
							ygsHandleStatus = CommonConstants.SEVEN_STRING;
							// 新增流程进展明细
							if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
								title += "派增";
							} else {
								title += "派减";
							}
							title += "养老、工伤、失业" + handleRemark;
							this.doSocialTAuditInfo(socialInfo, title, title, title, user);
							//}
						}
						updateSocial.setYgsHandleStatus(ygsHandleStatus);
						updateSocialList.add(updateSocial);
						socialMap.put(updateSocial.getId(), updateSocial);
					} else if (!typeFlag && CommonConstants.SEVEN_STRING.equals(socialInfo.getYsdHandleStatus())) {
						updateSocial = socialMap.get(socialInfo.getId());
						if (updateSocial == null) {
							updateSocial = new TSocialInfo();
							updateSocial.setId(socialInfo.getId());
						}
						// 空、待审核、撤回或作废数据、审核不通过、审核通过
						if ("审核通过".equals(excel.getAuditStatus())) {
							ysdHandleStatus = CommonConstants.SIX_STRING;
							ysdList = new ArrayList<>();
							ysdList.add(socialInfo.getDispatchId());
							handleRemark = "社保士兵自动办理成功！";
							remark = handleRemark;
							updateSocial.setYsdRemark(handleRemark);
							updateSocial.setYsdRemarkOld(auditRemark);
						} else if ("审核不通过".equals(excel.getAuditStatus())) {
							handleRemark = "社保士兵审核不通过转人工处理！";
							remark = auditRemark;
							handleRemark += remark;
							updateSocial.setYsdRemark(handleRemark);
							updateSocial.setYsdRemarkOld(auditRemark);
							ysdHandleStatus = CommonConstants.FIVE_STRING;
							// 新增流程进展明细
							if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
								title += "派增";
							} else {
								title += "派减";
							}
							title += "医疗、生育、大病" + handleRemark;
							this.doSocialTAuditInfo(socialInfo, title, title, title, user);
						} else {
							updateSocial.setYsdRemark(auditRemark);
							handleRemark = "社保士兵审核结果：" + excel.getAuditStatus();
							remark = auditRemark;
							handleRemark += remark;
							updateSocial.setYsdRemark(handleRemark);
							// 此时不能更新old，因为医疗要判断是新增还是续期，要根据这个字段来判断
							// updateSocial  setYgsRemarkOld(handleRemark)
							ysdHandleStatus = CommonConstants.SEVEN_STRING;
							// 新增流程进展明细
							if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
								title += "派增";
							} else {
								title += "派减";
							}
							title += "医疗、生育、大病" + handleRemark;
							this.doSocialTAuditInfo(socialInfo, title, title, title, user);
							//}
						}
						updateSocial.setYsdHandleStatus(ysdHandleStatus);
						updateSocialList.add(updateSocial);
						socialMap.put(updateSocial.getId(), updateSocial);
					}
					// 处理社保办理成功或失败，
					if (!updateSocialList.isEmpty()) {
						tSocialInfoService.updateBatchById(updateSocialList);
						updateSocialList = new ArrayList<>();
					}
					handleStatus = CommonConstants.ONE_STRING;

					// 处理社保办理成功后的状态同步-成功
					if (!ygsList.isEmpty()) {
						socialType = "1,4,3";
						this.doSocialAndDispatch(ygsList, typeSub, handleStatus, handleRemark, socialType, remark, user);
					}
					if (!ysdList.isEmpty()) {
						socialType = "2,5,6";
						this.doSocialAndDispatch(ysdList, typeSub, handleStatus, handleRemark, socialType, remark, user);
					}
					// 处理社保办理成功后的状态同步-失败
					handleStatus = CommonConstants.TWO_STRING;
					if (!ygsFailList.isEmpty()) {
						socialType = "1,4,3";
						this.doSocialAndDispatch(ygsFailList, typeSub, handleStatus, handleRemark, socialType, remark, user);
					}
					if (!ysdFailList.isEmpty()) {
						socialType = "2,5,6";
						this.doSocialAndDispatch(ysdFailList, typeSub, handleStatus, handleRemark, socialType, remark, user);
					}
				}
			}
		}
	}

	/**
	 * @Description: 社保士兵审核前的处理
	 * @Author: hgw
	 * @Date: 2024/5/27 11:29
	 * @return: void
	 **/
	private void importTSocialInfo(List<TSocialSoldierReturnErrorVo> excelVOList, Map<String, TSocialInfo> idCardMap
			, Map<String, FailReasonConfig> errorMap, String doAddId) {
		// 个性化校验逻辑
		// 执行数据插入操作 组装
		TSocialSoldierReturnErrorVo excel;
		String empIdCard;
		TSocialInfo socialInfo;
		List<TSocialInfo> updateSocialList = new ArrayList<>();
		TSocialInfo updateSocial;
		// true养工失 false 医生大
		boolean typeFlag = true;
		FailReasonConfig failConfig;
		String ygsHandleStatus;
		String ysdHandleStatus;
		// 养工失办理成功的单子
		List<String> ygsList = new ArrayList<>();
		// 养工失办理失败的单子
		List<String> ygsFailList = new ArrayList<>();
		// 医生大办理成功的单子
		List<String> ysdList = new ArrayList<>();
		// 医生大办理失败的单子
		List<String> ysdFailList = new ArrayList<>();
		Map<String, TSocialInfo> socialMap = new HashMap<>();

		// 处理社保办理成功后的状态同步-成功
		String typeSub = CommonConstants.ZERO_STRING;
		String handleStatus;
		String title = null;
		String handleRemark = null;
		String remark = null;
		String socialType;
		Set<String> dbAuthsSet = new HashSet<>();
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		YifuUser user = new YifuUser("1", 1L, "", "社保士兵",
				"社保士兵", "0", SecurityConstants.BCRYPT + "123456",
				"12345678911", true, true, true,
				true,
				"1", authorities, "1",
				null, null,
				null);
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			if ("是".equals(excel.getIsDoCompleted())) {
				// 插入
				log.info(excel.getErrorInfo());
				empIdCard = excel.getIdCard();
				if (Common.isEmpty(empIdCard)) {
					empIdCard = excel.getEmpIdCard();
					typeFlag = false;
				}
				if (Common.isNotNull(empIdCard)) {
					// 初始化继续办理
					ygsHandleStatus = CommonConstants.THREE_STRING;
					ysdHandleStatus = CommonConstants.THREE_STRING;
					title = "社保";
					socialInfo = idCardMap.get(doAddId + CommonConstants.DOWN_LINE_STRING + empIdCard);
					if (socialInfo != null) {

						if (typeFlag &&
								(CommonConstants.ONE_STRING.equals(socialInfo.getYgsHandleStatus())
										|| CommonConstants.TWO_STRING.equals(socialInfo.getYgsHandleStatus())
										|| CommonConstants.THREE_STRING.equals(socialInfo.getYgsHandleStatus()))) {
							updateSocial = socialMap.get(socialInfo.getId());
							if (updateSocial == null) {
								updateSocial = new TSocialInfo();
								updateSocial.setId(socialInfo.getId());
							}
							if ("是".equals(excel.getIsSuccess())) {
								/*ygsHandleStatus = CommonConstants.SIX_STRING;
								ygsList = new ArrayList<>();
								ygsList.add(socialInfo.getDispatchId());
								handleRemark = "社保士兵自动办理成功！";
								remark = "社保士兵自动办理成功！！";
								if (Common.isNotNull(excel.getMsg())) {
									failConfig = getConfig(excel.getMsg(),errorMap);
									if (failConfig != null) {
										updateSocial.setYgsRemark(failConfig.getSimpleReason());
									}
									updateSocial.setYgsRemarkOld(handleRemark);
								} else {
									updateSocial.setYgsRemark(handleRemark);
									updateSocial.setYgsRemarkOld(handleRemark);
								}*/

								handleRemark = "社保士兵提交成功！";
								remark = handleRemark;
								updateSocial.setYgsRemark(handleRemark);
								updateSocial.setYgsRemarkOld(handleRemark);
								ygsHandleStatus = CommonConstants.SEVEN_STRING;
								// 新增流程进展明细
								if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
									title += "派增";
								} else {
									title += "派减";
								}
								title += "养老、工伤、失业提交成功！";
								this.doSocialTAuditInfo(socialInfo, title, title, title, user);
							} else {
								updateSocial.setYgsRemark(excel.getMsg());
								updateSocial.setYgsRemarkOld(excel.getMsg());

								// 过期自动变为终止
								if (CommonConstants.ONE_STRING.equals(socialInfo.getYgsOverDueFlag())) {
									handleRemark = "已过期，自动中止办理！";
									updateSocial.setYgsRemarkOld(handleRemark);
									ygsHandleStatus = CommonConstants.FOUR_STRING;
									ygsFailList = new ArrayList<>();
									ygsFailList.add(socialInfo.getDispatchId());
									remark = handleRemark;
								} else if (Common.isNotNull(excel.getMsg())) {
									// 如果找到了失败原因配置：
									failConfig = getConfig(excel.getMsg(), errorMap);
									if (failConfig != null) {
										updateSocial.setYgsRemark(failConfig.getSimpleReason());
										// failConfig.getReplay() 1 继续办理 2 中止办理 3 人工办理
										// setYgsHandleStatus 3继续办理、4终止办理、5人工处理
										if (CommonConstants.ONE_STRING.equals(failConfig.getReplay())) {
											ygsHandleStatus = CommonConstants.THREE_STRING;
											// 新增流程进展明细
											if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
												title += "派增";
											} else {
												title += "派减";
											}
											title += "养老、工伤、失业办理失败！继续办理：" + failConfig.getSimpleReason();
											this.doSocialTAuditInfo(socialInfo, title, title, failConfig.getSimpleReason(), user);
										} else if (CommonConstants.TWO_STRING.equals(failConfig.getReplay())) {
											ygsHandleStatus = CommonConstants.FOUR_STRING;
											ygsFailList = new ArrayList<>();
											ygsFailList.add(socialInfo.getDispatchId());
											handleRemark = "中止办理：" + failConfig.getSimpleReason();
											remark = "中止办理：" + failConfig.getSimpleReason();
										} else if (CommonConstants.THREE_STRING.equals(failConfig.getReplay())) {
											ygsHandleStatus = CommonConstants.FIVE_STRING;

											// 新增流程进展明细
											if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
												title += "派增";
											} else {
												title += "派减";
											}
											title += "养老、工伤、失业办理失败！人工处理：" + failConfig.getSimpleReason();
											this.doSocialTAuditInfo(socialInfo, title, title, failConfig.getSimpleReason(), user);
										}
									} else {
										ygsHandleStatus = CommonConstants.FIVE_STRING;
										// 新增流程进展明细
										if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
											title += "派增";
										} else {
											title += "派减";
										}
										title += "养老、工伤、失业办理失败！人工处理：" + excel.getMsg();
										this.doSocialTAuditInfo(socialInfo, title, "养老、工伤、失业办理失败！人工处理：" + excel.getMsg(), excel.getMsg(), user);
									}
								}
							}
							updateSocial.setYgsHandleStatus(ygsHandleStatus);
							updateSocialList.add(updateSocial);
							socialMap.put(updateSocial.getId(), updateSocial);
						} else if (!typeFlag &&
								(CommonConstants.ONE_STRING.equals(socialInfo.getYsdHandleStatus())
										|| CommonConstants.TWO_STRING.equals(socialInfo.getYsdHandleStatus())
										|| CommonConstants.THREE_STRING.equals(socialInfo.getYsdHandleStatus()))) {
							updateSocial = socialMap.get(socialInfo.getId());
							if (updateSocial == null) {
								updateSocial = new TSocialInfo();
								updateSocial.setId(socialInfo.getId());
							}
							if ("是".equals(excel.getIsSuccess())) {
								// 2024-5-20 11:40:54 暂时将成功变为人工办理：
								/*ysdHandleStatus = CommonConstants.SIX_STRING;
								ysdList = new ArrayList<>();
								ysdList.add(socialInfo.getDispatchId());
								handleRemark = "社保士兵自动办理成功！";
								remark = "社保士兵自动办理成功！！";
								if (Common.isNotNull(excel.getMsg())) {
									failConfig = getConfig(excel.getMsg(),errorMap);
									if (failConfig != null) {
										updateSocial.setYsdRemark(failConfig.getSimpleReason());
									}
									updateSocial.setYsdRemarkOld(handleRemark);
								} else {
									updateSocial.setYsdRemark(handleRemark);
									updateSocial.setYsdRemarkOld(handleRemark);
								}*/
								handleRemark = "社保士兵提交成功：" + excel.getMsg();
								remark = handleRemark;
								updateSocial.setYsdRemark(handleRemark);
								updateSocial.setYsdRemarkOld("续保");
								if (Common.isNotNull(excel.getMsg()) && excel.getMsg().contains("新增")) {
									updateSocial.setYsdRemarkOld("新增");
								}
								ysdHandleStatus = CommonConstants.SEVEN_STRING;
								// 新增流程进展明细
								if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
									title += "派增";
								} else {
									title += "派减";
								}
								title += "医疗、生育、大病提交成功！";
								this.doSocialTAuditInfo(socialInfo, title, title, title, user);

							} else {
								updateSocial.setYsdRemark(excel.getMsg());
								updateSocial.setYsdRemarkOld(excel.getMsg());
								// 过期自动变为终止
								if (CommonConstants.ONE_STRING.equals(socialInfo.getYsdOverDueFlag())) {
									handleRemark = "已过期，自动中止办理！";
									updateSocial.setYsdRemarkOld(handleRemark);
									ysdHandleStatus = CommonConstants.FOUR_STRING;
									ysdFailList = new ArrayList<>();
									ysdFailList.add(socialInfo.getDispatchId());
									remark = handleRemark;
								} else if (Common.isNotNull(excel.getMsg())) {
									// 如果找到了失败原因配置：
									failConfig = getConfig(excel.getMsg(), errorMap);
									if (failConfig != null) {
										updateSocial.setYsdRemark(failConfig.getSimpleReason());
										// failConfig.getReplay() 1 继续办理 2 中止办理 3 人工办理
										// ysdHandleStatus 3继续办理、4终止办理、5人工处理
										if (CommonConstants.ONE_STRING.equals(failConfig.getReplay())) {
											ysdHandleStatus = CommonConstants.THREE_STRING;

											// 新增流程进展明细
											if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
												title += "派增";
											} else {
												title += "派减";
											}
											title += "医疗、生育、大病办理失败！继续办理：" + failConfig.getSimpleReason();
											this.doSocialTAuditInfo(socialInfo, title, title, failConfig.getSimpleReason(), user);
										} else if (CommonConstants.TWO_STRING.equals(failConfig.getReplay())) {
											ysdHandleStatus = CommonConstants.FOUR_STRING;
											ysdFailList = new ArrayList<>();
											ysdFailList.add(socialInfo.getDispatchId());
											handleRemark = "中止办理：" + failConfig.getSimpleReason();
											remark = "中止办理：" + failConfig.getSimpleReason();
										} else if (CommonConstants.THREE_STRING.equals(failConfig.getReplay())) {
											ysdHandleStatus = CommonConstants.FIVE_STRING;
											// 新增流程进展明细
											if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
												title += "派增";
											} else {
												title += "派减";
											}
											title += "医疗、生育、大病办理失败！人工处理：" + failConfig.getSimpleReason();
											this.doSocialTAuditInfo(socialInfo, title, "医疗、生育、大病办理失败！人工处理：" + failConfig.getSimpleReason(), failConfig.getSimpleReason(), user);
										}
									} else {
										ysdHandleStatus = CommonConstants.FIVE_STRING;
										// 新增流程进展明细
										if (CommonConstants.ZERO_STRING.equals(socialInfo.getDispatchType())) {
											title += "派增";
										} else {
											title += "派减";
										}
										title += "医疗、生育、大病办理失败！人工处理：" + excel.getMsg();
										this.doSocialTAuditInfo(socialInfo, title, "医疗、生育、大病办理失败！人工处理：" + excel.getMsg(), excel.getMsg(), user);
									}
								}
							}
							updateSocial.setYsdHandleStatus(ysdHandleStatus);
							updateSocialList.add(updateSocial);
							socialMap.put(updateSocial.getId(), updateSocial);
						}

						// 处理社保办理成功或失败，
						if (!updateSocialList.isEmpty()) {
							tSocialInfoService.updateBatchById(updateSocialList);
							updateSocialList = new ArrayList<>();
						}
						handleStatus = CommonConstants.ONE_STRING;

						// 处理社保办理成功后的状态同步-成功
						if (!ygsList.isEmpty()) {
							socialType = "1,4,3";
							this.doSocialAndDispatch(ygsList, typeSub, handleStatus, handleRemark, socialType, remark, user);
						}
						if (!ysdList.isEmpty()) {
							socialType = "2,5,6";
							this.doSocialAndDispatch(ysdList, typeSub, handleStatus, handleRemark, socialType, remark, user);
						}
						// 处理社保办理成功后的状态同步-失败
						handleStatus = CommonConstants.TWO_STRING;
						if (!ygsFailList.isEmpty()) {
							socialType = "1,4,3";
							this.doSocialAndDispatch(ygsFailList, typeSub, handleStatus, handleRemark, socialType, remark, user);
						}
						if (!ysdFailList.isEmpty()) {
							socialType = "2,5,6";
							this.doSocialAndDispatch(ysdFailList, typeSub, handleStatus, handleRemark, socialType, remark, user);
						}
					}
				}
			}
		}
	}

	/**
	 * @Description: 查找失败原因的关键字
	 * @Author: hgw
	 * @Date: 2024/5/14 17:55
	 * @return: com.yifu.cloud.plus.v1.yifu.social.entity.FailReasonConfig
	 **/
	private FailReasonConfig getConfig(String msg, Map<String, FailReasonConfig> errorMap) {
		if (errorMap != null) {
			for (Map.Entry<String, FailReasonConfig> config : errorMap.entrySet()) {
				if (msg.contains(config.getKey())) {
					return config.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * 调用成功的社保办理
	 *
	 * @param handleStatus 1 办理成功 2 办理失败
	 * @param handleRemark
	 * @param typeSub      0 社保 1  公积金
	 * @param socialType   （1养老 2医疗 3失业 4工伤 5生育 6大病）
	 * @return
	 * @Author hgw
	 * @Date 2024-5-11 17:03:12
	 **/
	public R<List<ErrorMessage>> doSocialAndDispatch(List<String> idList, String typeSub, String handleStatus
			, String handleRemark, String socialType, String remark, YifuUser user) {
		return tDispatchInfoService.addApplyHandle(idList, typeSub, handleStatus, handleRemark, socialType, remark, user, true);
	}

	/**
	 * 加办理记录
	 *
	 * @param handleRemark
	 * @Author hgw
	 * @Date 2024-5-16 11:43:33
	 **/
	public void doSocialTAuditInfo(TSocialInfo social, String title, String handleRemark, String remark, YifuUser user) {
		TAuditInfo auditInfo = new TAuditInfo();
		auditInfo.setType(CommonConstants.ONE_STRING);
		auditInfo.setId(null);
		auditInfo.setAuditStatus(CommonConstants.TWO_STRING);
		auditInfo.setAuditRemark(handleRemark);
		auditInfo.setTitle(title);
		auditInfo.setOrganName(user.getDeptName());
		auditInfo.setAuditUser(user.getNickname());
		auditInfo.setAuditTime(new Date());
		auditInfo.setRemark(remark);
		auditInfo.setIsCommision(CommonConstants.ONE_STRING);
		auditInfo.setDispatchInfoId(social.getDispatchId());
		auditInfo.setEmpIdcard(social.getEmpIdcard());
		auditInfo.setSocialId(social.getId());
		tAuditInfoService.save(auditInfo);
	}

}
