/*
 *    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.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TDispatchInfoPreVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseSearchVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.social.entity.SysHouseHoldInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.THouseHoldLimit;
import com.yifu.cloud.plus.v1.yifu.social.mapper.SysHouseHoldInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.mapper.THouseHoldLimitMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.THolidayInfoService;
import com.yifu.cloud.plus.v1.yifu.social.service.THouseHoldLimitService;
import com.yifu.cloud.plus.v1.yifu.social.vo.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * 户截止日配置表
 *
 * @author fxj
 * @date 2025-12-11 14:19:54
 */
@Log4j2
@Service
public class THouseHoldLimitServiceImpl extends ServiceImpl<THouseHoldLimitMapper, THouseHoldLimit> implements THouseHoldLimitService {

	@Autowired
	private SysHouseHoldInfoMapper sysHouseHoldInfoMapper;
	@Autowired
	private THolidayInfoService holidayInfoService;
	/**
	 * 户截止日配置表简单分页查询
	 *
	 * @param tHouseHoldLimit 户截止日配置表
	 * @return
	 */
	@Override
	public IPage<THouseHoldLimit> getTHouseHoldLimitPage(Page<THouseHoldLimit> page, THouseHoldLimitSearchVo tHouseHoldLimit) {
		return baseMapper.getTHouseHoldLimitPage(page, tHouseHoldLimit);
	}

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

	public List<THouseHoldLimitExportVo> exportDiy(THouseHoldLimitSearchVo searchVo) {
		return baseMapper.exportDiy(searchVo);
	}

	private int exportCountDiy(THouseHoldLimitSearchVo searchVo) {
		return baseMapper.exportCountDiy(searchVo);
	}


	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream,YifuUser user) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		//记录所有已存在的户名+户类型，包括EXCEL本身的
		Map<String,String> map = new HashMap<>();
		ExcelUtil<THouseHoldLimitVo> util1 = new ExcelUtil<>(THouseHoldLimitVo.class);
		;
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, THouseHoldLimitVo.class, new ReadListener<THouseHoldLimitVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<THouseHoldLimitVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
				/**
				 * 验证表头
				**/
				@Override
				public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
