package com.hh.lib_device;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.alipay.arome.aromecli.AromeServiceTask;
import com.alipay.arome.aromecli.requst.AromeExitAppRequest;
import com.alipay.arome.aromecli.response.AromeExitAppResponse;
import com.google.gson.JsonObject;
import com.hh.lib_ampe.bean.BaseAmpeAppletResultBean;
import com.hh.lib_ampe.bean.BaseAmpeRequestBean;
import com.hh.lib_ampe.utils.MyTypeToken;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.ConfigData;
import com.hh.lib_base.Constants;
import com.hh.lib_base.activity.BaseActivity;
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.GsonUtils;
import com.hh.lib_base.utils.device.DeviceUtils;
import com.hh.lib_device.bean.action.AmpeDeviceConfigResultBean;
import com.hh.lib_device.bean.action.AmpeDeviceConfigBean;
import com.hh.lib_device.bean.action.AmpeDeviceInfoResultBean;
import com.hh.lib_device.bean.action.AmpeRequestDownloadFileBean;
import com.hh.lib_device.bean.action.AmpeRequestFloatingBackBean;
import com.hh.lib_device.bean.action.AmpeResultDownloadFileBean;
import com.hh.lib_device.bean.download.AmpeDownloadFileEvent;
import com.hh.lib_device.deviceui.BaseDeviceUI;
import com.hh.lib_device.deviceui.IDeviceUI;
import com.hh.lib_device.utils.DownloadFileUtils;
import com.hh.lib_device.view.TouchBackView;


/**
 *
 * @author xwh
 * time 2024/8/29
 * Description: 设备AMPE能力调用器
 **/
public class DevicesInvoker {

    private volatile static DevicesInvoker devicesInvoker;

    private TouchBackView touchBackView; //小程序悬浮退出按钮

