package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.constants.ArchivesConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeRetirement;

import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeRetirementFlagDetail;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeRetirementFlagDetailMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeRetirementMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeRetirementService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
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.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.social.vo.TDispatchAuditExportVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TDispatchInfoSearchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author 86187
* @description 针对表【t_employee_retirement】的数据库操作Service实现
* @createDate 2023-05-18 15:40:46
*/
@Service
public class TEmployeeRetirementServiceImpl extends ServiceImpl<TEmployeeRetirementMapper, TEmployeeRetirement>
implements TEmployeeRetirementService {

@Autowired
private  TEmployeeRetirementMapper tEmployeeRetirementMapper;
@Autowired
private TEmployeeRetirementFlagDetailMapper tEmployeeRetirementFlagDetailMapper;


	@Override
	public IPage<TEmployeeRetirement> getTEmployeeRetirementPage(Page page, TEmployeeRetirementSearchVo searchVo) {
		YifuUser user=SecurityUtils.getUser();
		String userId = user.getId();
		return baseMapper.getTEmployeeRetirementPage(page, userId,searchVo);
	}


	@Override
	public void retireeRemind() {
		Date date = DateUtil.getCurrentDateTime();
		YifuUser user = SecurityUtils.getUser();
		SimpleDateFormat formatterMenYear = new SimpleDateFormat("YYYYMM");
		String YearMonth = formatterMenYear.format(date);
		SimpleDateFormat formatterManDate = new SimpleDateFormat("dd");
		String dateOne = formatterManDate.format(date);
		String mRemainTime = DateUtil.getYearAndMonth(YearMonth, ArchivesConstants.MYEAR_MONTH);
		String wRemainTime = DateUtil.getYearAndMonth(YearMonth, ArchivesConstants.WYEAR_MONTH);
		String TT = mRemainTime + dateOne;
		String LL = wRemainTime + dateOne;
		String oo=DateUtil.dateToString(DateUtil.stringToDate(TT));
		String pp=DateUtil.dateToString(DateUtil.stringToDate(LL));
		List<TEmployeeRetirement> list = baseMapper.getBirthday(oo,pp);
		for (TEmployeeRetirement tEmployeeRetirement : list) {
			int i = baseMapper.selectByEmpIdcard(tEmployeeRetirement.getEmpIdcard(),tEmployeeRetirement.getDeptNo());
			if (i == 0) {
				tEmployeeRetirement.setHandleFlag(0);
				tEmployeeRetirement.setCreateBy("1");
				tEmployeeRetirementMapper.insert(tEmployeeRetirement);
			}
		}
	}

	@Override
	public boolean changeHandleFlagAll(ChangeHandleFlagAllVo changeHandleFlagAllVo) {
		YifuUser user = SecurityUtils.getUser();
		for (int i = 0; i < changeHandleFlagAllVo.getIds().length; i++) {
			TEmployeeRetirementFlagDetail tEmployeeRetirementFlagDetail = new TEmployeeRetirementFlagDetail();
			if (changeHandleFlagAllVo.getHandleFlag() == 0) {

				tEmployeeRetirementFlagDetail.setDatailId(changeHandleFlagAllVo.getIds()[i]);
			TEmployeeRetirement tEmployeeRetirement=tEmployeeRetirementMapper.selectById(changeHandleFlagAllVo.getIds()[i]);
			if(tEmployeeRetirement.getHandleFlag()==0){
				tEmployeeRetirementFlagDetail.setContext(ArchivesConstants.HANDLE_FLAG_THREE);

			}
			    else {
					tEmployeeRetirementFlagDetail.setContext(ArchivesConstants.HANDLE_FLAG_TWO);
				}
				tEmployeeRetirementFlagDetail.setCreateBy(user.getId());
				tEmployeeRetirementFlagDetail.setCreateName(user.getNickname());
				tEmployeeRetirementFlagDetail.setCreateTime(DateTime.now());
				tEmployeeRetirementFlagDetailMapper.insert(tEmployeeRetirementFlagDetail);
			}

			if (changeHandleFlagAllVo.getHandleFlag() == 1) {

				tEmployeeRetirementFlagDetail.setDatailId(changeHandleFlagAllVo.getIds()[i]);
				TEmployeeRetirement tEmployeeRetirement=tEmployeeRetirementMapper.selectById(changeHandleFlagAllVo.getIds()[i]);
				if(tEmployeeRetirement.getHandleFlag()==1){
					tEmployeeRetirementFlagDetail.setContext(ArchivesConstants.HANDLE_FLAG_FOUR);

				}
				else {
					tEmployeeRetirementFlagDetail.setContext(ArchivesConstants.HANDLE_FLAG_ONE);
				}

				tEmployeeRetirementFlagDetail.setCreateBy(user.getId());
				tEmployeeRetirementFlagDetail.setCreateName(user.getNickname());
				tEmployeeRetirementFlagDetail.setCreateTime(DateTime.now());
				tEmployeeRetirementFlagDetailMapper.insert(tEmployeeRetirementFlagDetail);
			}
		}
			return baseMapper.changeHandleFlagAll(changeHandleFlagAllVo);
		}




	@Override
	public boolean changeHandleFlag(ChangeHandleFlagVo changeHandleFlagVo) {
		YifuUser user = SecurityUtils.getUser();
		TEmployeeRetirementFlagDetail tEmployeeRetirementFlagDetail = new TEmployeeRetirementFlagDetail();
		if(changeHandleFlagVo.getHandleFlag()==0){
			tEmployeeRetirementFlagDetail.setDatailId(changeHandleFlagVo.getId());
			tEmployeeRetirementFlagDetail.setContext(ArchivesConstants.HANDLE_FLAG_TWO);
			tEmployeeRetirementFlagDetail.setCreateBy(user.getId());
			tEmployeeRetirementFlagDetail.setCreateTime(DateTime.now());
			tEmployeeRetirementFlagDetail.setCreateName(user.getNickname());
			tEmployeeRetirementFlagDetailMapper.insert(tEmployeeRetirementFlagDetail);
		}
		if(changeHandleFlagVo.getHandleFlag()==1){
			tEmployeeRetirementFlagDetail.setDatailId(changeHandleFlagVo.getId());
			tEmployeeRetirementFlagDetail.setContext(ArchivesConstants.HANDLE_FLAG_ONE);
			tEmployeeRetirementFlagDetail.setCreateBy(user.getId());
			tEmployeeRetirementFlagDetail.setCreateTime(DateTime.now());
			tEmployeeRetirementFlagDetail.setCreateName(user.getNickname());
			tEmployeeRetirementFlagDetailMapper.insert(tEmployeeRetirementFlagDetail);
		}
		return  baseMapper.changeHandleFlag(changeHandleFlagVo);
	}


	@Override
	public void listExport(HttpServletResponse response, TEmployeeRetirementSearchVo searchVo) {
		YifuUser user=SecurityUtils.getUser();
		String userId = user.getId();
		String fileName = "人员退休提醒批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		List<TEmployeeRetirementExportVo> list = new ArrayList<>();
		long count = noPageCountDiy(userId,searchVo);
		try (ServletOutputStream out = response.getOutputStream()){
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , "UTF-8"));
			ExcelUtil<TEmployeeRetirementExportVo> util = new ExcelUtil<>(TEmployeeRetirementExportVo.class);
			// 获取所有字典type
			Map<String,String> nameAndDicTypeMap = util.getConverterDicType();
			// 获取所有字典对应的值
			Map<String,String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TEmployeeRetirementExportVo.class)
					.registerConverter(new DictConverter(nameAndDicTypeMap,redisLabelMap))
					.build();
			int index = 0;
			if (count >  CommonConstants.ZERO_INT){
				WriteSheet writeSheet;
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(userId,searchVo);
					for (TEmployeeRetirementExportVo tEmployeeRetirementExportVo :list) {
						String fileProvince = baseMapper.selectByIdd(tEmployeeRetirementExportVo.getFileProvince());
						String fileCity = baseMapper.selectByIdd(tEmployeeRetirementExportVo.getFileCity());
						String fileTown = baseMapper.selectByIdd(tEmployeeRetirementExportVo.getFileTown());
						if (null != fileProvince && null != fileCity) {
							if (null != fileCity && null == fileTown) {
								tEmployeeRetirementExportVo.setFileAddress(fileProvince + "/" + fileCity);
							} else {
								tEmployeeRetirementExportVo.setFileAddress(fileProvince + "/" + fileCity + "/" + fileTown);
							}
						}
						String socialProvince = baseMapper.selectByIdd(tEmployeeRetirementExportVo.getSocialProvince());
						String socialCity = baseMapper.selectByIdd(tEmployeeRetirementExportVo.getSocialCity());
						String socailTown = baseMapper.selectByIdd(tEmployeeRetirementExportVo.getSocialTown());
						if (null != socialProvince && null != socialCity ) {
							if (null != socialCity && null == socailTown) {
								tEmployeeRetirementExportVo.setSocialAddress(socialProvince + "/" + socialCity);
							} else {
								tEmployeeRetirementExportVo.setFileAddress(socialProvince + "/" + socialCity + "/" + socailTown);
							}
						}

					}
					if (Common.isNotNull(list)){
						writeSheet = EasyExcel.writerSheet("人员退休提醒批量导出"+index).build();
						excelWriter.write(list,writeSheet);
						index++;
					}
					if (Common.isNotNull(list)){
						list.clear();
					}
				}
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet("人员退休提醒批量导出"+index).build();
				excelWriter.write(list,writeSheet);
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			excelWriter.finish();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}
	}

	@Override
	public List<TEmployeeRetirementFlagDetail> getHandleFlagDetail(String id) {
		return tEmployeeRetirementFlagDetailMapper.getDatail(id);
	}

	private List<TEmployeeRetirementExportVo> noPageDiy(String userId,TEmployeeRetirementSearchVo searchVo) {

		return baseMapper.noPageDiy(userId,searchVo);
	}

	private int noPageCountDiy(String userId,TEmployeeRetirementSearchVo searchVo) {
		return baseMapper.noPageCountDiy(userId,searchVo);
	}
}
