package com.ycgis.macall.personalcenter.util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.utils.TypConversion;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.m.adapterbean.AppBean;
import com.ycgis.macall.personalcenter.m.adapterbean.AppInfoBean;
import com.ycgis.macall.personalcenter.m.adapterbean.MessageBean;
import com.ycgis.macall.personalcenter.m.enumbean.AppOpenType;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.callback.SelectReturnCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.v.activity.ApplicationGuideActivity;
import com.ycgis.macall.personalcenter.v.activity.FrequentlyQuestionsActivity;
import com.ycgis.macall.personalcenter.v.activity.MsgDetailsActivity;
import com.ycgis.macall.personalcenter.v.activity.OpenAppActivity;
import com.ycgis.macall.personalcenter.v.activity.OpinionsSuggestionsActivity;
import com.ycgis.macall.personalcenter.v.activity.WorkbenchCenterActivity;
import com.ycgis.macall.personalcenter.v.activity.applyfo.ApplyForMainActivity;
import com.ycgis.macall.personalcenter.v.activity.travel.TravelAssistantActivity;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * created by:   Macall
 * create time:  2022/12/3 16:21
 * copyright:    @ruansee.com
 * Describe:    跳转第三方应用工具类
 */
public class ToThirdPartyAppUtils implements LifecycleObserver {
    private final static String TAG = "ToThirdPartyAppUtils";
    //应用市场
    private final static String APP_MARKET_PK = "com.sixin.police.market";

    private WeakReference<Context> contextWeakReference;
    private Dialog insertTips;
    private Dialog lllAppTitle;

    public ToThirdPartyAppUtils(Context context) {
        contextWeakReference = new WeakReference<>(context);
    }

