package com.yifu.cloud.plus.v1.yifu.social.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
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.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.CheckedException;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hgw
 * @Date: 2024-5-8 15:00:58
 * @Description:
 * @return: 企业微信配置
 **/
@Configuration
@Data
@Slf4j
public class SocialConfig {

	// 秘钥
	@Value("${soldier.authorizations}")
	private String authorizations;
	// url前缀
	@Value("${soldier.urlPre}")
	private String urlPre;

	// 社保士兵——1功能列表的KEY
	private final String APP_GET_MODULE_DETAIL = "APP_GET_MODULE_DETAIL";
	// 社保士兵——2可执行设备
	private final String TERMINALS_BY_FUNCTION = "TERMINALS_BY_FUNCTION";
	// 社保士兵——5查看结果
	private final String GET_FIVE_JOB = "GET_FIVE_JOB";

	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * @Description: 1：获取功能列表接口
	 * @Author: hgw
	 * @Date: 2024-5-8 15:07:45
	 * @return: java.lang.String
	 **/
	public Map<String, String> getOneModuleDetailMap(RestTemplate restTemplate) {
		Map<String, String> sheMap = new HashMap<>();
		Object wxToken = redisTemplate.opsForValue().get(APP_GET_MODULE_DETAIL);
		if (null != wxToken) {
			return (Map<String, String>) wxToken;
		} else {
			String moduleDetailUrl = urlPre + "/api/basedata/appgetmoduledetail";
			HttpHeaders headers = new HttpHeaders();
			MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
			headers.setContentType(type);
			headers.add("accept", MediaType.TEXT_PLAIN.toString());
			headers.add("Authorization", authorizations);
			HttpEntity<String> formEntity = new HttpEntity<>(headers);
			ResponseEntity response = restTemplate.exchange(moduleDetailUrl, HttpMethod.GET, formEntity, String.class);
			if (Common.isEmpty(response) || Common.isEmpty(response.getBody())) {
				throw new CheckedException("获取社保士兵功能列表接口失败");
			}
			int status = response.getStatusCodeValue();
			if (status != 200) {
				throw new CheckedException("获取社保士兵功能列表接口失败，status="+status);
			}
			String body = (String) response.getBody();
			JSONObject bodyObject = JSON.parseObject(body);
			String code = bodyObject.getString("code");
			if (!"200".equals(code)) {
				throw new CheckedException("获取社保士兵功能列表接口失败，code="+code);
			}
			JSONArray dataArr = (JSONArray) bodyObject.get("data");
			JSONObject dataArrObj;
			JSONObject childrenArrObj;
			JSONObject sheBaoArrObj;
			JSONArray childrenArr;
			JSONArray sheBaoArr;
			for (int i = 0; i<dataArr.size(); i++) {
				dataArrObj = (JSONObject) dataArr.get(i);
				if ("合肥".equals(dataArrObj.get("label"))) {
					childrenArr = (JSONArray) dataArrObj.get("children");
					for (int j = 0; j<childrenArr.size(); j++) {
						childrenArrObj = (JSONObject) childrenArr.get(j);
						if ("社保".equals(childrenArrObj.get("label"))) {
							sheBaoArr = (JSONArray) childrenArrObj.get("children");
							for (int k = 0; k<sheBaoArr.size(); k++) {
								sheBaoArrObj = (JSONObject) sheBaoArr.get(k);
								if ("社保增员".equals(sheBaoArrObj.get("label"))) {
									sheMap.put("社保增员", sheBaoArrObj.getString("value"));
								} else if ("社保减员".equals(sheBaoArrObj.get("label"))) {
									sheMap.put("社保减员", sheBaoArrObj.getString("value"));
								}
							}
						} else if ("医保".equals(childrenArrObj.get("label"))) {
							sheBaoArr = (JSONArray) childrenArrObj.get("children");
							for (int k = 0; k<sheBaoArr.size(); k++) {
								sheBaoArrObj = (JSONObject) sheBaoArr.get(k);
								if ("医保增员".equals(sheBaoArrObj.get("label"))) {
									sheMap.put("医保增员", sheBaoArrObj.getString("value"));
								} else if ("医保减员".equals(sheBaoArrObj.get("label"))) {
									sheMap.put("医保减员", sheBaoArrObj.getString("value"));
								}
							}
						}
					}
				}
			}
		}
		if (Common.isEmpty(sheMap)) {
			throw new CheckedException("获取社保士兵功能列表接口数据失败！");
		}
		redisTemplate.opsForValue().set(APP_GET_MODULE_DETAIL, sheMap);
		redisTemplate.expire(APP_GET_MODULE_DETAIL, 3600, TimeUnit.SECONDS);
		return sheMap;
	}