    private DownloadFileUtils downloadFileUtils;
    /**
     *
     * @author xwh
     * Time 2024/8/29
     * Description:设备功能交互入口
     *
    **/
    public void onCalled(Context context, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        switch (dataBean.getAction()) {
            case Constants.Ampe.ACTION_DEVICE: //TODO 设备信息
                getDeviceInfo(dataBean.getEvent(),dataBean.getTaskId(),bridgeCallback);
                break;
            case Constants.Ampe.ACTION_DEVICE_CONFIG: //TODO 设备配置导航栏、状态栏等
                deviceTempConfig(context,dataBean,bridgeCallback);
                break;
            case Constants.Ampe.ACTION_FLOATINGEXITBUTTON:
                showFloatingBackButton(context,dataBean);
                break;
            case Constants.Ampe.ACTION_STORAGE:
                if (AmpeDownloadFileEvent.SET.equals(dataBean.getEvent())) {
                    saveStorage(dataBean);
                } else if (AmpeDownloadFileEvent.GET.equals(dataBean.getEvent())) {
                    getStorageList(dataBean);
                } else if (AmpeDownloadFileEvent.REMOVE.equals(dataBean.getEvent())) {
                    removeStorage(dataBean);
                }
                break;
            default:
                
                break;
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/8/29
     * Description: 返回设备信息
     *
    **/
    private void getDeviceInfo(String event, String taskId, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        BaseAmpeAppletResultBean bean = new BaseAmpeAppletResultBean();
        bean.setAction(Constants.Ampe.ACTION_DEVICE);
        bean.setEvent(event);
        bean.setTaskId(taskId);
        bean.setSuccess(true);
        bean.setMessage("成功");

        AmpeDeviceInfoResultBean dataBean = new AmpeDeviceInfoResultBean();
        // sn
        dataBean.setSn(DeviceUtils.getDeviceSN());
        // 设备型号
        dataBean.setDeviceModel(DeviceUtils.getDeviceModel());
        // IP
        dataBean.setDeviceIP(DeviceUtils.getDeviceIP());
        // 设备固件号
        dataBean.setDeviceDisplay(DeviceUtils.getDeviceDisplay());
        // app版本号
        dataBean.setAppVersion(DeviceUtils.getAppVersionCode(BaseApplication.getContext()) + "");
        // android版本
        dataBean.setAndroidVersion(DeviceUtils.getAndroidVersion());
        // 设置data
        bean.setData(dataBean);
        AppLogUtils.e("bean:" + bean.toString());

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append("jsonObject = ").append(jsonObject);
            UploadLogUtils.sendLogs("设备信息--回传处理结果给小程序--",
                    Constants.Ampe.ACTION_DEVICE,logLine,logContentSb.toString());
        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }


    /**
     *
     * Description: 设备配置
     * @author xwh
     * Time 2024/7/15
     *
     **/
    private void deviceTempConfig(Context context,BaseAmpeRequestBean requestBean
            , AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (requestBean == null) {
            return;
        }
        BaseAmpeRequestBean<AmpeDeviceConfigResultBean> newRequestBean = MyTypeToken
                .toBaseAmpeRequestBean(requestBean, AmpeDeviceConfigResultBean.class);
        if (newRequestBean == null) {
            return;
        }
        AmpeDeviceConfigResultBean data = null;
        try {
            data = newRequestBean.getParams();
        } catch (ClassCastException e) {

        }
        boolean isSuccess = false;
        String errMsg = "失败";
        if (data != null && data.getDeviceConfig() != null) {
            AmpeDeviceConfigBean deviceConfig = data.getDeviceConfig();
            int exitApplet = deviceConfig.getExitApplet();
            if (exitApplet == 1) {
                DeviceConfigResultBean configResultBean= ConfigData.getDeviceConfigResultBean();
                if(configResultBean==null){
                    return;
                }
                exitApplet(configResultBean.getMiniProgramAppid());
                isSuccess = true;
            }
            IDeviceUI iDeviceUI = BaseDeviceUI.getInstance().getDeviceUI();
            if (iDeviceUI != null) {
                int navigationBar = deviceConfig.getHideNavigationBar();
                if (navigationBar == 1 && context instanceof Activity) {
                    iDeviceUI.hideNavigationBar((Activity) context);
                } else if (navigationBar == 2) {
                    iDeviceUI.showNavigationBar((Activity) context);
                }
                int notificationBar = deviceConfig.getHideNotificationBar();
                if (notificationBar == 1) {
                    iDeviceUI.hideNotification((Activity) context);
                } else if (notificationBar == 2) {
                    iDeviceUI.showNotification((Activity) context);
                }
                isSuccess = true;
            }
        } else {
            errMsg = "入参参数错误！";
        }

        BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_DEVICE_CONFIG);
        ssConfigBean.setEvent(newRequestBean.getEvent());
        ssConfigBean.setTaskId(newRequestBean.getTaskId());
        ssConfigBean.setSuccess(isSuccess);
        ssConfigBean.setMessage(isSuccess ? "成功" : errMsg);
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(ssConfigBean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs("设备配置（导航栏、状态栏）----",
                    Constants.Ampe.ACTION_DEVICE_CONFIG, logLine, jsonObject.toString());
        } catch (Exception e) {
            AppLogUtils.e(e.toString());
        }
    }

    /**
     * 1050 未找到运行中的小程序
     */
    public void exitApplet(String appid) {
        AppLogUtils.e("exitApplet");
        AromeExitAppRequest request = new AromeExitAppRequest();
        request.appId = appid;
        AppLogUtils.e("exitApplet--appId&appletId:" + appid);
        AromeServiceInvoker.invoke(request, new AromeServiceTask.Callback<AromeExitAppResponse>() {
            @Override
            public void onCallback(final AromeExitAppResponse response) {
                AppLogUtils.e("exitApplet--response:" + response);
            }
        });
    }

    /**
     *
     * @author xwh
     * Time 2024/9/14
     * Description: 悬浮返回按钮
     *
     **/
    private synchronized void showFloatingBackButton(Context context,BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<AmpeRequestFloatingBackBean> newRequestBean=MyTypeToken
                .toBaseAmpeRequestBean(requestBean,AmpeRequestFloatingBackBean.class);
        if(newRequestBean==null){
            return;
        }
        String appId = newRequestBean.getParams().getAppId();
        boolean isOpen=newRequestBean.getParams().isOpen();
        if(isOpen){
            if (touchBackView != null && touchBackView.isAttachedToWindow()) {
                return;
            }
            if(touchBackView!=null){
                touchBackView.release();
            }
            touchBackView=null;
            boolean isSuccess = true;
            String errMsg="失败";
            if (TextUtils.isEmpty(appId)) {
                errMsg="appid为空";
                isSuccess = false;
            }

            if (isSuccess && touchBackView == null) {
                synchronized (DevicesInvoker.class) {
                    if (touchBackView == null) {
                        if(context!=null&&context instanceof BaseActivity){
                            ((BaseActivity) context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    touchBackView = new TouchBackView(context, appId);
                                }
                            });
                        }
                    }
                }
            }
            BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
            ssConfigBean.setAction(Constants.Ampe.ACTION_FLOATINGEXITBUTTON);
            ssConfigBean.setEvent(newRequestBean.getEvent());
            ssConfigBean.setTaskId(newRequestBean.getTaskId());
            ssConfigBean.setSuccess(isSuccess);
            ssConfigBean.setMessage(isSuccess?"成功":errMsg);
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(ssConfigBean).getAsJsonObject();
            if (newRequestBean.getBridgeCallback() != null) {
                newRequestBean.getBridgeCallback() .callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_FLOATINGEXITBUTTON,
                    Constants.Ampe.ACTION_FLOATINGEXITBUTTON,logLine
                    ,"已打开悬浮返回按钮---"+jsonObject);

        }else{
            if(touchBackView!=null){
                touchBackView.release();
                touchBackView=null;
            }
            BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
            ssConfigBean.setAction(Constants.Ampe.ACTION_FLOATINGEXITBUTTON);
            ssConfigBean.setEvent(newRequestBean.getEvent());
            ssConfigBean.setTaskId(newRequestBean.getTaskId());
            ssConfigBean.setSuccess(true);
            ssConfigBean.setMessage("已关闭悬浮返回按钮");
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(ssConfigBean).getAsJsonObject();
            if (newRequestBean.getBridgeCallback() != null) {
                newRequestBean.getBridgeCallback().callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_FLOATINGEXITBUTTON,
                    Constants.Ampe.ACTION_FLOATINGEXITBUTTON,logLine
                    ,"已关闭悬浮返回按钮---"+jsonObject);
        }
    }


    /**
     *
     * @author xwh
     * Time 2024/11/14
     * Description: 保存文件
     *
     **/
    private void saveStorage(BaseAmpeRequestBean requestBean){
        if (requestBean == null) {
            return;
        }
        BaseAmpeRequestBean<AmpeRequestDownloadFileBean> newRequestBean = MyTypeToken
                .toBaseAmpeRequestBean(requestBean, AmpeRequestDownloadFileBean.class);
        if (newRequestBean == null || newRequestBean.getParams() == null) {
            return;
        }
        AmpeRequestDownloadFileBean params= newRequestBean.getParams();
        DownloadFileUtils.getInstance().downLoadFile(params.getFileName(), params.getFileName()
                , new DownloadFileUtils.DownloadFileListener() {
                    @Override
                    public void saveSuccess( AmpeResultDownloadFileBean data) {
                        saveStorageCallBack(newRequestBean,data,true);
                    }

                    @Override
                    public void saveFailed(int code, String errMsg) {
                        saveStorageCallBack(newRequestBean,null,false);
                    }
                });

    }
    /**
     *
     * @author xwh
     * Time 2024/12/6
     * Description: 保存文件返回事件
     *
    **/
    private void saveStorageCallBack(BaseAmpeRequestBean requestBean, AmpeResultDownloadFileBean data, boolean isSuccess){
        if(requestBean==null){
            return;
        }
        BaseAmpeAppletResultBean result = new BaseAmpeAppletResultBean();
        result.setTaskId(requestBean.getTaskId());
        result.setAction(requestBean.getAction());
        result.setEvent(requestBean.getEvent());
        result.setSuccess(isSuccess);
        result.setMessage(isSuccess?"成功":"失败");
        if(isSuccess){
            result.setData(data);
        }
        JsonObject jsonObject = GsonUtils.getGson().toJsonTree(result).getAsJsonObject();
        if (requestBean.getBridgeCallback() != null) {
            requestBean.getBridgeCallback().callback(jsonObject.toString());
        }
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_DOWNLOADFILE,
                Constants.Ampe.ACTION_STORAGE+"   "+requestBean.getEvent(),logLine
                ,jsonObject.toString());
    }

    /**
     *
     * @author xwh
     * Time 2024/12/6
     * Description: 获取缓存文件列表
     *
    **/
    private void getStorageList(BaseAmpeRequestBean requestBean){
        if (requestBean == null) {
            return;
        }
        BaseAmpeAppletResultBean result = new BaseAmpeAppletResultBean();
        result.setTaskId(requestBean.getTaskId());
        result.setAction(requestBean.getAction());
        result.setEvent(requestBean.getEvent());
        result.setSuccess(true);
        result.setMessage("成功");
        result.setData(DownloadFileUtils.getInstance().getFileList());
        JsonObject jsonObject = GsonUtils.getGson().toJsonTree(result).getAsJsonObject();
        if (requestBean.getBridgeCallback() != null) {
            requestBean.getBridgeCallback().callback(jsonObject.toString());
        }
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_DOWNLOADFILE,
                Constants.Ampe.ACTION_STORAGE+"   "+requestBean.getEvent(),logLine
                ,jsonObject.toString());
    }
    /**
     *
     * @author xwh
     * Time 2024/12/6
     * Description: 删除文件
     *
    **/
    private void removeStorage(BaseAmpeRequestBean requestBean){
        if (requestBean == null) {
            return;
        }
        BaseAmpeRequestBean<AmpeRequestDownloadFileBean> newRequestBean = MyTypeToken
                .toBaseAmpeRequestBean(requestBean, AmpeRequestDownloadFileBean.class);
        if (newRequestBean == null || newRequestBean.getParams() == null) {
            return;
        }
        AmpeRequestDownloadFileBean params= newRequestBean.getParams();
       boolean isDeleted= DownloadFileUtils.getInstance().deleteFile(params.getPath());
       
        BaseAmpeAppletResultBean result = new BaseAmpeAppletResultBean();
        result.setTaskId(requestBean.getTaskId());
        result.setAction(requestBean.getAction());
        result.setEvent(requestBean.getEvent());
        result.setSuccess(isDeleted);
        result.setMessage(isDeleted?"成功":"失败");
        JsonObject jsonObject = GsonUtils.getGson().toJsonTree(result).getAsJsonObject();
        if (requestBean.getBridgeCallback() != null) {
            requestBean.getBridgeCallback().callback(jsonObject.toString());
        }
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_DOWNLOADFILE,
                Constants.Ampe.ACTION_STORAGE+"   "+requestBean.getEvent(),logLine
                ,jsonObject.toString());
    }

    public static DevicesInvoker getInstance() {
        if (devicesInvoker == null) {
            synchronized (DevicesInvoker.class) {
                if (devicesInvoker == null) {
                    devicesInvoker = new DevicesInvoker();

                }
            }
        }
        return devicesInvoker;
    }

    public void onRelease(){
        DeviceConfigResultBean deviceConfigBean=ConfigData.getDeviceConfigResultBean();
        if(deviceConfigBean!=null) {
            exitApplet(deviceConfigBean.getMiniProgramAppid());
        }
        if (touchBackView != null) {
            touchBackView.release();
            touchBackView = null;
        }
        if(downloadFileUtils!=null){
            downloadFileUtils.release();
            downloadFileUtils = null;
        }
        devicesInvoker = null;
    }
}
