package tech.glinfo.enbao.common.controller;

import com.baidu.aip.face.AipFace;
import tech.glinfo.enbao.common.utils.BaiDuAPIUtils;
import tech.glinfo.enbao.common.utils.R;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * Controller公共组件
 *
 * @author Mark linzhenjie@gltech.com
 */
public abstract class BdAbstractController {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected R baiduDetect(String image) {
		AipFace apiFace = BaiDuAPIUtils.getApiFace();

		// 传入可选参数调用接口
		HashMap<String, String> options = new HashMap<String, String>();
		//最多处理人脸的数目
		options.put("max_face_num", "1");
		//人脸的类型 LIVE表示生活照：通常为手机、相机拍摄的人像图片、或从网络获取的人像图片等
		options.put("face_type", "LIVE");
		//活体检测控制
		options.put("liveness_control", "LOW");

		String imageType = "BASE64";

		// 人脸检测
		JSONObject res = apiFace.detect(image, imageType, options);
		logger.debug("人脸检测结果:{}", res);
//		System.out.println(res.toString(2));
//		DetectResult result = JSON.parseObject(res.toString(), DetectResult.class);
		int errorCode = res.getInt("error_code");
		logger.debug("errorCode:{}", errorCode);
		if(errorCode != 0) {
			return R.error("人脸识别失败，请重试！");
		}
		JSONObject result = res.getJSONObject("result");
		JSONArray faceList = result.getJSONArray("face_list");
		JSONObject oneFace = faceList.getJSONObject(0);
		//人脸置信度，范围【0~1】，代表这是一张人脸的概率，0最小、1最大
		int faceProbability = oneFace.getInt("face_probability");
		logger.debug("faceProbability:{}", faceProbability);
		if(faceProbability < 0.9) {
			return R.error("人脸识别失败，请重试！");
		}
		JSONObject liveness = oneFace.getJSONObject("liveness");
		int livemapscore = liveness.getInt("livemapscore");
		logger.debug("livemapscore:{}", livemapscore);
		if(livemapscore < 0.9) {
			return R.error("人脸识别失败，请重试！");
		}

		return R.ok();
	}
}