	/**
	 * @Description: 2：获取可执行的设备接口Id
	 * @Author: hgw
	 * @Date: 2024-5-8 15:07:45
	 * @return: java.lang.String
	 **/
	public String getTwoTerminalId(RestTemplate restTemplate, String moduleId) {
		if (Common.isEmpty(moduleId)) {
			return null;
		}
		String terminalId = null;
		Object wxToken = redisTemplate.opsForValue().get(TERMINALS_BY_FUNCTION);
		if (null != wxToken) {
			return (String) wxToken;
		} else {
			String moduleDetailUrl = urlPre + "/api/terminal/getterminalsbyfunction?id="+moduleId;
			HttpHeaders headers = new HttpHeaders();
			MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
			headers.setContentType(type);
			headers.add("accept", MediaType.TEXT_PLAIN.toString());
			headers.add("Authorization", authorizations);
			HttpEntity<String> formEntity = new HttpEntity<>(headers);
			ResponseEntity response = restTemplate.exchange(moduleDetailUrl, HttpMethod.GET, formEntity, String.class);
			if (Common.isEmpty(response) || Common.isEmpty(response.getBody())) {
				throw new CheckedException("获取社保士兵【可执行的设备接口】失败");
			}
			int status = response.getStatusCodeValue();
			if (status != 200) {
				throw new CheckedException("获取社保士兵【可执行的设备接口】失败，status="+status);
			}
			String body = (String) response.getBody();
			JSONObject bodyObject = JSON.parseObject(body);
			String code = bodyObject.getString("code");
			if (!"200".equals(code)) {
				throw new CheckedException("获取社保士兵【可执行的设备接口】失败，code="+code);
			}
			JSONArray dataArr = (JSONArray) bodyObject.get("data");
			if (dataArr != null && !dataArr.isEmpty()) {
				terminalId = ((JSONObject)dataArr.get(0)).getString("value");
			}
		}
		if (Common.isEmpty(terminalId)) {
			throw new CheckedException("获取社保士兵【可执行的设备接口】数据失败！");
		}
		redisTemplate.opsForValue().set(TERMINALS_BY_FUNCTION, terminalId);
		redisTemplate.expire(TERMINALS_BY_FUNCTION, 3600, TimeUnit.SECONDS);
		return terminalId;
	}

	/**
	 * @Description: 3：上传任务文件与附件接口
	 * @Author: hgw
	 * @Date: 2024-5-8 15:07:45
	 * @return: java.lang.String
	 **/
	public String getThreeTerminalId(RestTemplate restTemplate, MultipartFile file) {
		String fileUrl;
		String moduleDetailUrl = urlPre + "/api/file/upload";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.MULTIPART_FORM_DATA);
		headers.add("accept", MediaType.TEXT_PLAIN.toString());
		headers.add("Authorization", authorizations);
		MultiValueMap<String, Object> resultMap = new LinkedMultiValueMap<>();
		try {
			ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
				@Override
				public String getFilename() {
					return file.getOriginalFilename();
				}
				@Override
				public long contentLength() {
					return file.getSize();
				}
			};
			resultMap.add("file", fileAsResource);
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(resultMap,headers);
		String dataResultList = restTemplate.postForObject(moduleDetailUrl, formEntity, String.class);
		JSONObject bodyObject = JSON.parseObject(dataResultList);
		String code = bodyObject.getString("code");
		if (!"200".equals(code)) {
			throw new CheckedException("获取社保士兵【上传任务文件与附件接口】失败，code="+code);
		}
		fileUrl = bodyObject.getString("data");
		return fileUrl;
	}

	/**
	 * @Description: 4：新增任务接口
	 * @Author: hgw
	 * @Date: 2024-5-8 15:07:45
	 * @return: java.lang.String
	 **/
	public String getFourAppAdd(RestTemplate restTemplate, String jobFile, String moduleDetailId, String terminalId) {
		String addId;
		String appAddUrl = urlPre + "/api/job/appadd";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.add("accept", MediaType.TEXT_PLAIN.toString());
		headers.add("Authorization", authorizations);
		JSONObject json = new JSONObject();
		json.put("jobFile", jobFile);
		json.put("jobAnnex", null);
		json.put("moduleDetailId", moduleDetailId);
		json.put("terminalId", terminalId);
		HttpEntity<String> formEntity = new HttpEntity<>(json.toString(), headers);
		String dataResultList = restTemplate.postForObject(appAddUrl, formEntity, String.class);
		JSONObject bodyObject = JSON.parseObject(dataResultList);
		String code = bodyObject.getString("code");
		if (!"200".equals(code)) {
			throw new CheckedException("获取社保士兵【新增任务接口】失败，code="+code);
		}
		addId = bodyObject.getString("data");
		return addId;
	}

	/**
	 * @Description: 5：任务查询接口
	 * @Author: hgw
	 * @Date: 2024-5-8 15:07:45
	 * @return: java.lang.String
	 **/
	public R<String> getFiveJob(RestTemplate restTemplate, String addId) {
		if (Common.isEmpty(addId)) {
			return null;
		}
		String resultFile = null;
		String moduleDetailUrl = urlPre + "/api/job/getjob?id="+addId;
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("accept", MediaType.TEXT_PLAIN.toString());
		headers.add("Authorization", authorizations);
		HttpEntity<String> formEntity = new HttpEntity<>(headers);
		ResponseEntity response = restTemplate.exchange(moduleDetailUrl, HttpMethod.GET, formEntity, String.class);
		if (Common.isEmpty(response) || Common.isEmpty(response.getBody())) {
			throw new CheckedException("获取社保士兵【任务查询接口】失败");
		}
		int status = response.getStatusCodeValue();
		if (status != 200) {
			throw new CheckedException("获取社保士兵【任务查询接口】失败，status="+status);
		}
		String body = (String) response.getBody();
		JSONObject bodyObject = JSON.parseObject(body);
		JSONObject dataObject = (JSONObject) bodyObject.get("data");
		String statusStr = dataObject.getString("status");
		if (!"完成".equals(statusStr)) {
			return R.failed(statusStr);
		}
		resultFile = dataObject.getString("resultFile");
		if (Common.isEmpty(resultFile)) {
			return R.failed(resultFile);
		}
		return R.ok(resultFile);
	}

}
