package org.springblade.command.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springblade.command.pojo.entity.FzyjFjEntity;
import org.springblade.command.pojo.vo.FileuploadVO;
import org.springblade.command.pojo.vo.FzyjFkVO;
import org.springblade.command.pojo.vo.FzyjYjVO;
import org.springblade.command.pojo.vo.WaitedUrgentRisksVO;
import org.springblade.common.utils.Base64Util;
import org.springblade.core.http.util.HttpUtil;
import org.springframework.stereotype.Component;

import java.io.File;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Component
public class FzyjUtil {
	private FzyjUtil() {
	}

	public final static DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");

	public final static DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmm");

	/**
	 * 身份鉴权
	 */
	public static String getSignature(String account, String apiKey, String calltime, String... params) {
		String signature = "";
		try {
			// 创建MessageDigest对象来执行SHA1加密算法
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			// 转换待加密数据为字节数组
			String data = calltime;
			if (params != null && params.length > 0) {
				for (int i = 0; i < params.length; i++) {
					if (StringUtils.isNotBlank(params[i])) {
						// 按参数的英文名顺序 排序拼接
						data = data + params[i];
					}
				}
			}
			data = data + account + apiKey;
			byte[] bytes = data.getBytes();
			// 执行SHA1加密
			digest.update(bytes);
			byte[] hashedBytes = digest.digest();
			// 转换加密后的字节数组为十六进制字符串
			StringBuilder hexString = new StringBuilder();
			for (byte b : hashedBytes) {
				String hex = Integer.toHexString(0xFF & b);
				if (hex.length() == 1) {
					hexString.append('0');
				}
				hexString.append(hex);
			}
			// 加密结果
			signature = hexString.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return signature;
	}

	/**
	 * 受理紧急高危预警信息
	 * 受理紧急高危反诈预警信息，告诉96110受理这些预警信息了，这样下回再拉取待处理的紧急高危预警时，这些已受理的预警就不会再拉取出来了
	 * 账号 account
	 * 调用时间 callTime，格式为yyyymmddhh24miss
	 * 加密后的指纹 signature
	 * 预警下发日期 issuedDay，格式为yyyymmdd
	 * 受理的预警的同步预警记录syncId数组 risks
	 */
	public static void markUrgentRisks(String account, String apiKey, String markUrgentRisksUrl, String[] risks) {
		String calltime = LocalDateTime.now().format(formatter2);
		String issuedDay = LocalDateTime.now().format(formatter1);
		String risk = "";
		for (int i = 0; i < risks.length; i++) {
			risk = risk + risks[i];
		}
		// 身份鉴权
		String signature = FzyjUtil.getSignature(account, apiKey, calltime, issuedDay, risk);
		// 调用 拉取预警信息 的接口
		Map<String, Object> map = new HashMap<>();
		map.put("account", account);
		map.put("calltime", calltime);
		map.put("issuedDay", issuedDay);
		map.put("risks", risks);
		map.put("signature", signature);
		String result = HttpUtil.post(markUrgentRisksUrl, map);
		// 处理返回结果
		WaitedUrgentRisksVO waitedUrgentRisksVO = JSONObject.parseObject(result, WaitedUrgentRisksVO.class);
	}

	/**
	 * 紧急高危预警反馈处置
	 */
	public static void feedbackUrgentRisks(String account, String apiKey, String feedbackUrgentRisksUrl, FzyjFkVO fzyjFkVO) {

		String calltime = LocalDateTime.now().format(FzyjUtil.formatter2);
		String disposalWayDct = fzyjFkVO.getDisposalWayDct(); // 处置方式
		String feedbackId = fzyjFkVO.getFeedbackId(); // 反馈人工号
		String feedbackIdcard = fzyjFkVO.getFeedbackIdcard(); // 反馈人身份证号，要确保和国家反诈系统中保存的身份证号保持一致
		String feedbackName = fzyjFkVO.getFeedbackName(); // 反馈人姓名
		String feedbackResultDct = fzyjFkVO.getFkjgDm(); // 反馈结果  1-未被骗  2-已被骗  3-未知
		String feedbackUnit = fzyjFkVO.getFeedbackUnit(); // 6位数字的单位编码（精度到区县），要确保是反馈人所属单位编码，参考《单位码表.xlsx》
		String fsafadsDct = fzyjFkVO.getFsafadsDct(); // 反馈情况
		String localUrl = fzyjFkVO.getLocalUrl(); // 附件的url地址（96110平台上的）
		String seeName = fzyjFkVO.getSeeName(); // 见面民警，如张三
		String seeResult = fzyjFkVO.getJmjgDm(); // 见面结果  1-成功见面  2-暂未见到本人  3-无法见到本人
		String seeUnit = fzyjFkVO.getSeeUnit(); // 见面单位，如xx派出所
		String seeUrl = fzyjFkVO.getJmdq() + fzyjFkVO.getJmdz(); // 见面地址，如xx市xx街xx小区
		Long syncId = fzyjFkVO.getSyncId(); // 同步的预警记录id
		String victimIdcard = fzyjFkVO.getShrList().get(0).getSfzh(); // 受害人身份证号
		String victimName = fzyjFkVO.getShrList().get(0).getXm(); // 受害人姓名
		String victimPhone = fzyjFkVO.getShrList().get(0).getSjh(); // 受害人手机号
		String webUrl = fzyjFkVO.getWebUrl(); // 附件的url地址（国家反诈平台上的）
		// 身份鉴权
		String signature = FzyjUtil.getSignature(account, apiKey, calltime, disposalWayDct, feedbackId, feedbackIdcard, feedbackName, feedbackResultDct,
						feedbackUnit, fsafadsDct, localUrl, seeName, seeResult, seeUnit, seeUrl, syncId.toString(), victimIdcard, victimName, victimPhone, webUrl);
		// 调用 拉取预警信息 的接口
		Map<String, Object> map = new HashMap<>();
		map.put("account", account);
		map.put("calltime", calltime);
		map.put("signature", signature);
		map.put("syncId", syncId);
		map.put("victimName", victimName);
		map.put("victimIdcard", victimIdcard);
		map.put("victimPhone", victimPhone);
		map.put("disposalWayDct", disposalWayDct);
		map.put("fsafadsDct", fsafadsDct);
		map.put("feedbackResultDct", feedbackResultDct);
		map.put("seeResult", seeResult);
		map.put("seeUnit", seeUnit);
		map.put("seeName", seeName);
		map.put("seeUrl", seeUrl);
		map.put("webUrl", webUrl);
		map.put("localUrl", localUrl);
		map.put("feedbackUnit", feedbackUnit);
		map.put("feedbackIdcard", feedbackIdcard);
		map.put("feedbackId", feedbackId);
		map.put("feedbackName", feedbackName);
		String result = HttpUtil.post(feedbackUrgentRisksUrl, map);
		// 处理返回结果
		FileuploadVO fileuploadVO = JSONObject.parseObject(result, FileuploadVO.class);
	}

	/**
	 * 附件文件上传
	 */
	public static String fileupload(String fileuploadUrl, String localPath, FzyjFjEntity fzyjFjEntity) {
		String fileBase64 = fzyjFjEntity.getFile();
		// base64 转 File
		File file = Base64Util.base64ToFile(fileBase64, localPath + fzyjFjEntity.getSyncId() + "." + fzyjFjEntity.getFileSuffix());
		Map<String, String> headers = new HashMap<>();
		headers.put("Content-Type", "multipart/form-data");
		String respContent = "";
		// 调用第三方接口上传附件
//		respContent = SendFileUtil.doPostUploadFile(fileuploadUrl, headers, file);
		return respContent;
	}

	/**
	 * 移交或指派高危预警
	 */
	public static void dealUrgentRisks(String account, String apiKey, String dealUrgentRisksUrl, FzyjYjVO fzyjYjVO, FzyjFkVO fzyjFkVO) {
		String calltime = LocalDateTime.now().format(FzyjUtil.formatter2);
		String assignRemark = fzyjYjVO.getTransferMsg(); // 指派或移交说明
		String assignUnit = fzyjYjVO.getTargetUnitCode(); // 指派或移交单位代码，参考《单位码表.xlsx》
		String assignUnitName = fzyjYjVO.getTargetUnitName(); // 指派或移交单位名称，参考《单位码表.xlsx》
		String createBy = fzyjFkVO.getFeedbackId(); // 处置人工号
		String disposeUnit = fzyjFkVO.getFeedbackUnit(); // 处置单位，参考《单位码表.xlsx》
		String disposeUnitName = fzyjFkVO.getSeeUnit(); // 处置单位名称，参考《单位码表.xlsx》
		int sendType = fzyjYjVO.getSendType(); // 发派方式 1指派 2移交
		Long syncId = fzyjYjVO.getSyncId(); // 同步的预警记录id
		String victimIdcard = ""; // 受害人身份证号
		String victimName = ""; // 受害人姓名
		String victimPhone = ""; // 受害人手机号
		// 身份鉴权
		String signature = FzyjUtil.getSignature(account, apiKey, calltime, assignRemark, assignUnit, assignUnitName, createBy,
			disposeUnit, disposeUnitName, String.valueOf(sendType), syncId.toString(), victimIdcard, victimName, victimPhone);
		// 调用 拉取预警信息 的接口
		Map<String, Object> map = new HashMap<>();
		map.put("account", account);
		map.put("calltime", calltime);
		map.put("signature", signature);
		map.put("syncId", syncId);
		map.put("assignRemark", assignRemark);
		map.put("assignUnit", assignUnit);
		map.put("assignUnitName", assignUnitName);
		map.put("createBy", createBy);
		map.put("disposeUnit", disposeUnit);
		map.put("disposeUnitName", disposeUnitName);
		map.put("sendType", sendType);
		map.put("victimIdcard", victimIdcard);
		map.put("victimName", victimName);
		map.put("victimPhone", victimPhone);
		String result = HttpUtil.post(dealUrgentRisksUrl, map);
	}
}