    /**
     * 该方法不需要手动调用   3  盒
     * 宿主执行了onDestroy时 会分发该事件
     * 使用时请在宿主（Activity 或 Fragment ） 中调用如下代码，调用后当 宿主执行什么周期方法 onDestroy 该方法自动被调用
     * { getLifecycle().addObserver(locationGPSManage) }
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(@NotNull LifecycleOwner owner) {
        contextWeakReference.clear();
        contextWeakReference = null;
    }

    public void skipApp(AppInfoBean dataItem, AppOpenType openType) {
        if (contextWeakReference == null) return;
        if (interceptJump(String.valueOf(dataItem.getId()), dataItem.getName(), AppOpenType.LOGIN.getName()))
            return;
        AppBean bean = new AppBean();
        bean.setAppType(String.valueOf(dataItem.getType()));
        bean.setLinkUrl(dataItem.getLink());
        bean.setClientSecret(dataItem.getClientSecret());
        bean.setClientId(dataItem.getClientId());
        bean.setAppName(dataItem.getName());
        bean.setOperationName(dataItem.getOperationPerson());
        bean.setOperationPhone(dataItem.getPhoneNumber());
        skipLevel(bean, openType);
    }

    public void skipApp(AppBean dataItem) {
        if (contextWeakReference == null) return;
        if (interceptJump(dataItem.getId(), dataItem.getAppName(), AppOpenType.LOGIN.getName()))
            return;
        skipLevel(dataItem, AppOpenType.LOGIN);
    }

    private boolean interceptJump(String appId, String appName, String operatorType) {
        if (contextWeakReference == null) return true;
        Context context = contextWeakReference.get();
        if (context == null) return true;
        if (StringUtil.isNullOrEmpty(appName)) {
            ToastUtil.centered(context, "应用错误！");
            return true;
        }
        //通讯录暂时无数据 57
        if ("更多应用".equals(appName)) {
            context.startActivity(new Intent(context, WorkbenchCenterActivity.class));
//            addClickCount(appId,appName, operatorType);
            return true;
        }//应用申请
        if ("应用申请".equals(appName)) {
            context.startActivity(new Intent(context, ApplyForMainActivity.class));
            addClickCount(appId, appName, operatorType);
            return true;
        }//差旅助手
        if ("差旅助手".equals(appName)) {
            context.startActivity(new Intent(context, TravelAssistantActivity.class));
            addClickCount(appId, appName, operatorType);
            return true;
        }
        if ("应用指南".equals(appName)) {
            context.startActivity(new Intent(context, ApplicationGuideActivity.class));
//            addClickCount(appId, appName, operatorType);
            return true;
        }
        if ("常见问题".equals(appName)) {
            context.startActivity(new Intent(context, FrequentlyQuestionsActivity.class));
//            addClickCount(appId, appName, operatorType);
            return true;
        }
        if ("意见反馈".equals(appName)) {
            context.startActivity(new Intent(context, OpinionsSuggestionsActivity.class));
//            addClickCount(appId, appName, operatorType);
            return true;
        }
        return false;
    }

    public void skipLevel(AppBean bean, AppOpenType openType) {
        if (contextWeakReference == null) return;
        Context context = contextWeakReference.get();
        if ("3".equals(bean.getAppType())) {
            //原生应用
            FileUtils.startAPP(context, bean.getLinkUrl(), message -> {
                if (!message) {
                    if (contextWeakReference == null) return;
                    Context context1 = contextWeakReference.get();
                    showInstallationTips(context1);
                }
            });
        } else {
            Intent intent = new Intent(context, OpenAppActivity.class);
            intent.putExtra(OpenAppActivity.paramKey1, bean.getClientId());
            intent.putExtra(OpenAppActivity.paramKey2, bean.getClientSecret());
            intent.putExtra(OpenAppActivity.paramKey3, bean.getLinkUrl());
            intent.putExtra(OpenAppActivity.paramKey9, bean.getAppName());
            intent.putExtra(OpenAppActivity.paramKey10, bean.getOperationName());
            intent.putExtra(OpenAppActivity.paramKey11, bean.getOperationPhone());
            if ("Ⅲ类应用".equals(bean.getNetworkType())) {//三类应用
                //弹出提示框
                if (!RuanseeApplication.isShowIIIAppTitle) {
                    showIIIAppTitle(context, intent, bean.getId(), bean.getAppName(), openType.getName());
                    return;
                }
            }
            context.startActivity(intent);
        }
        addClickCount(bean.getId(), bean.getAppName(), openType.getName());
    }

    /*public void skipLevel(AppBean bean, AppOpenType openType) {
        if (contextWeakReference == null) return;
        Context context = contextWeakReference.get();
        if ("3".equals(bean.getAppType())) {
            //原生应用
            FileUtils.startAPP(context, bean.getLinkUrl(), new SelectReturnCallback<Boolean>() {
                @Override
                public void returnMsg(Boolean message) {
                    if (!message) {
                        if (contextWeakReference == null) return;
                        Context context = contextWeakReference.get();
                        showInstallationTips(context);
                    }
                }
            });
        } else {
            Intent intent = new Intent(context, OpenAppActivity.class);
            intent.putExtra(OpenAppActivity.paramKey1, bean.getClientId());
            intent.putExtra(OpenAppActivity.paramKey2, bean.getClientSecret());
            intent.putExtra(OpenAppActivity.paramKey3, bean.getLinkUrl());
            intent.putExtra(OpenAppActivity.paramKey9, bean.getAppName());
            intent.putExtra(OpenAppActivity.paramKey10, bean.getOperationName());
            intent.putExtra(OpenAppActivity.paramKey11, bean.getOperationPhone());
            if ("Ⅲ类应用".equals(bean.getNetworkType())) {//三类应用
                //弹出提示框
                if (!RuanseeApplication.isShowIIIAppTitle) {
                    showIIIAppTitle(context, intent,bean.getId());
                    return;
                }
            }
            context.startActivity(intent);
        }
        addClickCount(bean.getId(),bean.getAppName(),openType.getName());
    }*/

    private void addClickCount(String appId, String appName, String operatorType) {
        Map<String, Object> param = new HashMap<>();
        param.put("appId", appId);
        param.put("appName", appName);
        param.put("operatorName", RuanseeApplication.getUserData().getUserName());
        param.put("operatorPoliceNumber", RuanseeApplication.getUserData().getUserCode());
        param.put("operatorIdCard", RuanseeApplication.getUserData().getIdCardNum());
        param.put("deptId", RuanseeApplication.getUserData().getDeptCode());
        param.put("deptName", RuanseeApplication.getUserData().getDeptName());
        param.put("type", operatorType);
//        String url = "http://192.168.43.183:8081/wzt/app/v1/zamh/addOperationRecords";


//        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody stringBody = RequestBody.Companion.create(new Gson().toJson(param), mediaType);
        ApiModel.requestIO(RetrofitService.getBaseInstance().saveAppOperationLog(stringBody), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                LogUtils.e(TAG, msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                LogUtils.w(TAG, result.toString());
            }
        });
//        ApiModel.requestIO(RetrofitService.getBaseInstance().addClickCount(TypConversion.strToLong(appId)), new BaseRequestCallback<JsonObject>() {
//            @Override
//            public void onRequestFailure(String msg) {
//                LogUtils.e(TAG, msg);
//            }
//
//            @Override
//            public void onRequestSuccess(JsonObject result) {
//                LogUtils.w(TAG, result.toString());
//            }
//        });
    }

    private void showInstallationTips(Context context) {
        if (insertTips == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_not_insert_app, null, false);
            insertTips = new AlertDialog.Builder(context)
                    .setView(view)
                    .create();
        }
        insertTips.show();
        //提示内容
