package tech.glinfo.enbao.modules.service.impl;


import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.jhlabs.image.ImageUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.glinfo.enbao.common.utils.BaiDuApiUtils;
import tech.glinfo.enbao.common.utils.HttpUtil;
import tech.glinfo.enbao.common.utils.RedisUtils;
import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.modules.service.BaiduApiService;

import java.util.ArrayList;
import java.util.HashMap;

@Service("baiduApiService")
public class BaiduApiServiceImpl implements BaiduApiService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisUtils redisUtils;

    /**
     * score 推荐阈值0.8，超过即判断为同一人
     * @param image 人脸图片base64字符串
     * @param idCardNumber 身份证号码
     * @param name 姓名
     * @return
     */
    @Override
    public JSONObject personVerify(String image, String idCardNumber, String name) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");

        String imageType = "BASE64";

        AipFace client = BaiDuApiUtils.getApiFace();
        // 身份验证
        JSONObject res = client.personVerify(image, imageType, idCardNumber, name, options);
        logger.debug("res : {}", res.toString(2));

        return res;
    }

    /**
     * 两张人脸比对
     * @param image1
     * @param image1
     * @return
     */
    @Override
    public JSONObject match(String image1, String image2) {
        AipFace apiFace = BaiDuApiUtils.getApiFace();

        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1, "BASE64");
        MatchRequest req2 = new MatchRequest(image2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);

        return apiFace.match(requests);
    }

    @Override
    public byte[] synthesis(String text) {
        return new byte[0];
    }


    @Override
    public JSONObject groupAdd(String groupId) {
        AipFace apiFace = BaiDuApiUtils.getApiFace();

        HashMap<String, String> options = new HashMap<String, String>();

        //先查询是否已经存在该用户组了
        JSONObject groupList = apiFace.getGroupList(options);
        if(groupList != null) {
            logger.debug(groupList.toString(2));
            if(groupList.has("group_id_list")) {
                JSONArray idList = groupList.getJSONArray("group_id_list");
                for(int i=0; i<idList.length(); i++) {
                    String o = idList.getString(i);
                    if(groupId.equals(o)) {
                        JSONObject object = new JSONObject();
                        object.put("error_code", 0);
                        return object;
                    }
                }
            }
        }

        // 创建用户组
        JSONObject result = apiFace.groupAdd(groupId, options);
        if(result != null ) {
            logger.debug(result.toString(2));
        }

        return result;

    }

    @Override
    public JSONObject addUser(String image, String userId, String groupId, String userInfo) {

        AipFace apiFace = BaiDuApiUtils.getApiFace();

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", userInfo);
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "REPLACE");

//        String image = "取决于image_type参数，传入BASE64字符串或URL字符串或FACE_TOKEN字符串";
        String imageType = "BASE64";
//        String groupId = "group1";
//        String userId = "user1";

        // 人脸注册
        JSONObject result = apiFace.addUser(image, imageType, groupId, userId, options);

        if(result != null ) {
            logger.debug(result.toString(2));
        }

        return result;

    }

    @Override
    public JSONObject updateUser(String image, String userId, String groupId, String userInfo) {

        AipFace apiFace = BaiDuApiUtils.getApiFace();

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", userInfo);
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "REPLACE");

//        String image = "取决于image_type参数，传入BASE64字符串或URL字符串或FACE_TOKEN字符串";
        String imageType = "BASE64";
