package cn.hmsoft.hmplatform.identity.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import cn.hmsoft.ai.baidu.BaiduTokenService;
import cn.hmsoft.ai.identity.IdentifiedResult;
import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.hmplatform.helper.HttpClientHelper;
import cn.hmsoft.hmplatform.helper.ParamHelper;
import cn.hmsoft.hmplatform.identity.baidu.BaiduOpenApiTokenService;
import cn.hmsoft.hmplatform.identity.baidu.OpenApiParamUtil;
import cn.hmsoft.hmplatform.identity.util.EncodeHelper;
import cn.hmsoft.log.LogHelper;

@Service
public class FaceMatchService {
	/**
	 * @百度比对.
	 * @param image_file1 照片文件1
	 * @param image_file2 照片文件2
	 * @return
	 */
	public IdentifiedResult baiduMatch(String img1, String img2) {
		IdentifiedResult result = new IdentifiedResult();
		SpringHelper.getBean(BaiduTokenService.class).getBaiduToken();
		String url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + BaiduTokenService.ACCESS_TOKEN;
		//头部参数
		Map<String, Object> headerMap = new HashMap<String, Object>();
		//创建请求参数
		Set<Object> param = new HashSet<Object>();
		//执行请求
		try {
			Map<String, Object> pic1Map = new HashMap<String, Object>();
			if (img1.startsWith("http")) {
				pic1Map.put("image", EncodeHelper.encodeUrlImageToBase64(img1));
			} else {
				pic1Map.put("image", Base64.getEncoder().encodeToString(org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(new File(img1)))));
			}
			pic1Map.put("image_type", "BASE64");
			pic1Map.put("face_type", "LIVE");
			pic1Map.put("quality_control", "NONE");//质量要求要低
			pic1Map.put("liveness_control", "NONE");
			
			Map<String, Object> pic2Map = new HashMap<String, Object>();
			if (img2.startsWith("http")) {
				pic2Map.put("image", EncodeHelper.encodeUrlImageToBase64(img2));
			} else {
				pic2Map.put("image", Base64.getEncoder().encodeToString(org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(new File(img2)))));
			}
			pic2Map.put("image_type", "BASE64");
			pic2Map.put("face_type", "LIVE");
			pic2Map.put("quality_control", "NONE");//质量要求要低
			pic2Map.put("liveness_control", "NONE");
			
			param.add(pic1Map);
			param.add(pic2Map);
			
			Gson gson = new Gson();
			String requestBody = gson.toJson(param);
			LogHelper.info(requestBody);
			//提交请求
			long startTime = System.currentTimeMillis();
			String json = HttpClientHelper.postJson(url, requestBody, headerMap);
			long endTime = System.currentTimeMillis();
			
			JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
			LogHelper.info("比对结果-----> " + json);
			LogHelper.info("执行时间: " + (endTime-startTime) / 1000.0);
			
			result.setError_msg(jsonObject.get("error_msg").getAsString());
			result.setSuccess(jsonObject.get("error_code").getAsInt() == 0 ? true : false);
			result.setPercent(jsonObject.getAsJsonObject("result").get("score").getAsDouble());
		} catch(Exception e) {
			result.setSuccess(false);
			result.setError_msg(e.getMessage());
			LogHelper.error(e);
		}
		return result;
	}
	
	/**
	 * 公司离线比对
	 * @param img1
	 * @param img2
	 * @param key_pass
	 * @return
	 */
	public IdentifiedResult hmFaceMatch(String img1, String img2, String key_pass) {
		IdentifiedResult result = new IdentifiedResult();
		result.setError_msg("");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("key_pass", key_pass);
		try {
			if (img1.startsWith("http")) {
				params.put("img1", EncodeHelper.encodeUrlImageToBase64(img1));
			} else {
				params.put("img1", img1);
			}
			
			if (img2.startsWith("http")) {
				params.put("img2", EncodeHelper.encodeUrlImageToBase64(img2));
			} else {
				params.put("img2", img2);
			}
			String hmFaceUrl = ParamHelper.getParamValue("HmFaceUrl", "http://39.98.40.30:8080/f/platform/face/match.htm");
			String json = HttpClientHelper.post(hmFaceUrl, params);
			JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
			if (jsonObject.get("errorCode").getAsInt() == 0) {
				double score = Double.valueOf(jsonObject.get("entity") != null ? jsonObject.get("entity").getAsString() : "0");
				result.setPercent(score);
				result.setSuccess(true);
			} else {
				result.setSuccess(false);
				result.setError_msg(jsonObject.get("errorMsg").getAsString());
			}
			
		} catch (Exception e) {
			result.setSuccess(false);
			result.setError_msg(e.getMessage());
		}
		return result;
	}
	
	/**
	 * @语音字节数据.
	 * @param text
	 * @param cuid
	 * @return
	 * @throws Exception 
	 */
	public byte[] text2AudioBytes(String text, String cuid) throws BusinessException {
		byte[] bytes = null;
		FrameAssertUtil.isNotEmpty(text, "语音文件不能为空!");
		if (StringHelper.isEmpty(cuid)) {
			cuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
		}
		SpringHelper.getBean(BaiduOpenApiTokenService.class).getBaiduToken();
	    String params = "tex=" + OpenApiParamUtil.urlEncode(OpenApiParamUtil.urlEncode(text));
        params += "&lan=zh&ctp=1&aue=3&per=0&spd=5&pit=5&vol=5&cuid=" + cuid + "&tok=" + BaiduOpenApiTokenService.ACCESS_TOKEN;
        //aue-下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
        String url = "http://tsn.baidu.com/text2audio?" + params;
        try {
	        //执行请求
	        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
	        conn.setDoInput(true);
	        conn.setDoOutput(true);
	        conn.setConnectTimeout(5000);
	        PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
	        printWriter.write(params);
	        printWriter.close();
	        String contentType = conn.getContentType();
	        if (contentType.contains("audio/")) {
	           bytes = OpenApiParamUtil.getResponseBytes(conn);
	        } else {
	        	LogHelper.info("ERROR: content-type= " + contentType);
	            String res = OpenApiParamUtil.getResponseString(conn);
	            throw new BusinessException(res);
	        }
        } catch(Exception e) {
        	throw new BusinessException(e.getMessage());
        }
        return bytes;
	}
}
