package com.xjrsoft.module.hikvision.util;

import cn.hutool.core.util.IdUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xjrsoft.common.utils.ImageUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
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) {
        JsonParser parser = new JsonParser();

        String apiUrl = "/api/resource/v1/person/condition/personInfo";
        JsonObject paramsJson = new JsonObject();
        paramsJson.addProperty("paramName", "personId");
        JsonArray array = new JsonArray();
        array.add(personId);
        paramsJson.add("paramValue", array);
        String personInfoRes = apiUtil.doPost(apiUrl, paramsJson.toString(), null);
        JsonObject personInfoData = parser.parse(personInfoRes).getAsJsonObject();
        String faceId = null;
        if("0".equals(personInfoData.get("code").getAsString()) && "success".equals(personInfoData.get("msg").getAsString())){
            JsonObject dataJson = personInfoData.get("data").getAsJsonObject();
            if(dataJson.get("total").getAsInt() > 0){
                JsonArray personPhoto = dataJson.get("list").getAsJsonArray().get(0)
                        .getAsJsonObject().get("personPhoto").getAsJsonArray();
                if(personPhoto.size() > 0){
                    faceId = personPhoto.get(0).getAsJsonObject().get("personPhotoIndexCode").getAsString();
                }

            }
        }
        String response = null;
        String base64String = ImageToBase64(fileUrl);
        JsonObject paramJson = new JsonObject();
        if(faceId == null){
            paramJson.addProperty("personId", personId);
            paramJson.addProperty("faceData", base64String);

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

            String apiPath = "/api/resource/v1/face/single/add";
            response = apiUtil.doPost(apiPath, String.valueOf(paramJson), querys);
        }else{
            String apiPath = "/api/resource/v1/face/single/update";
            paramJson.addProperty("faceId", faceId);
            paramJson.addProperty("faceData", base64String);
            response = apiUtil.doPost(apiPath, paramJson.toString(), null);
        }

        return response;
    }

    public static String ImportStudentFace(String personId, String fileUrl) {

        JsonParser parser = new JsonParser();

        String apiUrl = "/api/resource/v1/person/condition/personInfo";
        JsonObject paramsJson = new JsonObject();
        paramsJson.addProperty("paramName", "personId");
        JsonArray array = new JsonArray();
        array.add(personId);
        paramsJson.add("paramValue", array);
        String personInfoRes = apiUtil.doPost(apiUrl, paramsJson.toString(), null);
        JsonObject personInfoData = parser.parse(personInfoRes).getAsJsonObject();
        String faceId = null;
        if("0".equals(personInfoData.get("code").getAsString()) && "success".equals(personInfoData.get("msg").getAsString())){
            JsonObject dataJson = personInfoData.get("data").getAsJsonObject();
            if(dataJson.get("total").getAsInt() > 0){
                JsonArray personPhoto = dataJson.get("list").getAsJsonArray().get(0)
                        .getAsJsonObject().get("personPhoto").getAsJsonArray();
                if(personPhoto.size() > 0){
                    faceId = personPhoto.get(0).getAsJsonObject().get("personPhotoIndexCode").getAsString();
                }

            }
        }
        String response = null;
        String base64String = ImageToBase64(fileUrl);
        JsonObject paramJson = new JsonObject();
        if(faceId == null){
            paramJson.addProperty("personId", personId);
            paramJson.addProperty("faceData", base64String);

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

            String apiPath = "/api/resource/v1/face/single/add";
            response = apiUtil.doPost(apiPath, String.valueOf(paramJson), querys);
        }else{
            String apiPath = "/api/resource/v1/face/single/update";
            paramJson.addProperty("faceId", faceId);
            paramJson.addProperty("faceData", base64String);
            response = apiUtil.doPost(apiPath, paramJson.toString(), null);
        }

        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();
            //压缩到200k
            imageBytes = ImageUtil.compressUnderSize(imageBytes, 204800);

            //压缩之后，存入本地
            String[] split = imageUrl.split("\\.");
            String suffix = split[split.length - 1];
            String filePath = "/" + IdUtil.getSnowflakeNextId() + "." + suffix;
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(imageBytes);
            fos.close();
            //再读取出来
            File file = new File(filePath);
            imageBytes = Files.readAllBytes(file.toPath());

            //删除文件
            if(file.exists()){
                file.delete();
            }

            base64String = Base64.getEncoder().encodeToString(imageBytes);
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int commaIndex = base64String.indexOf(',') + 1;
        return base64String.substring(commaIndex);
    }
}
