/*
 *    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.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
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.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import com.yifu.cloud.plus.v1.yifu.social.entity.THolidayInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialDeadlineInfo;
import com.yifu.cloud.plus.v1.yifu.social.mapper.THolidayInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TSocialDeadlineInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialDeadlineInfoService;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialDeadlineInfoSearchVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialDeadlineInfoVo;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 社保医疗截止日配置
 *
 * @author fxj
 * @date 2024-05-08 11:52:09
 */
@Log4j2
@AllArgsConstructor
@Service
public class TSocialDeadlineInfoServiceImpl extends ServiceImpl<TSocialDeadlineInfoMapper, TSocialDeadlineInfo> implements TSocialDeadlineInfoService {

	private final THolidayInfoMapper holidayInfoMapper;
	/**
	 * 社保医疗截止日配置简单分页查询
	 *
	 * @param tSocialDeadlineInfo 社保医疗截止日配置
	 * @return
	 */
	@Override
	public IPage<TSocialDeadlineInfo> getTSocialDeadlineInfoPage(Page<TSocialDeadlineInfo> page, TSocialDeadlineInfoSearchVo tSocialDeadlineInfo) {
		return baseMapper.getTSocialDeadlineInfoPage(page, tSocialDeadlineInfo);
	}

