package com.yanzhu.manage.utils;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.yanzhu.common.core.utils.StringUtils;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class UniUtils {
    public static final String UNIBASE="http://wo-api.uni-ubi.com/";
    public static final String ADMITCREATE=UNIBASE+"v2/admit/create";
    public static final String ADMITUPDATE=UNIBASE+"v2/admit/update";
    public static final String ADMITDELETE=UNIBASE+"v2/admit/delete";
    public static final String ADMITDETAIL=UNIBASE+"v2/admit/detail";
    public static final String FACEREGISTER=UNIBASE+"v2/face/register";
    public static final String FACEDELETE=UNIBASE+"v2/face/delete";
    public static final String FACEDETAIL=UNIBASE+"v2/face/detail";

    public static final String DEVICECREATE=UNIBASE+"v2/device/create";
    public static final String DEVICEUPATE=UNIBASE+"v2/device/update";
    public static final String DEVICEDELETE=UNIBASE+"v2/device/delete";
    public static final String DEVICEDETAIL=UNIBASE+"v2/device/detail";

    public static final String AUTHDEVICE=UNIBASE+"v2/auth/device";
    public static final String AUTHDEVICEUPDATE=UNIBASE+"v2/auth/device/update";
    public static final String AUTHDEVICEREVOKE=UNIBASE+"v2/auth/device/revoke";
    public static String getAuthUrl(String projectGuid){
        return  UNIBASE+ "/v1/"+projectGuid+"/auth";
    }

    public static Headers setHeaderParams(Map<String, String> headerParams) {
        Headers headers = null;
        Headers.Builder headersbuilder = new Headers.Builder();
        if (headerParams != null && headerParams.size() > 0) {
            for (String key : headerParams.keySet()) {
                if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(headerParams.get(key))) {
                    //如果参数不是null并且不是""，就拼接起来
                    headersbuilder.add(key, headerParams.get(key));
                }
            }
        }

        headers = headersbuilder.build();
        return headers;
    }

    public static String getResult(Request request) {
        OkHttpClient client = new OkHttpClient();
        Response response;
        try {
            response = client.newCall(request).execute();
            if (response.body() != null) {
                return response.body().string();
            } else {
                return "";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static RequestBody toJsonBody(JSONObject data) {
        return RequestBody.create(MediaType.parse("application/json"),data.toJSONString());
    }

    public static String md5(String data){
        try {
            return MD5Utils.md5Hex(data.getBytes());
        }catch (Exception ex){
            return  "";
        }
    }
}