// 定义期望的表头
					Map<Integer, String> expectedHead = new HashMap<>();
					expectedHead.put(0, "户名");
					expectedHead.put(1, "户类型");
					expectedHead.put(2, "派增截止(日)");
					expectedHead.put(3, "派增办理规则");

					// 验证表头
					for (Map.Entry<Integer, String> entry : expectedHead.entrySet()) {
						String actualValue = headMap.get(entry.getKey()).getStringValue();
						if (null != headMap && null != headMap.get(entry.getKey())) {
							actualValue = headMap.get(entry.getKey()).getStringValue();
						}
						String expectedValue = entry.getValue();

						if (!expectedValue.equals(actualValue)) {
							errorMessageList.add(new ErrorMessage(entry.getKey() + 1,
									String.format("第%d列表头验证失败，期望:'%s'，实际:'%s'",
											entry.getKey() + 1, expectedValue, actualValue)));
							throw new ExcelAnalysisException(
									String.format("第%d列表头验证失败，期望:'%s'，实际:'%s'",
											entry.getKey() + 1, expectedValue, actualValue)

							);
						}
					}
				}
				@Override
				public void invoke(THouseHoldLimitVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						errorMessage.setData(data);
						errorMessageList.add(errorMessage);
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					importTHouseHoldLimit(cachedDataList, errorMessageList,map,user);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			if (Common.isNotKong(errorMessageList)){
				return R.failed(errorMessageList.get(0).getMessage());
			}else{
				return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
			}
		}finally {
			if (Common.isNotNull(map)){
				map.clear();
			}
		}
		return this.judgeAllMessage1(errorMessageList);
	}
	/**
	 * @Author fxj
	 * @Description 全部成功就返回成功
	 * @Date 15:22 2025/12/11
	 * @Param
	 * @return
	**/
	private R<List<ErrorMessage>> judgeAllMessage1(List<ErrorMessage> errorMessageList) {
		if (!errorMessageList.isEmpty()) {
			if(errorMessageList.stream().allMatch(e-> CommonConstants.SAVE_SUCCESS.equals(e.getMessage()))) {
				return R.ok();
			} else {
				return R.failed(errorMessageList);
			}
		}
		return R.ok();
	}
	private void importTHouseHoldLimit(List<THouseHoldLimitVo> excelVOList,
									   List<ErrorMessage> errorMessageList,
									   Map<String,String> map, YifuUser user) {
		// 个性化校验逻辑
		ErrorMessage errorMsg;
		//获取户数据(启用)
		Map<String,SysHouseHoldInfo> houseHoldMap = new HashMap<>();
		List<SysHouseHoldInfo> houseHoldInfoList = sysHouseHoldInfoMapper
				.selectList(Wrappers.<SysHouseHoldInfo>query().lambda()
				.eq(SysHouseHoldInfo::getDelFlag,CommonConstants.ZERO_STRING));
		if(Common.isNotNull(houseHoldInfoList)) {
			for (SysHouseHoldInfo houseHoldInfo : houseHoldInfoList) {
				houseHoldMap.put(houseHoldInfo.getName()+houseHoldInfo.getType(),houseHoldInfo);
			}
		}
		THouseHoldLimit holdLimit = null;
		SysHouseHoldInfo houseHold = null;
		String houseLimitRowIndex = null;
		THouseHoldLimit limitInsert = null;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			THouseHoldLimitVo excel = excelVOList.get(i);
			houseHold = houseHoldMap.get(excel.getName()+excel.getType());
			if(!Common.isNotNull(houseHold)) {
				errorMsg = new ErrorMessage(excel.getRowIndex(), "未找到该户名及户类型的数据", excel);
				errorMessageList.add(errorMsg);
				continue;
			}
			houseLimitRowIndex = map.get(excel.getName()+excel.getType());
			if (Common.isNotNull(houseLimitRowIndex)){
				errorMsg = new ErrorMessage(excel.getRowIndex(), "该户名及户类型已存在EXCEL第"+houseLimitRowIndex+"行，请勿重复导入", excel);
				errorMessageList.add(errorMsg);
				continue;
			}
			holdLimit = baseMapper.selectOne(Wrappers.<THouseHoldLimit>query().lambda()
						.eq(THouseHoldLimit::getType,excel.getType())
						.eq(THouseHoldLimit::getName,excel.getName())
				.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(excel.getDeadLineDay())){
				if (!Common.isNumber(excel.getDeadLineDay())){
					errorMsg = new ErrorMessage(excel.getRowIndex(), "派增截止(日)只能是数字", excel);
					errorMessageList.add(errorMsg);
					continue;
				}
				if (Integer.parseInt(excel.getDeadLineDay()) > 31 || Integer.parseInt(excel.getDeadLineDay()) < 10){
					errorMsg = new ErrorMessage(excel.getRowIndex(), "派增截止(日)只能是10-31的数字", excel);
					errorMessageList.add(errorMsg);
					continue;
				}
			}
			if (Common.isNotNull(excel.getAddHandleRule())){
				if (!CommonConstants.ZERO_STRING.equals(excel.getAddHandleRule()) && !CommonConstants.ONE_STRING.equals(excel.getAddHandleRule())){
					errorMsg = new ErrorMessage(excel.getRowIndex(), "派增办理规则只能是'当月办当月生效'或'当月办次月生效'", excel);
					errorMessageList.add(errorMsg);
					continue;
				}
			}
			if (Common.isNotNull(excel.getType())){
				if (!CommonConstants.ZERO_STRING.equals(excel.getType()) && !CommonConstants.ONE_STRING.equals(excel.getType())){
					errorMsg = new ErrorMessage(excel.getRowIndex(), "户类型只能是'社保'或'公积金'", excel);
					errorMessageList.add(errorMsg);
					continue;
				}

			}
			limitInsert = new THouseHoldLimit();
			limitInsert.setHouseHoldId(houseHold.getId());
			limitInsert.setType(excel.getType());
			limitInsert.setDeadLineDay(excel.getDeadLineDay());
			limitInsert.setAddHandleRule(excel.getAddHandleRule());
			limitInsert.setName(excel.getName());
			limitInsert.setUpdateBy(user.getId());
			limitInsert.setUpdateTime(LocalDateTime.now());
			// 从户配置中覆盖省市县信息（处理空值情况）
			limitInsert.setProvince(Common.isEmpty(houseHold.getProvince()) ? "" : houseHold.getProvince());
			limitInsert.setCity(Common.isEmpty(houseHold.getCity()) ? null : houseHold.getCity());
			limitInsert.setTown(Common.isEmpty(houseHold.getTown()) ? null : houseHold.getTown());
			map.put(excel.getName()+excel.getType(),excel.getRowIndex().toString());
			// 判断是新增还是更新
			boolean success;
			if (null != holdLimit){
				// 更新已有记录
				limitInsert.setId(holdLimit.getId());
				limitInsert.setCreateBy(holdLimit.getCreateBy());
				limitInsert.setCreateTime(holdLimit.getCreateTime());
				limitInsert.setCreateName(holdLimit.getCreateName());
				limitInsert.setUpdateBy(user.getId());
				limitInsert.setUpdateTime(LocalDateTime.now());
				success = updateExcel(limitInsert);
			} else {
				// 新增记录
				limitInsert.setCreateBy(user.getId());
				limitInsert.setCreateTime(LocalDateTime.now());
				limitInsert.setCreateName(user.getNickname());
				success = insertExcel(limitInsert);
			}
			if (!success){
				errorMsg = new ErrorMessage(excel.getRowIndex(), "导入异常", excel);
				errorMessageList.add(errorMsg);
				continue;
			}
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS, excel));
		}
	}

	/**
	 * 插入excel record
	 */
	private boolean insertExcel(THouseHoldLimit insert) {
		return baseMapper.insert(insert) >= 1;
	}

	/**
	 * 更新excel record
	 */
	private boolean updateExcel(THouseHoldLimit update) {
		return baseMapper.updateById(update) >= 1;
	}

	/**
	 * 通过户名称及类型查询到具体截止日期后去看是否为工作日，如果不是工作日则往前推，知道找到工作日，然后返回工作日
	 * 如果找不到对应截止日期，则返回null
	 * @param paramVo:户名称 type: 0 社保、1 公积金
	 * @return R true 当月能办理  false 当月不能办理
	 */
	@Override
	public THouseHoldLimitInnerVo getWorkDayByDeadLineDay(BaseSearchVO paramVo) {
		THouseHoldLimit houseHoldLimit = baseMapper.selectOne(Wrappers.<THouseHoldLimit>query().lambda()
				.eq(THouseHoldLimit::getName,paramVo.getName())
				.eq(THouseHoldLimit::getType,paramVo.getType())
				.last(CommonConstants.LAST_ONE_SQL));
		if (null == houseHoldLimit){
			return null;
		}
		THouseHoldLimitInnerVo limitInnerVo = null;
		String deadLineDay = houseHoldLimit.getDeadLineDay();
		if (Common.isNotNull(deadLineDay)) {
			try {
				TEmployeeInsuranceWorkDayVo vo = new TEmployeeInsuranceWorkDayVo();
				// 设置RegistDate为当前月份对应的截止日期deadLineDay
				Date registDate = DateUtil.setDayByDate(DateUtil.formatDateByPatten(new Date(), DateUtil.ISO_EXPANDED_DATE_FORMAT), Integer.parseInt(deadLineDay));
				if (null == registDate) {
					return null;
				}
				vo.setRegistDate(registDate);
				vo.setType(CommonConstants.ONE_STRING);
				holidayInfoService.selectBeforeOrAfterWorkDay(vo);
				limitInnerVo = new THouseHoldLimitInnerVo();
				limitInnerVo.setCanBeHandle(false);
				limitInnerVo.setDeadLineDay(deadLineDay);
				limitInnerVo.setName(houseHoldLimit.getName());
				limitInnerVo.setType(houseHoldLimit.getType());
				limitInnerVo.setWordDate(vo.getRegistDate());
				limitInnerVo.setAddHandleRule(houseHoldLimit.getAddHandleRule());
				// 判断当前日期是否在截止日期之后
				// 如果当前时间在截止日之后，则表示不可以办理，返回false，否则返回true
				if (vo.getRegistDate() != null) {
					LocalTime currentTime = LocalTime.now();
					LocalTime thresholdTime = LocalTime.of(15, 20);
					int dayOffset = (currentTime.isBefore(thresholdTime) || currentTime.equals(thresholdTime)) ? 0 : 1;
					if (!DateUtil.isAfter(DateUtil.getDateByDayNum(dayOffset), vo.getRegistDate())) {
						limitInnerVo.setCanBeHandle(true);
					}
				}
			} catch (NumberFormatException e) {
				// 截止日期不是有效数字，返回null表示无法确定
				return null;
			}
		}
		return limitInnerVo;
	}

	@Override
	public  R<String> getConfirmDate(BaseSearchVO paramVo) {
		THouseHoldLimit houseHoldLimit = baseMapper.selectOne(Wrappers.<THouseHoldLimit>query().lambda()
				.eq(THouseHoldLimit::getName,paramVo.getName())
				.eq(THouseHoldLimit::getType,paramVo.getType())
				.last(CommonConstants.LAST_ONE_SQL));
		if (null == houseHoldLimit){
			return R.failed("未找到户截止日配置信息");
		}
		String deadLineDay = houseHoldLimit.getDeadLineDay();
		if (Common.isNotNull(deadLineDay)) {
			try {
				TEmployeeInsuranceWorkDayVo vo = new TEmployeeInsuranceWorkDayVo();
				// 设置RegistDate为当前月份对应的截止日期deadLineDay
				Date registDate = DateUtil.setDayByDate(DateUtil.formatDateByPatten(new Date(), DateUtil.ISO_EXPANDED_DATE_FORMAT), Integer.parseInt(deadLineDay));
				if (null == registDate) {
					return R.failed("未找到截止日期对应的可用工作日");
				}
				vo.setRegistDate(registDate);
				vo.setType(CommonConstants.ONE_STRING);
				holidayInfoService.selectBeforeOrAfterWorkDay(vo);
				boolean  canBeHandle = false;
				String addHandleRule = houseHoldLimit.getAddHandleRule();
				// 如果当前时间在截止日之后，则表示不可以办理，返回false，否则返回true
				if (vo.getRegistDate() != null) {
					LocalTime currentTime = LocalTime.now();
					LocalTime thresholdTime = LocalTime.of(15, 20);
					int dayOffset = (currentTime.isBefore(thresholdTime) || currentTime.equals(thresholdTime)) ? 0 : 1;
					if (!DateUtil.isAfter(DateUtil.getDateByDayNum(dayOffset), vo.getRegistDate())) {
						canBeHandle = true;
					}
				}
				return  R.ok(initExpectedCollectionTime( paramVo.getStartDate(),canBeHandle,addHandleRule));
			} catch (NumberFormatException e) {
				// 截止日期不是有效数字，返回null表示无法确定
				return R.failed("截止日期不是有效数字");
			}
		}
		return R.ok("获取日期信息失败，请查验配置数据");
	}
	/**
	 * @Author fxj
	 * @Description 初始化预计派单发起时间、预计派单确认时间
	 * @Date 17:06 2025/12/12
	 **/
	private String initExpectedCollectionTime(Date startDate,boolean canBeHandle,String addHandleRule) {
		LocalTime currentTime = LocalTime.now();
		LocalTime thresholdTime = LocalTime.of(15, 20);
		boolean isBeforeThreshold = currentTime.isBefore(thresholdTime) || currentTime.equals(thresholdTime);

		//获取次月1号日期
		Date nextMonthFirstDay = DateUtil.addMonthByDate(DateUtil.formatDateByPatten(new Date(), DateUtil.ISO_EXPANDED_DATE_FORMAT), 1);
		nextMonthFirstDay = DateUtil.setDayByDate(nextMonthFirstDay, 1);

		//获取起缴月份1号
		Date startDateFirstDay = DateUtil.addDayByDate(DateUtil.formatDateByPatten(startDate, DateUtil.ISO_EXPANDED_DATE_FORMAT), 0);
		startDateFirstDay = DateUtil.setDayByDate(startDateFirstDay, 1);

		//获取起缴月-1日期
		Date startDatePrevMonth = DateUtil.addMonthByDate(startDateFirstDay, -1);

		//获取次日
		Date tomorrow = DateUtil.getDateByDayNum(1);
		//1.起缴月份为当月及之前的月份
		if (DateUtil.isCurrentOrBeforeMonth(startDate)){
			if (canBeHandle){
				//发起时间不看工作日
				if (isBeforeThreshold) {
					Date today = new Date();
					return DateUtil.dateToString(today, DateUtil.ISO_EXPANDED_DATE_FORMAT);
				} else {
					return DateUtil.dateToString(tomorrow, DateUtil.ISO_EXPANDED_DATE_FORMAT);
				}
			} else {
				return DateUtil.dateToString(nextMonthFirstDay, DateUtil.ISO_EXPANDED_DATE_FORMAT) ;
			}
		}
		//2.起缴月份为次月
		else if (DateUtil.isNextMonth(startDate)){
			//当月办次月生效
			if (CommonConstants.ONE_STRING.equals(addHandleRule)){
				if (canBeHandle){
					if (isBeforeThreshold){
						Date today = new Date();
						return  DateUtil.dateToString(today, DateUtil.ISO_EXPANDED_DATE_FORMAT);
					}else {
						return DateUtil.dateToString(tomorrow, DateUtil.ISO_EXPANDED_DATE_FORMAT);
					}
				} else {
					return DateUtil.dateToString(nextMonthFirstDay, DateUtil.ISO_EXPANDED_DATE_FORMAT);
				}
				//当月办当月生效
			} else if (CommonConstants.ZERO_STRING.equals(addHandleRule)){
				return DateUtil.dateToString(nextMonthFirstDay, DateUtil.ISO_EXPANDED_DATE_FORMAT);
			}
		}
		//3.起缴月份为次月之后的月份
		else if (DateUtil.isNextNextMonthOrAfter(startDate)){
			//当月办次月生效
			if (CommonConstants.ONE_STRING.equals(addHandleRule)){
				return  DateUtil.dateToString(startDatePrevMonth, DateUtil.ISO_EXPANDED_DATE_FORMAT);
			} else if (CommonConstants.ZERO_STRING.equals(addHandleRule)){
				return DateUtil.dateToString(startDateFirstDay, DateUtil.ISO_EXPANDED_DATE_FORMAT) ;
			}
		}
		return null;
	}
}
