package com.xjrsoft.module.hikvision.util;

import com.google.gson.JsonObject;
import com.xjrsoft.module.personnel.entity.TeacherFaceProcess;
import com.xjrsoft.module.teacher.mapper.FaceImportMapper;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;



public class FaceImportUtil {

    private static ApiUtil apiUtil = new ApiUtil();

    public static String ImportTeacherFace(String personId, String fileUrl) {
        JsonObject paramJson = new JsonObject();
        paramJson.addProperty("personId", personId);
        paramJson.addProperty("faceData", ImageToBase64(fileUrl));

        Map<String, String> querys = new HashMap<>();
        querys.put("tagId", "frs");

        String apiPath = "/api/resource/v1/face/single/add";
        String response = apiUtil.doPost(apiPath, String.valueOf(paramJson), querys);

        return response;
    }

    public static String ImportStudentFace(String personId, String fileUrl) {
        JsonObject paramJson = new JsonObject();
        paramJson.addProperty("personId", personId);
        paramJson.addProperty("faceData", ImageToBase64(fileUrl));

        Map<String, String> querys = new HashMap<>();
        querys.put("tagId", "frs");

        String apiPath = "/api/resource/v1/face/single/add";
        String response = apiUtil.doPost(apiPath, String.valueOf(paramJson), querys);

        return response;
    }

    public static String ImageToBase64(String imageUrl) {
        String base64String = "";
        try {
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = outputStream.toByteArray();
            base64String = Base64.getEncoder().encodeToString(imageBytes);
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int commaIndex = base64String.indexOf(',') + 1;
        return base64String.substring(commaIndex);
    }
}
