package com.bcxin.identify.util.baidu.v3;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bcxin.identify.util.codes.CommonConst;
import com.bcxin.identify.util.common.StringUtil;
import com.bcxin.identify.util.sys.ConfigUtil;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/***
 * 百度人脸认证
 */
public class FaceMatch {

    /***
     *  日志
     */
    private static final Logger logger = LoggerFactory.getLogger(FaceMatch.class);

	private static int HIGH_FACE_LEVEL = 4;

	public static void setLevel(int level) {
		HIGH_FACE_LEVEL = level;
	}

	public static String faceMatch(String token, String param) {
		try {
			return HttpUtil.post(ConfigUtil.getValue(CommonConst.BAIDU_FACE_MATCH_URL), token, "application/json", param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/***
	 * 返回人像比对结果，通过返回true，不通过返回false
	 * @param img1 人像一地址
	 * @param img2 人像二地址
	 * @param vtp 阈值（通用80）
	 * @return  比对结果
	 */
	public static Map<String,String> matchResult(String token, String img1, String img2,int vtp,String faceBizMode) {
		Map<String, String> resultMap = Maps.newHashMap();
		boolean result = false;
		cn.hutool.json.JSONArray arr = JSONUtil.createArray();
		/* 不一样的模式采用不一样的照片比对方式 */
		if (CommonConst.FACE_BIZ_MODE_INITACCOUNT.equals(faceBizMode)) {
			arr.add(JSONUtil.parseObj(new IdCardFaceObj(img1)));
			arr.add(JSONUtil.parseObj(new LiveFaceObj(img2)));
		} else if (CommonConst.FACE_BIZ_MODE_FACEAUTH.equals(faceBizMode)) {
			arr.add(JSONUtil.parseObj(new SysExistsFaceObj(img1)));
			arr.add(JSONUtil.parseObj(new OffLineFaceObj(img2)));
		} else if (CommonConst.FACE_BIZ_MODE_UNIAPP.equals(faceBizMode)) {
			arr.add(JSONUtil.parseObj(new IdCardFaceObj(img1)));
			arr.add(JSONUtil.parseObj(new LiveFaceObj(img2)));
//			arr.add(JSONUtil.parseObj(new NoLiveFaceObj(img2)));
		} else if (CommonConst.FACE_BIZ_MODE_HIGHLIVENESS.equals(faceBizMode)) {
			arr.add(JSONUtil.parseObj(new IdCardFaceObj(img1)));
			HighLiveFaceObj high = new HighLiveFaceObj(img2);
			switch (HIGH_FACE_LEVEL) {
				case 1:
					high.setLiveness_control("NONE");
					break;
				case 2:
					high.setLiveness_control("LOW");
					break;
				case 3:
					high.setLiveness_control("NORMAL");
					break;
				default:
					high.setLiveness_control("HIGH");
					break;
			}
			arr.add(JSONUtil.parseObj(high));
		} else {
			arr.add(JSONUtil.parseObj(new DefaultFaceObj(img1)));
			arr.add(JSONUtil.parseObj(new DefaultFaceObj(img2)));
		}
		//人像比对
		String matchStr = faceMatch(token, arr.toString());
		logger.warn("FACE-THAN-FOR-BAIDU==>Time:{},param:{} result:{}", matchStr, DateUtil.now(), arr);
		//碰到图片下载失败，等待2秒重新请求一次
		if(StringUtils.isNotEmpty(matchStr)&& matchStr.contains("image download fail")){
			try {
				matchStr = base64MatchResult( token, img1, img2, faceBizMode);
				logger.warn("FACE-THAN-FOR-BAIDU (RETRY)==>Time:{},param:{} result:{}", DateUtil.now(), arr, matchStr);
			} catch (Exception e) {
				logger.error("FACE-THAN-FOR-BAIDU (RETRY)==>Time:{},param:{} result:{}", DateUtil.now(), arr, e.getMessage());
			}
		}
		resultMap.put("param", arr.toString());
		resultMap.put("resContent", matchStr);
		if (StringUtil.isNotEmpty(matchStr)) {
			//json格式转换
			JSONObject data = JSONUtil.parseObj(matchStr);
			resultMap.put("response",BDErrorEnum.errorMsg(data.get("error_msg").toString()));
			if ("SUCCESS".equals(data.get("error_msg"))) {
				JSONObject res = JSONUtil.parseObj(data.get("result"));
				Object score = res.get("score");
				//大等于阈值是同个人
				if (score != null && Double.parseDouble(String.valueOf(score)) >= vtp) {
					result = true;
				}else{
					resultMap.put("response","比对结果未达阈值标准，人脸不匹配");
				}
			}
		}
		resultMap.put("result", result ? "1" : "0");
		return resultMap;
	}

	public static String base64MatchResult(String token, String img1, String img2,String faceBizMode){
		String base64_img1 = remoteImageToBase64(img1);
		String base64_img2 = remoteImageToBase64(img2);
		cn.hutool.json.JSONArray arr = JSONUtil.createArray();
		/* 不一样的模式采用不一样的照片比对方式 */
		if (CommonConst.FACE_BIZ_MODE_INITACCOUNT.equals(faceBizMode)) {
			IdCardFaceObj idCardFaceObj = new IdCardFaceObj(base64_img1);
			idCardFaceObj.setImage_type("BASE64");
			LiveFaceObj liveFaceObj = new LiveFaceObj(base64_img2);
			liveFaceObj.setImage_type("BASE64");
			arr.add(JSONUtil.parseObj(idCardFaceObj));
			arr.add(JSONUtil.parseObj(liveFaceObj));
		} else if (CommonConst.FACE_BIZ_MODE_FACEAUTH.equals(faceBizMode)) {
			SysExistsFaceObj sysExistsFaceObj = new SysExistsFaceObj(base64_img1);
			sysExistsFaceObj.setImage_type("BASE64");
			OffLineFaceObj offLineFaceObj = new OffLineFaceObj(base64_img2);
			offLineFaceObj.setImage_type("BASE64");
			arr.add(JSONUtil.parseObj(sysExistsFaceObj));
			arr.add(JSONUtil.parseObj(offLineFaceObj));
		} else if (CommonConst.FACE_BIZ_MODE_UNIAPP.equals(faceBizMode)) {
			IdCardFaceObj idCardFaceObj = new IdCardFaceObj(base64_img1);
			idCardFaceObj.setImage_type("BASE64");
			LiveFaceObj liveFaceObj = new LiveFaceObj(base64_img2);
			liveFaceObj.setImage_type("BASE64");
			arr.add(JSONUtil.parseObj(idCardFaceObj));
			arr.add(JSONUtil.parseObj(liveFaceObj));
//			arr.add(JSONUtil.parseObj(new NoLiveFaceObj(img2)));
		} else if (CommonConst.FACE_BIZ_MODE_HIGHLIVENESS.equals(faceBizMode)) {
			IdCardFaceObj idCardFaceObj = new IdCardFaceObj(base64_img1);
			idCardFaceObj.setImage_type("BASE64");
			arr.add(JSONUtil.parseObj(idCardFaceObj));
			HighLiveFaceObj high = new HighLiveFaceObj(base64_img2);
			high.setImage_type("BASE64");
			switch (HIGH_FACE_LEVEL) {
				case 1:
					high.setLiveness_control("NONE");
					break;
				case 2:
					high.setLiveness_control("LOW");
					break;
				case 3:
					high.setLiveness_control("NORMAL");
					break;
				default:
					high.setLiveness_control("HIGH");
					break;
			}
			arr.add(JSONUtil.parseObj(high));
		} else {
			DefaultFaceObj defaultFaceObj1 = new DefaultFaceObj(base64_img1);
			defaultFaceObj1.setImage_type("BASE64");
			DefaultFaceObj defaultFaceObj2 = new DefaultFaceObj(base64_img2);
			defaultFaceObj2.setImage_type("BASE64");
			arr.add(JSONUtil.parseObj(defaultFaceObj1));
			arr.add(JSONUtil.parseObj(defaultFaceObj2));
		}
		//人像比对
		return faceMatch(token, arr.toString());
	}
	
	public static String remoteImageToBase64(String imgUrl) {
		HttpURLConnection conn = null;
		InputStream inStream = null;
		ByteArrayOutputStream output = null;
		try {
			URL url = new URL(imgUrl);
			conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10 * 1000);
			// 流处理
			inStream = conn.getInputStream();


			output = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = inStream.read(buffer)) != -1) {
				output.write(buffer, 0, length);
			}
			// 获取字节数组并进行Base64编码
			return Base64.encodeBase64String(output.toByteArray());
		} catch (Exception e) {
			logger.error("图片文件转存异常："+e.getMessage(),e);
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return "";
	}

	public static String testMatchResult(String token, String img1, String img2, int vtp){
		cn.hutool.json.JSONArray arr = JSONUtil.createArray();
		arr.add(JSONUtil.parseObj(new DefaultFaceObj(img1)));
		arr.add(JSONUtil.parseObj(new DefaultFaceObj(img2)));
		//人像比对
		return faceMatch(token, arr.toString());
	}

	public static void main(String[] args) {
		String img1 = "https://zafkxt.jcgov.gov.cn/obpm/uploads/2025/05-23/6f17d34e-8b59-4e2d-984b-668e44058abd/1747967147605.jpg";
//		String img1 = "https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com/upload%2F2021-03-26%2F1616751658163271824.png";
		/*String img2 = "https://bcxin-saas-prod.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2021-03-26%2F1616751667243633700.jpg";
		int vtp = 80;
		System.out.println(FaceMatch.matchResult("",img1, img2,vtp,"HIGHLIVENESS"));*/

		System.out.println(remoteImageToBase64(img1));

		//String img1 = "http://bcxinsaasprod.baibaodun.cn/upload%2F2020-10-27%2F1603762307292760611.jpg";
		//String img2 = "http://bcxinsaasprod.baibaodun.cn/upload%2F2020-06-06%2F1591419255585532065.jpg";
		//int vtp = 80;
		//System.out.println(FaceMatch.matchResult("",img1, img2, vtp));

		//System.out.println(cn.hutool.http.HttpUtil.downloadFile("http://bcxinsaasprod.baibaodun.cn/upload%2F2020-10-27%2F1603762307292760611.jpg",a));
	}
	
}