package com.hh.lib_face.utils;

import static com.hh.lib_base.Constants.Value.CAMERA_BRAND;

import android.os.Bundle;
import android.util.DisplayMetrics;

import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.ipc.IpcChannel;
import com.alipay.iot.bpaas.api.ipc.IpcListener;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.Constants;
import com.hh.lib_base.bean.device.DeviceConfigResultBean;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.StringUtils;
import com.hh.lib_base.utils.device.DeviceUtils;
import com.hh.lib_face.BPaaSApiInvoker;
import com.hh.lib_base.ConfigData;
import com.hh.lib_face.bean.StartReadyBpaasServiceBean;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Description: $
 *
 * @author xwh
 * time 2024/8/26
 **/
public class BPaaSApiCommonUtils {

    private volatile static BPaaSApiCommonUtils commonUtils;
    public static BPaaSApiCommonUtils getInstance() {
        if (commonUtils == null) {
            synchronized (BPaaSApiCommonUtils.class) {
                if (commonUtils == null) {
                    commonUtils = new BPaaSApiCommonUtils();

                }
            }
        }

        return commonUtils;
    }




    /**
     *
     * @author xwh
     * Time 2024/8/26
     * Description: 启动刷脸服务配置参数
     *
    **/
    public Bundle startBpaasServiceparameter(final StartReadyBpaasServiceBean bpaasServiceBean){
        if (bpaasServiceBean == null) {
            return null;
        }
        Bundle params = new Bundle();
        params.putString("trade", bpaasServiceBean.getTrade());
        params.putBoolean("need1v1", bpaasServiceBean.isNeed1v1());
        params.putString("checkWay", bpaasServiceBean.getCheckWay());
        //这里 xxxxx 需替换成 isv 自己的需要授权的 merchantAppId
        params.putString("merchantAppId", bpaasServiceBean.getMerchantAppId());


        try {
            JSONObject extInfo = new JSONObject();
            // 聚合授权-------begin
            String serviceId = bpaasServiceBean.getServiceId();
            AppLogUtils.e("serviceId = " + serviceId);
            if (StringUtils.isNotNull(serviceId)) {
                extInfo.put("serviceId", serviceId);
            }

            String query = bpaasServiceBean.getQuery();
            AppLogUtils.e("query = " + query);
            if (StringUtils.isNotNull(query)) {
                extInfo.put("query", query);
            }

            // 信息授权组件scope
            String scope = bpaasServiceBean.getScope();
            AppLogUtils.e("scope = " + scope);
            if (StringUtils.isNotNull(scope)) {
                extInfo.put("scope", scope);
            }
            // 聚合授权-------end
            DisplayMetrics dm = BaseApplication.getContext().getResources().getDisplayMetrics();
            int displayWidth = dm.widthPixels;
            int displayHeight = dm.heightPixels;
            AppLogUtils.e("displayHeight:" + displayHeight);
            AppLogUtils.e("displayWidth:" + displayWidth);

            String deviceModel = DeviceUtils.getDeviceModel();
            if (Constants.DeviceModel.D2.equals(deviceModel)) {
                // D2访客机刷脸屏幕设置-----begin
                // 是否悬浮，默认false
                extInfo.put("isFloat", true);
                // 显示X偏移，默认0    （宽度-刷脸界面宽度）/2   越大越往右边偏移
                extInfo.put("displayX", (displayWidth - (displayHeight * 0.625)) / 2 + 41);
//            extInfo.put("displayX",0);
                // 显示Y偏移，默认0
                extInfo.put("displayY", -300);
//            extInfo.put("displayY",0);
                // 显示宽度，默认屏幕宽度
//            extInfo.put("displayWidth",675);
                extInfo.put("displayWidth", (displayHeight * 0.625));// 如果+1.5的话，就会是悬浮状态（其余黑色）
                // 显示宽度，默认屏幕⾼度
//            extInfo.put("displayHeight",1080);
                extInfo.put("displayHeight", displayHeight);
                // 主副屏，0主 1副
                extInfo.put("displayMode", 0);
                // D2访客机刷脸屏幕设置-----end
            }
            params.putString("extInfo", extInfo.toString());

        } catch (JSONException e) {
            AppLogUtils.e("extInfo -- e = " + e.toString());
            e.printStackTrace();
        }

        String cameraBrand = ConfigData.getDeviceConfigResultBean().getCameraBrand();
        AppLogUtils.e("cameraBrand=" + cameraBrand);
        if (!CAMERA_BRAND.equals(cameraBrand)) {
            try {
                params.putString("zolozConfig", BPaaSApiCommonUtils.getInstance().getHardWareConfig());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        params.putLong(BPaaSApi.KEY_BPAAS_IPC_TIME_OUT, -1L);
        return params;
    }


    /**
     *
     * @author xwh
     * Time 2024/8/26
     * Description: 刷脸参数配置
     *
     **/
    public StartReadyBpaasServiceBean getStartReadyBpaasServiceBean() {
        DeviceConfigResultBean deviceConfigResultBean = ConfigData.getDeviceConfigResultBean();
        if (deviceConfigResultBean == null) {
            deviceConfigResultBean = new DeviceConfigResultBean();
        }
        StartReadyBpaasServiceBean bpaasServiceBean = new StartReadyBpaasServiceBean();
        bpaasServiceBean.setTrade(deviceConfigResultBean.getTrade());
        bpaasServiceBean.setNeed1v1(ConfigData.isNeed1V1);
        bpaasServiceBean.setCheckWay(ConfigData.checkWay);
        bpaasServiceBean.setMerchantAppId(deviceConfigResultBean.getServiceAppId());
//        bpaasServiceBean.setMerchantAppId("2021004108612349");
        bpaasServiceBean.setmSessionId(ConfigData.mSessionId);
        bpaasServiceBean.setServiceId(ConfigData.serviceId);
        bpaasServiceBean.setQuery(ConfigData.query);
        bpaasServiceBean.setScope(ConfigData.scope);
        AppLogUtils.e("ConfigData.scopes = " + ConfigData.scope);


        return bpaasServiceBean;
    }

    /**
     *
     * @author xwh
     * Time 2024/8/26
     * Description: zolozConfig配置
     *
     **/
    public String getHardWareConfig() throws JSONException {

        org.json.JSONObject zolozConfig = new JSONObject();
        String deviceModel = DeviceUtils.getDeviceModel();
        DeviceConfigResultBean deviceConfigBean = ConfigData.getDeviceConfigResultBean();
        if(Constants.DeviceModel.P55.equals(deviceModel)){
            //相机id
            zolozConfig.put("cameraID", 1);
            //ir摄像头id
            zolozConfig.put("supCameraID", 0);
            if (deviceConfigBean == null) {
                //算法orientation(int)，取值：0，90，180，270
                zolozConfig.put("algorithmAngle", 270);
                //预览orientation(int)，取值：0，90，180，270
                zolozConfig.put("displayAngle", 90);
                //预览是否需要镜像(boolean)
                zolozConfig.put("isDisplayMirror", true);
                //帧数据是否需要镜像(boolean)
                zolozConfig.put("isMirror", false);

                //ir预览orientation(int)，取值：0，90，180，270
                zolozConfig.put("supDisplayAngle", 90);
            }else {
                zolozConfig.put("algorithmAngle", deviceConfigBean.getAlgorithmAngle());  // 送算法的图像角度
                zolozConfig.put("supAlgorithmAngle", deviceConfigBean.getSupAlgorithmAngle());   // 用于ir摄像头算法角度
                zolozConfig.put("displayAngle", deviceConfigBean.getDisplayAngle());    // 预览角度
                zolozConfig.put("isDisplayMirror", deviceConfigBean.isDisplayMirror());   // 预览的图像是否需要镜像 后面的摄像头背景  false头像移动向左，摄像头里也是向左
                zolozConfig.put("isMirror", deviceConfigBean.isMirror());  // 送算法图像是否镜像  小圆圈里的
            }
        }else {
            zolozConfig.put("cameraID", 0); // 相机camera id 一般为0为colorCamera, 1为IrCamera
            zolozConfig.put("supCameraID", 1);  // 用于ir相机camera id，不设置的话自动用colorCameraId加1
            zolozConfig.put("toygerPowerMode", 0);
            zolozConfig.put("minIod", 0.02);
            zolozConfig.put("supIsMirror", false);  // 用于ir摄像头帧数据是否镜像
            zolozConfig.put("supIsDisplayMirror", false);    // 用于ir摄像头预览是否镜像
            zolozConfig.put("supDisplayAngle", 0);  // 用于ir摄像头预览角度，不设置的话保持和color的一致

            if (deviceConfigBean == null) {
                String logLine = (new Throwable().getStackTrace())[0].toString();
                UploadLogUtils.sendLogs("zolozConfig",
                        "摄像头配置错误---zolozConfig---getHardWareConfig",
                        logLine, "deviceConfigBean == null，开始用默认值");
                // 设置k8默认值
                zolozConfig.put("algorithmAngle", 90);  // 送算法的图像角度
                zolozConfig.put("supAlgorithmAngle", 90);   // 用于ir摄像头算法角度
                zolozConfig.put("displayAngle", 0);    // 预览角度
                zolozConfig.put("isDisplayMirror", true);   // 预览的图像是否需要镜像  后面的摄像头背景 false头像移动向左，摄像头里也是向左
                zolozConfig.put("isMirror", false);  // 送算法图像是否镜像   小圆圈里的

            } else {
                zolozConfig.put("algorithmAngle", deviceConfigBean.getAlgorithmAngle());  // 送算法的图像角度
                zolozConfig.put("supAlgorithmAngle", deviceConfigBean.getSupAlgorithmAngle());   // 用于ir摄像头算法角度
                zolozConfig.put("displayAngle", deviceConfigBean.getDisplayAngle());    // 预览角度
                zolozConfig.put("isDisplayMirror", deviceConfigBean.isDisplayMirror());   // 预览的图像是否需要镜像 后面的摄像头背景  false头像移动向左，摄像头里也是向左
                zolozConfig.put("isMirror", deviceConfigBean.isMirror());  // 送算法图像是否镜像  小圆圈里的
            }
        }
        String logLine = (new Throwable().getStackTrace())[0].toString();
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append("zolozConfig = ").append(zolozConfig.toString());
        UploadLogUtils.sendLogs("zolozConfig",
                "摄像头配置---zolozConfig---getHardWareConfig",
                logLine, logContentSb.toString());
        return zolozConfig.toString();
    }

    public String getD2Config() {
        DisplayMetrics dm = BaseApplication.getContext().getResources().getDisplayMetrics();
        int displayWidth = dm.widthPixels;
        int displayHeight = dm.heightPixels;
        AppLogUtils.e("displayHeight:" + displayHeight);
        AppLogUtils.e("displayWidth:" + displayWidth);

        String deviceModel = DeviceUtils.getDeviceModel();
        try {
            JSONObject extInfo = new JSONObject();
            if (Constants.DeviceModel.D2.equals(deviceModel)) {

                AppLogUtils.e("displayHeight:" + displayHeight);
                AppLogUtils.e("displayWidth:" + displayHeight * 0.625);
                AppLogUtils.e("displayX:" + (displayWidth - (displayHeight * 0.625)) / 2);

                // D2访客机刷脸屏幕设置-----begin
                // 是否悬浮，默认false
                extInfo.put("isFloat", true);
                // 显示X偏移，默认0    （宽度-刷脸界面宽度）/2   越大越往右边偏移
                extInfo.put("displayX", (displayWidth - (displayHeight * 0.625)) / 2 + 41);
//            extInfo.put("displayX",0);
                // 显示Y偏移，默认0
                extInfo.put("displayY", -300);
//            extInfo.put("displayY",0);
                // 显示宽度，默认屏幕宽度
//            extInfo.put("displayWidth",675);
                extInfo.put("displayWidth", (displayHeight * 0.625));// 如果+1.5的话，就会是悬浮状态（其余黑色）
                // 显示宽度，默认屏幕⾼度
//            extInfo.put("displayHeight",1080);
                extInfo.put("displayHeight", displayHeight);
                // 主副屏，0主 1副
                extInfo.put("displayMode", 0);
                // D2访客机刷脸屏幕设置-----end
            }


            AppLogUtils.e("extInfo = " + extInfo.toString());
            return extInfo.toString();

        } catch (JSONException e) {
            AppLogUtils.e("extInfo -- e = " + e.toString());
            e.printStackTrace();
        }
        return "";
    }

    public final IpcListener mIpcListener = new IpcListener() {
        @Override
        public void onConnected(IpcChannel ipcChannel) {
            //启动核身服务
//            startBpaasService(ConfigD.trade, true, Config.GroupID, 0, Config.mSessionId,
//                    Config.machineAppId, "scanFace", false);
//            startBpaasService(ConfigData.getDeviceConfigResultBean().getTrade(), true, ConfigData.getDeviceConfigResultBean().getGroupId(), 0, ConfigData.mSessionId,
//                    ConfigData.getDeviceConfigResultBean().getAbcpAppId(), "scanFace", false);


            // 获取启动Bpaas刷脸的参数
            StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();
            //启动核身服务
            BPaaSApiInvoker.getInstance().startZfbBpaasService(bpaasServiceBean);


        }

        @Override
        public void onDisconnected(IpcChannel ipcChannel) {
        }

        @Override
        public void onConnectionFailed(IpcChannel ipcChannel) {
        }
    };

    public void onRelease(){
        commonUtils = null;
    }
}