	/**
	 * 社保医疗截止日配置批量导出
	 *
	 * @param searchVo 社保医疗截止日配置
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TSocialDeadlineInfoSearchVo searchVo) {
		String fileName = "社保医疗截止日配置批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TSocialDeadlineInfo> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			//EasyExcel.write(out, TEmpBadRecord.class).sheet("不良记录").doWrite(list);
			ExcelWriter excelWriter = EasyExcel.write(out, TSocialDeadlineInfo.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 = noPageDiy(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TSocialDeadlineInfo> util = new ExcelUtil<>(TSocialDeadlineInfo.class);
						for (TSocialDeadlineInfo 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);
			}
		}
	}

	@Override
	public List<TSocialDeadlineInfo> noPageDiy(TSocialDeadlineInfoSearchVo searchVo) {
		LambdaQueryWrapper<TSocialDeadlineInfo> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TSocialDeadlineInfo::getId, idList);
		}
		if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0) {
			wrapper.last(" limit " + searchVo.getLimitStart() + "," + searchVo.getLimitEnd());
		}
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectList(wrapper);
	}

	private Long noPageCountDiy(TSocialDeadlineInfoSearchVo searchVo) {
		LambdaQueryWrapper<TSocialDeadlineInfo> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TSocialDeadlineInfo::getId, idList);
		}
		return baseMapper.selectCount(wrapper);
	}

	private LambdaQueryWrapper buildQueryWrapper(TSocialDeadlineInfoSearchVo entity) {
		LambdaQueryWrapper<TSocialDeadlineInfo> wrapper = Wrappers.lambdaQuery();
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TSocialDeadlineInfo::getCreateTime, entity.getCreateTimes()[0])
					.le(TSocialDeadlineInfo::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getCreateName())) {
			wrapper.eq(TSocialDeadlineInfo::getCreateName, entity.getCreateName());
		}
		return wrapper;
	}

	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TSocialDeadlineInfoVo> util1 = new ExcelUtil<>(TSocialDeadlineInfoVo.class);
		;
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, TSocialDeadlineInfoVo.class, new ReadListener<TSocialDeadlineInfoVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TSocialDeadlineInfoVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TSocialDeadlineInfoVo 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)) {
						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());
					importTSocialDeadlineInfo(cachedDataList, errorMessageList);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return R.ok(errorMessageList);
	}

	private void importTSocialDeadlineInfo(List<TSocialDeadlineInfoVo> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			TSocialDeadlineInfoVo excel = excelVOList.get(i);
			// 数据合法情况 TODO

			// 插入
			insertExcel(excel);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
		}
	}

	/**
	 * 插入excel bad record
	 */
	private void insertExcel(TSocialDeadlineInfoVo excel) {
		TSocialDeadlineInfo insert = new TSocialDeadlineInfo();
		BeanUtil.copyProperties(excel, insert);
		this.save(insert);
	}
	/**
	 * @Description: 定时任务生成月度截止日配置信息  没有一号生成当月派遣截止日配置
	 * @Author: fxj
	 * @Date: 2024/5/8
	 **/
	@Override
	public void createDeadLineSetInfo() {
		//获取基础配置信息
		List<TSocialDeadlineInfo>  baseLists = baseMapper.selectList(Wrappers.<TSocialDeadlineInfo>query().lambda()
				.eq(TSocialDeadlineInfo::getStatus,CommonConstants.ZERO_STRING)
				.eq(TSocialDeadlineInfo::getType,CommonConstants.ONE_STRING));
		if (Common.isNotNull(baseLists)){
			List<TSocialDeadlineInfo> saveList = new ArrayList<>();
			//获取当前月份所有假期配置表
			Date date  = new Date();
			List<THolidayInfo>  holidayInfos = holidayInfoMapper.selectList(Wrappers.<THolidayInfo>query().lambda()
					.eq(THolidayInfo::getYear,DateUtil.getYear(date))
					.eq(THolidayInfo::getMonth,DateUtil.getMonth(date)));
			Map<String,String> holidayMap = new HashMap<>();
			if (Common.isNotNull(holidayInfos)){
				for (THolidayInfo h:holidayInfos){
					holidayMap.put(h.getDay(),h.getDay());
				}
			}
			TSocialDeadlineInfo save;
			LambdaQueryWrapper<TSocialDeadlineInfo> queryWrapper;
			for (TSocialDeadlineInfo sd:baseLists){
				queryWrapper= null;
				save = new TSocialDeadlineInfo();
				BeanUtil.copyProperties(sd,save);
				save.setId(null);
				save.setMonth(Integer.parseInt(DateUtil.getThisMonth()));
				save.setType(CommonConstants.ZERO_STRING);

				//如果月份超出当前月 大概率是 日设置有问题这里做个优化
				// 初始化 月日时分
				if (Common.isNotNull(save.getMedicalStartDate())) {
					save.setMedicalStartDate(this.getNewDateByOldDate(save.getMedicalStartDate()));
				}
				if (Common.isNotNull(save.getMedicalEndDate())) {
					save.setMedicalEndDate(this.getNewDateByOldDate(save.getMedicalEndDate()));
				}
				if (Common.isNotNull(save.getSocialStartDate())) {
					save.setSocialStartDate(this.getNewDateByOldDate(save.getSocialStartDate()));
				}
				if (Common.isNotNull(save.getSocialEndDate())) {
					save.setSocialEndDate(this.getNewDateByOldDate(save.getSocialEndDate()));
				}

				initSocialEndDate(holidayMap, save);
				initMedicalEndDate(holidayMap, save);
				save.setUpdateTime(null);
				save.setUpdateBy(null);
				save.setUpdateName(null);
				queryWrapper = initCountQuery(save,queryWrapper);
				if (baseMapper.selectCount(queryWrapper) > 0){
					continue;
				}
				saveList.add(save);
			}
			if (Common.isNotNull(saveList)){
				this.saveBatch(saveList);
			}
		}
	}

	/**
	 * @param oldDate 原先的时间
	 * @Description: 传入老时间，返回新时间，将 月日时分 替换为新的，超过下个月的，返回当前时间
	 * @Author: hgw
	 * @Date: 2024/9/2 11:15
	 * @return: java.util.Date
	 **/
	private Date getNewDateByOldDate(Date oldDate) {
		return DateUtil.getDayOfThisMonthByHourAndMin(Math.min(DateUtil.getDays(oldDate), DateUtil.getLastDayOfDate(new Date())), oldDate);
	}

