package com.qmth.sop.business.sync;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qmth.sop.business.service.SysConfigService;
import com.qmth.sop.common.been.FaceMatchParam;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.util.FileUtil;
import com.qmth.sop.common.util.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 百度人脸识别工具类
 * @Author: CaoZixuan
 * @Date: 2023-09-14
 */
@Component
public class FaceApiUtils {
    @Resource
    private SysConfigService sysConfigService;

    @Value("${face.verify.baiduLocalAppId}")
    String faceVerifyBaiduLocalAppId;

    @Value("${face.verify.baiduLocalUrlPrefix}")
    String faceVerifyBaiduLocalUrlPrefix;

    /**
     * 百度人脸识别-人脸对比
     *
     * @param f1 人脸图片文件1
     * @param f2 人脸图片文件2
     * @return 识别度
     * @throws IOException 异常
     */
    public BigDecimal faceMatch(File f1, File f2) throws IOException {
//        String appId = sysConfigService.findByConfigKey(SystemConstant.FACE_VERIFY_BAIDU_LOCAL_APP_ID).getConfigValue();
//        String uri = sysConfigService.findByConfigKey(SystemConstant.FACE_VERIFY_BAIDU_LOCAL_URL_PREFIX).getConfigValue();
        String url = sysConfigService.findByConfigKey(SystemConstant.BAIDU_FACE_COMPARE_URL).getConfigValue();

        String postUrl = faceVerifyBaiduLocalUrlPrefix + url + "?appId=" + faceVerifyBaiduLocalAppId;
        List<FaceMatchParam> faceMatchParamList = new ArrayList<>();
        FaceMatchParam p1 = new FaceMatchParam();
        p1.setImage(FileUtil.fileToBase64(f1));
        p1.setImage_type("BASE64");
        faceMatchParamList.add(p1);

        FaceMatchParam p2 = new FaceMatchParam();
        p2.setImage(FileUtil.fileToBase64(f2));
        p2.setImage_type("BASE64");
        faceMatchParamList.add(p2);
        String json = JSONArray.toJSONString(faceMatchParamList);

        String result = HttpUtil.postJson(postUrl, json, null, null, false);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String errorCode = jsonObject.getString("error_code");
        String errorMsg = jsonObject.getString("error_msg");

        if (!errorCode.equals("0")) {
            throw ExceptionResultEnum.ERROR.exception(String.format("人脸识别对比请求失败，错误码: %s [%s]", errorCode, errorMsg));
        }
        JSONObject detail = jsonObject.getJSONObject("result");
        return detail.getBigDecimal("score").setScale(2, RoundingMode.HALF_UP);
    }
}
