package cn.hmsoft.ai.face.baidu;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.baidu.aip.util.Base64Util;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import cn.hmsoft.ai.baidu.BaiduTokenService;
import cn.hmsoft.ai.face.FaceAI;
import cn.hmsoft.ai.face.FacePhoto;
import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.frame.constants.FrameSex;
import cn.hmsoft.helper.FileHelper;
import cn.hmsoft.helper.http.HttpHelper;

public class BaiduIdPhotoAI extends FaceAI {

	@Override
	protected FacePhoto distFaceByFile(File file, String id_card) {
		SpringHelper.getBean(BaiduTokenService.class).getBaiduToken();
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + BaiduTokenService.ACCESS_TOKEN;
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("image", Base64Util.encode(FileHelper.readFileByBytes(file.getPath())));
			map.put("max_face_num", "10");
			map.put("image_type", "BASE64");
			map.put("face_type", "CERT");
			map.put("face_field", "faceshape,facetype,age,gender,beauty");

			String param = new GsonBuilder().create().toJson(map);

			String result = HttpHelper.post(url, "application/json", param);
			//System.out.println(result);
			JsonObject json = new JsonParser().parse(result).getAsJsonObject();
			FacePhoto photo = new FacePhoto();

			BufferedImage sourceImg = ImageIO.read(new FileInputStream(file));
			photo.setPhoto_width(sourceImg.getWidth());
			photo.setPhoto_height(sourceImg.getHeight());
			int error_code = json.get("error_code").getAsInt();
			if (error_code == 0) {
				// {"error_code":0,"error_msg":"SUCCESS","log_id":305486828495045361,"timestamp":1572849504,"cached":0,"result":{"face_num":3,"face_list":[{"face_token":"459973baa9a22ccde3be486923cc00f6","location":{"left":419.15,"top":578.18,"width":59,"height":51,"rotation":-3},"face_probability":0.83,"angle":{"yaw":-14.12,"pitch":11.59,"roll":-0.8},"face_shape":{"type":"round","probability":0.48},"face_type":{"type":"human","probability":1},"age":19,"gender":{"type":"male","probability":1}},{"face_token":"da81263b4d9ded68611cedcee114b80d","location":{"left":780.6,"top":576.82,"width":54,"height":47,"rotation":-2},"face_probability":1,"angle":{"yaw":-17.43,"pitch":13.92,"roll":-0.03},"face_shape":{"type":"round","probability":0.62},"face_type":{"type":"human","probability":1},"age":31,"gender":{"type":"male","probability":1}},{"face_token":"53129bca7f94bbecf5e47f9b0f5368dd","location":{"left":1134.12,"top":575.5,"width":52,"height":40,"rotation":6},"face_probability":0.69,"angle":{"yaw":-34.6,"pitch":28.32,"roll":17.56},"face_shape":{"type":"round","probability":0.7},"face_type":{"type":"human","probability":1},"age":37,"gender":{"type":"male","probability":0.99}}]}}

				photo.setSuccess(true);
				JsonObject rs = json.getAsJsonObject("result");
				photo.setPerson_total(rs.get("face_num").getAsInt());
				if (photo.getPerson_total() > 0) {
					// 处理第一个人脸
					// {"face_token":"459973baa9a22ccde3be486923cc00f6","location":{"left":419.15,"top":578.18,"width":59,"height":51,"rotation":-3},"face_probability":0.83,"angle":{"yaw":-14.12,"pitch":11.59,"roll":-0.8},"face_shape":{"type":"round","probability":0.48},"face_type":{"type":"human","probability":1},"age":19,"gender":{"type":"male","probability":1}}
					JsonObject p = rs.getAsJsonArray("face_list").get(0).getAsJsonObject();
					// 图片ID
					photo.setPhoto_id(p.get("face_token").getAsString());
					// 人脸概率
					photo.setFace_probability((int) (p.get("face_probability").getAsDouble() * 100));
					// 年龄
					photo.setPerson_age((int) (p.get("age").getAsDouble() * 100));

					JsonObject g = p.get("gender").getAsJsonObject();
					// 性别
					String sex = g.get("type").getAsString();
					if ("male".equals(sex)) {
						photo.setPerson_sex(FrameSex.Male);
					} else
						photo.setPerson_sex(FrameSex.Female);
					// 性别可靠度
					photo.setPerson_sex_probability((int) (g.get("probability").getAsDouble() * 100));

					// 美颜
					photo.setPerson_beauty(p.get("beauty").getAsDouble());
					// 人脸旋转度
					JsonObject loc = p.get("location").getAsJsonObject();
					photo.setFace_rotation(loc.get("rotation").getAsInt());
					photo.setFace_height(loc.get("height").getAsDouble());
					photo.setFace_width(loc.get("width").getAsDouble());
					photo.setFace_left(loc.get("left").getAsDouble());
					photo.setFace_top(loc.get("top").getAsDouble());

					photo.setFace_height_percent(photo.getFace_height() / photo.getPhoto_height() * 100);
					photo.setFace_width_percent(photo.getFace_width() / photo.getPhoto_width() * 100);

				}
//				System.out.println("原图大小（高、宽）：" + photo.getPhoto_height() + " * " + photo.getPhoto_width());
//				System.out.println("头像大小（高、宽）：" + photo.getFace_height() + " * " + photo.getFace_width());
//				System.out
//						.println("头像占比（高、宽）：" + photo.getFace_height_percent() + " * " + photo.getFace_width_percent());
//				System.out.println("头像边距（上、左）：" + photo.getFace_left() + " * " + photo.getFace_top());
//
//				System.out.println("美丑打分分值：" + photo.getPerson_beauty());
//				System.out.println("美丑倾斜度：" + photo.getFace_rotation());

			} else {
				photo.setSuccess(false);
				if (error_code == 222202) {
					photo.setError_msg("未识别出头像信息，请重新上传照片！");
				}
			}
			return photo; 

		} catch (Exception e) {
			// e.printStackTrace();
		}

		return null;
	}

}