	private LambdaQueryWrapper<TSocialDeadlineInfo> initCountQuery(TSocialDeadlineInfo save,LambdaQueryWrapper<TSocialDeadlineInfo> queryWrapper) {
		queryWrapper  = Wrappers.lambdaQuery();
		queryWrapper.eq(TSocialDeadlineInfo::getMonth, save.getMonth());
		queryWrapper.eq(TSocialDeadlineInfo::getProvince, save.getProvince());
		if (Common.isNotNull(save.getCity())){
			queryWrapper.eq(TSocialDeadlineInfo::getCity, save.getCity());
			if (Common.isNotNull(save.getTown())){
				queryWrapper.eq(TSocialDeadlineInfo::getTown, save.getTown());
			}else {
				queryWrapper.isNull(TSocialDeadlineInfo::getTown);
			}
		}else {
			queryWrapper.isNull(TSocialDeadlineInfo::getCity);
		}
		return queryWrapper;
	}

	@Transactional
	@Override
	public R<Boolean>  updateByIdAsso(TSocialDeadlineInfo tSocialDeadlineInfo) {
		LambdaQueryWrapper<TSocialDeadlineInfo> queryWrapper = new LambdaQueryWrapper<>();
		initCheckSql(tSocialDeadlineInfo, queryWrapper);
		queryWrapper.ne(TSocialDeadlineInfo::getId,tSocialDeadlineInfo.getId());
		TSocialDeadlineInfo exit = baseMapper.selectOne(queryWrapper.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(exit)){
			return R.failed("已存在对应月份与缴纳地的配置，请确认后操作！");
		}
		//如果是基础配置 重置之前的配置
		updateType(tSocialDeadlineInfo);
		if (Common.isEmpty(tSocialDeadlineInfo.getCity())){
			tSocialDeadlineInfo.setCity(null);
		}
		if (Common.isEmpty(tSocialDeadlineInfo.getTown())){
			tSocialDeadlineInfo.setTown(null);
		}
		if (baseMapper.updateById(tSocialDeadlineInfo)>=0){
			return  R.ok();
		}
		return R.failed(CommonConstants.UPDATE_DATA_FAIL);
	}

	private void updateType(TSocialDeadlineInfo tSocialDeadlineInfo) {
		if (CommonConstants.ONE_STRING.equals(tSocialDeadlineInfo.getType())){
			LambdaUpdateWrapper<TSocialDeadlineInfo> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(TSocialDeadlineInfo::getType,CommonConstants.ONE_STRING)
					.eq(TSocialDeadlineInfo::getProvince, tSocialDeadlineInfo.getProvince())
					.set(TSocialDeadlineInfo::getStatus, CommonConstants.ZERO_STRING)
					.set(TSocialDeadlineInfo::getType, CommonConstants.ZERO_STRING)
					.set(TSocialDeadlineInfo :: getUpdateBy,"1")
					.set(TSocialDeadlineInfo :: getUpdateTime, LocalDateTime.now());
			if (Common.isEmpty(tSocialDeadlineInfo.getCity())){
				updateWrapper.isNull(TSocialDeadlineInfo::getCity);
			}else {
				updateWrapper.eq(TSocialDeadlineInfo::getCity, tSocialDeadlineInfo.getCity());
				if (Common.isEmpty(tSocialDeadlineInfo.getTown())){
					updateWrapper.isNull(TSocialDeadlineInfo::getTown);
				}else {
					updateWrapper.eq(TSocialDeadlineInfo::getTown, tSocialDeadlineInfo.getTown());
				}
			}
			update(updateWrapper);
		}
	}
	private void initCheckSql(TSocialDeadlineInfo tSocialDeadlineInfo, LambdaQueryWrapper<TSocialDeadlineInfo> queryWrapper) {
		queryWrapper.eq(TSocialDeadlineInfo::getMonth, tSocialDeadlineInfo.getMonth());
		queryWrapper.eq(TSocialDeadlineInfo::getProvince, tSocialDeadlineInfo.getProvince());
		if (Common.isNotNull(tSocialDeadlineInfo.getCity())){
			queryWrapper.eq(TSocialDeadlineInfo::getCity, tSocialDeadlineInfo.getCity());
			if (Common.isNotNull(tSocialDeadlineInfo.getTown())){
				queryWrapper.eq(TSocialDeadlineInfo::getTown, tSocialDeadlineInfo.getTown());
			}else {
				queryWrapper.isNull(TSocialDeadlineInfo::getTown);
			}
		}else {
			queryWrapper.isNull(TSocialDeadlineInfo::getCity);
		}
	}
	@Transactional
	@Override
	public R<Boolean>  saveAsso(TSocialDeadlineInfo tSocialDeadlineInfo) {
		LambdaQueryWrapper<TSocialDeadlineInfo> queryWrapper = new LambdaQueryWrapper<>();
		initCheckSql(tSocialDeadlineInfo, queryWrapper);
		TSocialDeadlineInfo exit = baseMapper.selectOne(queryWrapper.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(exit)){
			return R.failed("已存在对应月份与缴纳地的配置，请确认后操作！");
		}
		//如果是基础配置 重置之前的配置
		updateType(tSocialDeadlineInfo);
		if (Common.isEmpty(tSocialDeadlineInfo.getCity())){
			tSocialDeadlineInfo.setCity(null);
		}
		if (Common.isEmpty(tSocialDeadlineInfo.getTown())){
			tSocialDeadlineInfo.setTown(null);
		}
		if (baseMapper.insert(tSocialDeadlineInfo) >= 0){
			return  R.ok();
		}
		return R.failed(CommonConstants.SAVE_FAILED);
	}

