package com.hh.lib_face.storageface;




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

import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.google.gson.JsonObject;

import com.hh.lib_ampe.bean.BaseAmpeAppletResultBean;
import com.hh.lib_ampe.bean.BaseAmpeRequestBean;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.GsonUtils;
import com.hh.lib_base.ConfigData;
import com.hh.lib_face.storageface.bean.BPaaSOpenRocketBean;

/**
 * Description:支付宝刷脸入库服务
 * @author xwh
 * time 2024/7/18
 **/
public class ZfbBPaaSOpenRocketUtils {
    
    private static final String TAG = ZfbBPaaSOpenRocketUtils.class.getName();

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

                }
            }
        }

        return openRocketUtils;
    }
    
    
    /**
     * 
     * Description: 启动支付宝 "BPaaSOpenRocket服务
     * @author xwh
     * Time 2024/7/18
     *
    **/
    public  String startZfbBpaasOpenRocketService(BaseAmpeRequestBean<BPaaSOpenRocketBean> ampeAppletRequestBean) {
        if (ampeAppletRequestBean == null) {
            AppLogUtils.e("startBPaaSOpenRocketBean:  " + ampeAppletRequestBean);
            return "";
        }
        Bundle bundle = new Bundle();
        // 启动组件的appId
        bundle.putString("schema", "engine://platformapi/startapp?appId=2021003197687001&type=cube");
        JSONObject launchParams = new JSONObject();
        launchParams.put("orgOutId", ampeAppletRequestBean.getParams().getOrgOutId());
        launchParams.put("componentOutId", ampeAppletRequestBean.getParams().getComponentOutId());
        launchParams.put("isvPid", ampeAppletRequestBean.getParams().getIsvPid()); //企业的支付宝的PID
        launchParams.put("appId", ampeAppletRequestBean.getParams().getServiceAppId());
        if(!TextUtils.isEmpty(ampeAppletRequestBean.getParams().getD2Config())){
            launchParams.put("extInfo", ampeAppletRequestBean.getParams().getD2Config());
        }
        String cameraBrand = ConfigData.getDeviceConfigResultBean().getCameraBrand();
        if (CAMERA_BRAND.equals(cameraBrand)) {
            AppLogUtils.e("是马里奥的，不配置zolozConfig");
        } else {
            AppLogUtils.e("非马里奥的，开始配置zolozConfig");
            //各设备 zolozConfig 参数，参考 zolozConfig
            try {
                launchParams.put("zolozConfig",ampeAppletRequestBean.getParams().getZolozConfig());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (!TextUtils.isEmpty(ampeAppletRequestBean.getParams().getUniqueId().trim())) {
          //  launchParams.put("ext", "xxxx"); // 刷脸授权开通时非必传，刷身份证和手工录入开通时不能传该参数
            launchParams.put("uniqueId", ampeAppletRequestBean.getParams().getUniqueId()); // 刷脸授权开通时不能传该参数，刷身份证开通和手工录入开通时必传

            JSONObject identityInfoJson = new JSONObject();
            identityInfoJson.put("name", ampeAppletRequestBean.getParams().getName());
            identityInfoJson.put("certNo", ampeAppletRequestBean.getParams().getCertNo());
            if (!TextUtils.isEmpty(ampeAppletRequestBean.getParams().getPhone())) {
                identityInfoJson.put("phone", ampeAppletRequestBean.getParams().getPhone());  //选填
            }
            JSONObject businessParamsJson = new JSONObject();
            businessParamsJson.put("identityInfo", identityInfoJson );
            launchParams.put("businessParams", businessParamsJson );
        }
        bundle.putString("launchParams", launchParams.toJSONString());
        bundle.putString("controlParams", "{\"isShowTitleBar\":false, \"showLoading\": false}");
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs("老年食堂--入参",ACTION_STORAGE_FACE_INFO,logLine,(bundle==null?"":bundle.toString()));

        String sessionId = BPaaSApi.getInstance().startBPaaSService(ampeAppletRequestBean.getParams().getMachineAppId(), "BPaaSOpenRocket",
                bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse bPaaSResponse) {
                        String logLine = (new Throwable().getStackTrace())[0].toString();
                        UploadLogUtils.sendLogs("老年食堂--onResponse",ACTION_STORAGE_FACE_INFO,
                                logLine,(bPaaSResponse==null?"":bPaaSResponse.toString()));
                        if (bPaaSResponse != null && bPaaSResponse.getCode() == BPaaSResponse.RESULT_CODE_SUCCESS) {
                            // bpaas服务调用成功，不需要处理
                        } else {
                            // bpaas服务调用失败，可以重试
                        }
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle bundle) {
                        // 接收到组件消息，处理结果
                        String logLine = (new Throwable().getStackTrace())[0].toString();
                        UploadLogUtils.sendLogs("老年食堂--onEvent",ACTION_STORAGE_FACE_INFO,logLine,
                                "eventId=" + eventId + ",data=" + data + ",extra=" + (bundle==null?"":bundle.toString()));
                        try {
                             boolean isSuccess=false;
                            JSONObject dataJson = JSON.parseObject(data);
                            if (eventId.equals("BPaaSOpenRocket") && dataJson.getString("eventType").equals("rocketResult")) {
                                JSONObject eventData = dataJson.getJSONObject("eventData");
                                String subCode = eventData.getString("subCode");
                                // 开通成功
                                if (subCode.equals("SUCCESS")) {
                                    isSuccess=true;
                                }
                                // 刷脸授权开通时若授权失败，则在接收组件消息中获取uniqueId，后续传入相应组件编码和uniqueId切换至刷身份证或者手工录入开通
                                if (subCode.equals("90001")) {
                                    AppLogUtils.d(TAG, eventData.getString("uniqueId"));
                                    isSuccess=false;
                                }
                                // 其他都是开通失败

                            }
                            //todo 如果失败，就使用errMsg字段文字
                            sendBridgeCallback(ampeAppletRequestBean,dataJson,isSuccess,"失败");

                        } catch (JSONException e) {
                            AppLogUtils.e(e.toString());
                        }
                    }
                });
        return sessionId;
    }


    /**
     *
     * @author xwh
     * Time 2024/8/27
     * Description: 发送结果给小程序
     *
    **/
    public void sendBridgeCallback(BaseAmpeRequestBean<BPaaSOpenRocketBean> ampeAppletRequestBean,
                                   JSONObject dataJson,boolean isSuccess,String errMsg) {
        if(ampeAppletRequestBean==null){
            return;
        }
        BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(ACTION_STORAGE_FACE_INFO);
        ssConfigBean.setEvent(ampeAppletRequestBean.getEvent());
        ssConfigBean.setTaskId(ampeAppletRequestBean.getTaskId());
        ssConfigBean.setSuccess(isSuccess);
        ssConfigBean.setMessage(isSuccess?"成功":errMsg);
        ssConfigBean.setData(dataJson.toJSONString());
        JsonObject jsonObject = GsonUtils.getGson().toJsonTree(ssConfigBean).getAsJsonObject();
        AromeServiceInvoker.BridgeCallback bridgeCallback=ampeAppletRequestBean.getBridgeCallback();
        if (bridgeCallback != null) {
            bridgeCallback.callback(jsonObject.toString());
        }

    }

    public void onRelease(){
        openRocketUtils = null;
    }

}
