/*
 *    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.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.TSocialInfo;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TSocialSoldierMapper;
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.SocialSoldierYgsAddVo;
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.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;

	/**
	 * @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);
						log.error("社保增员TWO_STRING="+socialInfo.getId());
					} else {
						socialInfo.setYsdAddId(addId);
						socialInfo.setYsdHandleStatus(CommonConstants.TWO_STRING);
						log.error("医疗增员TWO_STRING="+socialInfo.getId());
					}
				}
				tSocialInfoService.updateBatchById(socialList);
			}
		}
		return R.ok("推送成功！");
	}

	public MultipartFile getFile(List<SocialSoldierYgsAddVo> list) {
		File file = null;
		if (list != null) {
			String filePath = "socialFile" + DateUtil.getThisTime() + CommonConstants.XLSX;
			EasyExcelFactory.write(filePath, SocialSoldierYgsAddVo.class).sheet("社保明细").doWrite(list);
			file = new File(filePath);
		}
		if (file != null) {
			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.error("dispatchIdList="+dispatchIdList);
		// 社保增员、社保减员、医保增员、医保减员
		// 养工失新增列表
		List<SocialSoldierYgsAddVo> ygsAddlist = baseMapper.getSocialSoldierYgsAddVoList(dispatchIdList);
		log.error("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);
			if (Common.isNotNull(file)) {
				log.error("社保增员");
				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);
			if (Common.isNotNull(file)) {
				log.error("社保减员");
				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);
			if (Common.isNotNull(file)) {
				log.error("医保增员");
				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);
			if (Common.isNotNull(file)) {
				log.error("医保减员");
				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("推送成功！！");
	}

}