//       insertTips.findViewById(R.id.tv_msg);
        insertTips.findViewById(R.id.btn_determine).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                insertTips.dismiss();
            }
        });
        insertTips.findViewById(R.id.btn_go_insert).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                insertTips.dismiss();
                FileUtils.startAPP(context, APP_MARKET_PK, null);
            }
        });
    }

    private void showIIIAppTitle(Context context, Intent intent, String id, String appName, String operatorType) {
        if (lllAppTitle == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_show_lll_app_title, null, false);
            lllAppTitle = new AlertDialog.Builder(context)
                    .setView(view)
                    .create();
        }
        lllAppTitle.show();
        lllAppTitle.findViewById(R.id.btn_cancel).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                lllAppTitle.dismiss();
            }
        });
        lllAppTitle.findViewById(R.id.btn_confirm_open).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                lllAppTitle.dismiss();
                CheckBox checkBox = lllAppTitle.findViewById(R.id.checkBox);
                RuanseeApplication.isShowIIIAppTitle = checkBox.isChecked();
                context.startActivity(intent);
                addClickCount(id, appName, operatorType);
            }
        });
    }

    //扫描二维码

    //    /**
//     * 消息列表跳转执行此方法
//     * @param dataItem
//     */
    public void skipReadMsg(MessageBean dataItem) {
        if (contextWeakReference == null) return;
        Context context = contextWeakReference.get();
        ApiModel.uploadOperationLog("3","3","用户查看消息");
        if (dataItem.getAppExhibition() == 1) {
            Intent intent = new Intent(context, MsgDetailsActivity.class);
            intent.putExtra("msgData",dataItem);
            context.startActivity(intent);
        } else {
            Intent intent = new Intent(context, OpenAppActivity.class);
            intent.putExtra(OpenAppActivity.paramKey1, dataItem.getClientId());
            intent.putExtra(OpenAppActivity.paramKey2, dataItem.getClientSecret());
            intent.putExtra(OpenAppActivity.paramKey3, dataItem.getAppLinkUrl());
            intent.putExtra(OpenAppActivity.paramKey4, dataItem.getMsgId());
            intent.putExtra(OpenAppActivity.paramKey5, dataItem.getMsgType());
            intent.putExtra(OpenAppActivity.paramKey9, dataItem.getAppName());
            intent.putExtra(OpenAppActivity.paramKey6, "readMessage");
//        intent.putExtra(OpenAppActivity.paramKey10, dataItem.getOperationName());
//        intent.putExtra(OpenAppActivity.paramKey11, dataItem.getOperationPhone());
            context.startActivity(intent);
        }
        if (!dataItem.isRead()){
            ApiModel.requestIO(RetrofitService.getBaseInstance().readMessage(dataItem.getId()), null);
        }
        addClickCount(dataItem.getApplicationId(), dataItem.getAppName(), AppOpenType.READ_MESSAGE.getName());
    }

//    /**
//     * 从搜索结果跳转执行此方法
//     * @param id            id
//     * @param appId         应用注册ID
//     * @param secret        秘钥
//     * @param dataJson      Json数据
//     * @param url           应用链接
//     * @param searchType    搜索类型（car/person）
//     */
//    public void skipSearchData(String id,String name,String appId,String secret,String url,String searchType,String dataJson,String ywryName,String phone) {
//        if (contextWeakReference == null) return;
//        Context context = contextWeakReference.get();
//        Intent intent = new Intent(context, OpenAppActivity.class);
//        intent.putExtra(OpenAppActivity.paramKey1, appId);
//        intent.putExtra(OpenAppActivity.paramKey2, secret);
//        intent.putExtra(OpenAppActivity.paramKey3, url);
//        intent.putExtra(OpenAppActivity.paramKey6,"search");
//        intent.putExtra(OpenAppActivity.paramKey7, searchType);
//        intent.putExtra(OpenAppActivity.paramKey8, dataJson);
//        intent.putExtra(OpenAppActivity.paramKey9,name);
//        intent.putExtra(OpenAppActivity.paramKey10, ywryName);
//        intent.putExtra(OpenAppActivity.paramKey11,phone);
//        context.startActivity(intent);
//        addClickCount(id,name,AppOpenType.SEARCH.getName());
//    }
}