//        String groupId = "group1";
//        String userId = "user1";

        // 人脸更新
        JSONObject result = apiFace.updateUser(image, imageType, groupId, userId, options);
        if(result != null ) {
            logger.debug(result.toString(2));
        }

        return result;
    }

    @Override
    public JSONObject delUser(String userId, String groupId, String faceToken) {

        AipFace apiFace = BaiDuApiUtils.getApiFace();

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();

//        String userId = "user1";
//        String groupId = "group1";
//        String faceToken = "face_token_23123";

        // 人脸删除
        JSONObject result = apiFace.faceDelete(userId, groupId, faceToken, options);
        if(result != null ) {
            logger.debug(result.toString(2));
        }

        return result;
    }

    @Override
    public JSONObject search(String image, String groupId) {

        AipFace apiFace = BaiDuApiUtils.getApiFace();

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
//        options.put("max_face_num", "3");
        options.put("match_threshold", "80");
        options.put("quality_control", "NONE");
        options.put("liveness_control", "NONE");
//        options.put("user_id", "233451");
//        options.put("max_user_num", "3");

//        String image = ImageUtils.img2Base641("E:/attend/b.jpg");
//        String image = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0//wAARCACgAHgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEI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zf3jXExymFhJ3U5rsrW7R4kB+UkcelDTtoS2Xc0maZuozWYD80ZphNJmkIkzXP+K9zRW0aAsWc4AGST/k1uSPsHIJprTQkB8gMOhPWtYJ7k3RycGiMiCW+JTP3YlPzH6+n8/pWpp9lFGxlEUabPugLk5+p5p1xL5k5PYVahIFsSOhORW9rIm9zlb9v+Jjcf739BVfrU96c6hN7nNQVjLc2jsIRSYp1FTcqwgWnqMU2lzRcBs7fJiugsZDNaBc/MBx9a5uVsmtfS5Ssm3tWkDOZqWl7KW8t3OV5A/pWrHMsi5JwfSueuT5N7uHRvmq5HLudck46jFVKCkRexpy3UcSgncc9MCof7Qj/AOeb0biynYuV9xTcN6L+tQqcQ5mf/9k=";
        String imageType = "BASE64";
//        String groupIdList = "facelock1";

        // 人脸搜索
        JSONObject result = apiFace.search(image, imageType, groupId, options);
        if(result != null ) {
            logger.debug(result.toString(2));
        }

        return result;
    }

    @Override
    public String chat(String text, String chatId) {
        // 请求URL
        String talkUrl = "https://aip.baidubce.com/rpc/2.0/unit/service/v3/chat";
        try {
            // 请求参数
            String logId = StringUtils.getUUID();
            logger.info("请问LogId:{}", logId);
            String params = "{\"version\":\"3.0\",\"service_id\":\""+chatId+"\",\"session_id\":\"\",\"log_id\":\""+ logId +"\",\"request\":{\"terminal_id\":\"88888\",\"query\":\""+text+"\"}}";

            String accessToken = redisUtils.get("baidu_access_token");
            if (accessToken == null) {
                JSONObject jsonObject = BaiDuApiUtils.getAuth();
                if (jsonObject == null) {
                    return null;
                }
                accessToken = jsonObject.getString("access_token");
                int expiresIn = jsonObject.getInt("expires_in");
                redisUtils.set("baidu_access_token", accessToken, expiresIn - 10);
            }

            String result = HttpUtil.post(talkUrl, accessToken, "application/json", params);
            if(result != null) {
                logger.info("{}>>返回结果：{}",text, result);
                JSONObject object = new JSONObject(result);
                if(object.has("result")) {
                    JSONObject result1 = object.getJSONObject("result");
                    if(result1.has("responses")) {
                        JSONArray responses = result1.getJSONArray("responses");
                        JSONObject jsonObject = responses.getJSONObject(0);//推荐第一个回答
                        if(jsonObject.has("actions")) {
                            JSONArray actions = jsonObject.getJSONArray("actions");
                            JSONObject first = actions.getJSONObject(0);
                            String reply = first.getString("say");
                            if("satisfy".equals(first.getString("type"))) {//type satisfy(满足)
                                for(int i=1; i<responses.length(); i++) {
                                    JSONObject jsonObject1 = responses.getJSONObject(i);
                                    if(jsonObject1.has("actions")) {
                                        JSONArray actions1 = jsonObject1.getJSONArray("actions");
                                        JSONObject first1 = actions1.getJSONObject(0);
                                        if ("satisfy".equals(first1.getString("type"))) {
                                            reply += "，" + first1.getString("say");
                                            break;
                                        }
                                    }
                                }
                            }
                            return reply;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
