/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.yifu.cloud.plus.v1.yifu.social.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.social.config.SocialConfig;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialAutoAuditTask;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialInfo;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TSocialSoldierMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialAutoAuditTaskService;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialInfoService;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialSoldierPushService;
import com.yifu.cloud.plus.v1.yifu.social.vo.SocialSoldierSetVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.SocialSoldierYgsAddVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.SocialSoldierYgsAuditVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.SocialSoldierYsdAuditVo;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

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

	private RestTemplate restTemplate = new RestTemplate();
	private final SocialConfig socialConfig;
	private final TSocialInfoService tSocialInfoService;
	private final TSocialAutoAuditTaskService tSocialAutoAuditTaskService;

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

	/**
	 * @Description: 组装社保与医保的文件流
	 * @Author: hgw
	 * @Date: 2024/5/23 17:59
	 * @return: org.springframework.web.multipart.MultipartFile
	 **/
	public MultipartFile getFile(List<SocialSoldierYgsAddVo> list, int type) {
		if (list != null) {
			String fileName = "soldierFile" + DateUtil.getThisTime() + new Date().getTime() + CommonConstants.XLSX;

			ExcelWriter excelWriter = EasyExcelFactory.write(fileName).build();
			WriteSheet writeSheet = EasyExcelFactory.writerSheet("社保明细").head(SocialSoldierYgsAddVo.class).build();
			excelWriter.write(list, writeSheet);
			if (type == 2) {
				List<SocialSoldierSetVo> setList = new ArrayList<>();
				SocialSoldierSetVo vo = new SocialSoldierSetVo();
				vo.setIsAutoSubmit("否");
				vo.setIsAutoInsert("否");
				vo.setIsAutoUpload("否");
				vo.setIsDoShenBao("否");
				setList.add(vo);
				WriteSheet writeSheet2 = EasyExcelFactory.writerSheet("功能设置").head(SocialSoldierSetVo.class).build();
				excelWriter.write(setList, writeSheet2);
			}
			File file = new File(fileName);
			excelWriter.finish();
			return getMultipartFile(file);
		}
		return null;
	}

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

	/**
	 * @Description: 推送到社保士兵
	 * @Author: hgw
	 * @Date: 2024/5/10 17:53
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> pushSoldier(List<String> dispatchIdList) {
		log.info("dispatchIdList="+dispatchIdList);
		// 社保增员、社保减员、医保增员、医保减员
		// 养工失新增列表
		List<SocialSoldierYgsAddVo> ygsAddlist = baseMapper.getSocialSoldierYgsAddVoList(dispatchIdList);
		log.info("ygsAddlist="+ygsAddlist);
		if (ygsAddlist != null && !ygsAddlist.isEmpty()) {
			List<TSocialInfo> socialIdList = new ArrayList<>();
			TSocialInfo socialInfo;
			for (SocialSoldierYgsAddVo vo : ygsAddlist) {
				socialInfo = new TSocialInfo();
				socialInfo.setId(vo.getSocialId());
				socialIdList.add(socialInfo);
			}
			MultipartFile file = this.getFile(ygsAddlist, 1);
			if (Common.isNotNull(file)) {
				this.getOneAppGetModuleDetail(socialIdList, file, "社保增员");
			}
		}
		// 养工失减少列表
		List<SocialSoldierYgsAddVo> ygsReducelist = baseMapper.getSocialSoldierYgsReduceVoList(dispatchIdList);
		if (ygsReducelist != null && !ygsReducelist.isEmpty()) {
			List<TSocialInfo> socialIdList = new ArrayList<>();
			TSocialInfo socialInfo;
			for (SocialSoldierYgsAddVo vo : ygsReducelist) {
				socialInfo = new TSocialInfo();
				socialInfo.setId(vo.getSocialId());
				socialIdList.add(socialInfo);
			}
			MultipartFile file = this.getFile(ygsReducelist, 2);
			if (Common.isNotNull(file)) {
				this.getOneAppGetModuleDetail(socialIdList, file, "社保减员");
			}
		}
		// 医生大新增列表
		List<SocialSoldierYgsAddVo> ysdAddlist = baseMapper.getSocialSoldierYsdAddVoList(dispatchIdList);
		if (ysdAddlist != null && !ysdAddlist.isEmpty()) {
			List<TSocialInfo> socialIdList = new ArrayList<>();
			TSocialInfo socialInfo;
			for (SocialSoldierYgsAddVo vo : ysdAddlist) {
				socialInfo = new TSocialInfo();
				socialInfo.setId(vo.getSocialId());
				socialIdList.add(socialInfo);
			}
			MultipartFile file = this.getFile(ysdAddlist, 3);
			if (Common.isNotNull(file)) {
				this.getOneAppGetModuleDetail(socialIdList, file, "医保增员");
			}
		}
		// 医生大减少列表
		List<SocialSoldierYgsAddVo> ysdReducelist = baseMapper.getSocialSoldierYsdReduceVoList(dispatchIdList);
		if (ysdReducelist != null && !ysdReducelist.isEmpty()) {
			List<TSocialInfo> socialIdList = new ArrayList<>();
			TSocialInfo socialInfo;
			for (SocialSoldierYgsAddVo vo : ysdReducelist) {
				socialInfo = new TSocialInfo();
				socialInfo.setId(vo.getSocialId());
				socialIdList.add(socialInfo);
			}
			MultipartFile file = this.getFile(ysdReducelist, 4);
			if (Common.isNotNull(file)) {
				this.getOneAppGetModuleDetail(socialIdList, file, "医保减员");
			}
		}
		if ((ygsAddlist == null || ygsAddlist.isEmpty())
				&& (ygsReducelist == null || ygsReducelist.isEmpty())
				&& (ysdAddlist == null || ysdAddlist.isEmpty())
				&& (ysdReducelist == null || ysdReducelist.isEmpty())
		) {
			return R.failed("无数据，推送结束！");
		}
		return R.ok("推送成功！！");
	}

	/**
	 * @Description: 推送社保士兵审核结果查询文件
	 * @Author: hgw
	 * @Date: 2024-5-23 18:02:27
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> pushSoldierByAudit() {
		// 养工失待审核列表
		List<SocialSoldierYgsAuditVo> ygsAddlist = baseMapper.getSocialSoldierYgsAuditVoList();
		log.info("养工失待审核列表="+ygsAddlist);
		String sheetName = "审核数据查询";
		if (ygsAddlist != null && !ygsAddlist.isEmpty()) {
			MultipartFile file = this.getFileByAudit(ygsAddlist, null, sheetName);
			if (Common.isNotNull(file)) {
				List<TSocialInfo> socialIdList = new ArrayList<>();
				TSocialInfo socialInfo;
				for (SocialSoldierYgsAuditVo vo : ygsAddlist) {
					socialInfo = new TSocialInfo();
					socialInfo.setId(vo.getSocialId());
					socialIdList.add(socialInfo);
				}
				this.getOneAppGetModuleDetailByAudit(socialIdList, file, sheetName);
			}
		}
		// 医生大【续保】待审核列表
		List<SocialSoldierYsdAuditVo> ysdXuBaolist = baseMapper.getSocialSoldierYsdAuditVoList();
		log.info("医生大【续保】待审核列表="+ysdXuBaolist);
		sheetName = "审核数据信息查询";
		if (ysdXuBaolist != null && !ysdXuBaolist.isEmpty()) {
			MultipartFile file = this.getFileByAudit(null, ysdXuBaolist, sheetName);
			if (Common.isNotNull(file)) {
				List<TSocialInfo> socialIdList = new ArrayList<>();
				TSocialInfo socialInfo;
				for (SocialSoldierYsdAuditVo vo : ysdXuBaolist) {
					socialInfo = new TSocialInfo();
					socialInfo.setId(vo.getSocialId());
					socialIdList.add(socialInfo);
				}
				this.getOneAppGetModuleDetailByAudit(socialIdList, file, sheetName);
			}
		}
		// 医生大【新增】待审核列表
		List<SocialSoldierYsdAuditVo> ysdAddlist = baseMapper.getSocialSoldierYsdAddAuditVoList();
		log.info("医生大【新增】待审核列表="+ysdAddlist);
		if (ysdAddlist != null && !ysdAddlist.isEmpty()) {
			MultipartFile file = this.getFileByAudit(null, ysdAddlist, sheetName);
			if (Common.isNotNull(file)) {
				List<TSocialInfo> socialIdList = new ArrayList<>();
				TSocialInfo socialInfo;
				for (SocialSoldierYsdAuditVo vo : ysdAddlist) {
					socialInfo = new TSocialInfo();
					socialInfo.setId(vo.getSocialId());
					socialIdList.add(socialInfo);
				}
				this.getOneAppGetModuleDetailByAudit(socialIdList, file, sheetName);
			}
		}
		if (ygsAddlist == null || ysdXuBaolist == null|| ysdAddlist == null) {
			return R.failed("无数据，推送结束！");
		}
		return R.ok("推送成功！！");
	}

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

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

}