	private void initMedicalEndDate(Map<String, String> holidayMap, TSocialDeadlineInfo save) {
		// type  0 休假  1 补班
		String day = holidayMap.get(DateUtil.getDay(save.getMedicalEndDate()));
		if (Common.isNotNull(day)){
			save.setMedicalEndDate(DateUtil.addDayByDate(save.getMedicalEndDate(),CommonConstants.ONE_INT_NEGATE));
		}else {
			return;
		}
		initMedicalEndDate(holidayMap,save);
	}

	private void initSocialEndDate(Map<String, String> holidayMap, TSocialDeadlineInfo save) {
		// type  0 休假  1 补班
		String day= holidayMap.get(DateUtil.getDay(save.getSocialEndDate()));
		if (Common.isNotNull(day)){
			save.setSocialEndDate(DateUtil.addDayByDate(save.getSocialEndDate(),CommonConstants.ONE_INT_NEGATE));
		}else {
			return;
		}
		initSocialEndDate(holidayMap,save);
	}

	/**
	 * @Description: 获取 当月启用 的配置
	 * @Author: hgw
	 * @Date: 2024/9/2 15:25
	 * @return: java.util.Map<java.lang.String, com.yifu.cloud.plus.v1.yifu.social.entity.TSocialDeadlineInfo>
	 **/
	@Override
	public Map<String, TSocialDeadlineInfo> getSocialSet() {
		Map<String, TSocialDeadlineInfo> setMap = new HashMap<>();
		List<TSocialDeadlineInfo> setlist = baseMapper.selectList(Wrappers.<TSocialDeadlineInfo>query().lambda()
				.eq(TSocialDeadlineInfo::getMonth, DateUtil.getThisMonth())
				.eq(TSocialDeadlineInfo::getStatus, CommonConstants.ZERO_STRING));
		if (setlist != null && !setlist.isEmpty()) {
			StringBuilder addressKey;
			ExcelUtil<TSocialDeadlineInfo> util = new ExcelUtil<>(TSocialDeadlineInfo.class);
			for (TSocialDeadlineInfo socialSet : setlist) {
				if (Common.isNotNull(socialSet.getProvince())) {
					util.convertEntity(socialSet, null, null, null);
					addressKey = new StringBuilder(socialSet.getProvince()).append(CommonConstants.DOWN_LINE_STRING);
					if (Common.isEmpty(socialSet.getCity())) {
						addressKey.append(CommonConstants.CENTER_SPLIT_LINE_STRING);
					} else {
						addressKey.append(socialSet.getCity());
					}
					addressKey.append(CommonConstants.DOWN_LINE_STRING);
					if (Common.isEmpty(socialSet.getTown())) {
						addressKey.append(CommonConstants.CENTER_SPLIT_LINE_STRING);
					} else {
						addressKey.append(socialSet.getTown());
					}
					setMap.put(addressKey.toString(), socialSet);
				}
			}
		}
		return setMap;
	}
}
