package com.yidianling.im.helper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;

import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.data.http.BaseResponse;
import com.ydl.ydlcommon.data.http.UpLoadLogUtils;
import com.ydl.ydlcommon.ui.LoadingDialogFragment;
import com.ydl.ydlcommon.utils.NetworkParamsUtils;
import com.ydl.ydlcommon.utils.UserInfoCache;
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.im.api.bean.IMExpertBuild;
import com.yidianling.im.bean.DoctorAssistantRespDtoBean;
import com.yidianling.im.bean.GetExpert;
import com.yidianling.im.bridge.P2PCustomActionHandlerImpl;
import com.yidianling.im.config.constants.ImConstants;
import com.yidianling.im.http.ImRetrofitApi;
import com.yidianling.im.router.ImIn;
import com.yidianling.im.session.SessionHelper;
import com.yidianling.uikit.business.session.helper.ChatStatusCacheHelper;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

//import com.ydl.ydlcommon.dialog.CommonDialog;

/**
 * Created by Jim on 2017/12/13 0013.
 * 聊天接口封装
 */
public class IMUtil {

    public static final int FLAG_SAVE = 0x001;
    public static final int FLAG_USE_UM = 0x002;

    public interface ExpertDataFetchListener {
        void onDataFetched(BaseResponse<IMExpertBuild> datas);
    }

    public static void startChat(AppCompatActivity context, String toUid, int flag, int canTalk, ExpertDataFetchListener listener) {
        startChat(context, toUid, flag, canTalk, listener, 0, false);
    }

    /**
     * 客服专用
     */
    public static void startKefuChat(AppCompatActivity context, String toUid, int flag, int canTalk, ExpertDataFetchListener listener) {
        SessionHelper.startP2PSession(context, -1, "14", null,
                new P2PCustomActionHandlerImpl("14", "客服小壹", "14"));
    }

    /**
     * @param context
     * @param toUid
     * @param flag
     * @param canTalk
     * @param listener
     * @param isFromQingShu     用于判断是否从倾诉流程跳转私聊：1：是   其他：不是    从倾述流程跳转私聊，需要发送自定义消息
     * @param isFromMessageList 用于判断是否来自于聊天列表点击进入 true 是 false，不是
     */
    @SuppressLint("CheckResult")
    public static void startChat(AppCompatActivity context, String toUid, int flag, int canTalk, ExpertDataFetchListener listener, int isFromQingShu, boolean isFromMessageList) {
        if (!ImIn.INSTANCE.isLogin(context, true)) {
            return;
        }

        boolean isSaveUserInfo = (flag & FLAG_SAVE) != 0;
        boolean isUseUm = (flag & FLAG_USE_UM) != 0;
        LogUtil.d("isSaveUserInfo: " + isSaveUserInfo + " isUseUm: " + isUseUm);
        LoadingDialogFragment dialog = LoadingDialogFragment.Companion.newInstance(null);

        if (context.getSupportFragmentManager() != null && !context.isDestroyed()) {
            dialog.show(context.getSupportFragmentManager(), null);
        }

        GetExpert cmd = new GetExpert(Integer.parseInt(toUid), canTalk);


        if (isFromMessageList) {
            //先根据uid判断用户类型：专家调一个接口，非专家调另外的接口
            ImRetrofitApi.Companion.getImJavaApi().getUserType(toUid)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(res -> {
                        if (res.code == 200 && res.data != null) {
                            if (res.data.getChatEvent()) {//和助理私聊需要打开常用语弹窗
                                ChatStatusCacheHelper.setStatusCache("chatEvent", res.data.getChatEvent());
                            }
                            if (res.data.getCollectEvent()) {//和助理私聊需要打开信息采集弹窗
                                ChatStatusCacheHelper.setStatusCache("collectEvent", res.data.getCollectEvent());
                            }

                            if (TextUtils.equals(res.data.getUserType(), "2")) {//专家 java 接口
                                //如果是从消息列表点击进来的，那么专家还是专家，助理还是助理，不走其他所有逻辑（比如销售代运营）
                                if (isFromMessageList) {
                                    startExpertChat(context, toUid, dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
                                    return;
                                }

                                //在uid用户类型确定为专家的情况下，根据uid调用接口判断是进入专家私聊还是助理私聊
                                ImRetrofitApi.Companion.getImJavaApi().getChatUid((toUid))
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(resp -> {

                                            DoctorAssistantRespDtoBean bean = resp.data;
                                            if (bean.getRole() == 1) {
                                                //接口返回值是专家，java接口
                                                startExpertChat(context, bean.getChatUid(), dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
                                            } else {

                                                GetExpert cmd1 = new GetExpert(Integer.parseInt(bean.getChatUid()), canTalk);
                                                //接口返回值是助理，php接口
                                                startAssistantChat(context, bean.getChatUid(), cmd1, dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
                                            }

                                        }, t -> {
                                            HttpErrorUtils.Companion.handleError(context, t);
                                        });
                            } else {//非专家 php接口
                                startAssistantChat(context, toUid, cmd, dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
                            }
                        } else {
                            if (dialog.isVisible()) {
                                dialog.dismissAllowingStateLoss();
                            }
                            ToastUtil.toastShort(res.msg);
                        }
                    }, throwable -> {
                        if (dialog.isVisible()) {
                            dialog.dismissAllowingStateLoss();
                        }
                        HttpErrorUtils.Companion.handleError(context, throwable);
                    });

        } else {
            ImRetrofitApi.Companion.getImJavaApi().getChatUid(toUid)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(getChatUidResp -> {

                        DoctorAssistantRespDtoBean bean = getChatUidResp.data;
                        ImRetrofitApi.Companion.getImJavaApi().getUserType(bean.chatUid)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(userTypeResp -> {
                                    if (userTypeResp.code == 200 && userTypeResp.data != null) {
                                        if (userTypeResp.data.getChatEvent()) {//和助理私聊需要打开常用语弹窗
                                            ChatStatusCacheHelper.setStatusCache("chatEvent", userTypeResp.data.getChatEvent());
                                        }
                                        if (userTypeResp.data.getCollectEvent()) {//和助理私聊需要打开信息采集弹窗
                                            ChatStatusCacheHelper.setStatusCache("collectEvent", userTypeResp.data.getCollectEvent());
                                        }

                                        if (TextUtils.equals(userTypeResp.data.getUserType(), "2")) {//专家 java 接口
                                            //接口返回值是专家，java接口
                                            startExpertChat(context, bean.chatUid, dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
                                        } else {
                                            //非专家 php接口

                                            GetExpert cmd1 = new GetExpert(Integer.parseInt(bean.chatUid), canTalk);
                                            startAssistantChat(context, bean.chatUid, cmd1, dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
                                        }

                                    } else {
                                        if (dialog.isVisible()) {
                                            dialog.dismissAllowingStateLoss();
                                        }
                                        ToastUtil.toastShort(userTypeResp.msg);
                                    }
                                }, throwable -> {
                                    if (dialog.isVisible()) {
                                        dialog.dismissAllowingStateLoss();
                                    }
                                    HttpErrorUtils.Companion.handleError(context, throwable);
                                });

                    }, t -> {
                        if (dialog.isVisible()) {
                            dialog.dismissAllowingStateLoss();
                        }
                        HttpErrorUtils.Companion.handleError(context, t);
                    });

        }


//        //先根据uid判断用户类型：专家调一个接口，非专家调另外的接口
//        Disposable disposable = ImRetrofitApi.Companion.getImJavaApi().getUserType(toUid)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(res -> {
//                    if (res.code == 200) {
//                        if (TextUtils.equals(res.data, "2")) {//专家 java 接口
//
//                            //如果是从消息列表点击进来的，那么专家还是专家，助理还是助理，不走其他所有逻辑（比如销售代运营）
//                            if (isFromMessageList) {
//                                startExpertChat(context, toUid, dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
//                                return ;
//                            }
//
//                            //在uid用户类型确定为专家的情况下，根据uid调用接口判断是进入专家私聊还是助理私聊
//                            Disposable disposa =  ImRetrofitApi.Companion.getImJavaApi().getChatUid((toUid))
//                                    .subscribeOn(Schedulers.io())
//                                    .observeOn(AndroidSchedulers.mainThread())
//                                    .subscribe(resp -> {
//
//                                        DoctorAssistantRespDtoBean bean = resp.data;
//                                        if (bean.getRole() == 1) {
//                                            //接口返回值是专家，java接口
//                                            startExpertChat(context, bean.getChatUid(), dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
//                                        }else {
//
//                                            GetExpert cmd1 = new GetExpert(Integer.parseInt(bean.getChatUid()), canTalk);
//                                            //接口返回值是助理，php接口
//                                            startAssistantChat(context, bean.getChatUid(), cmd1, dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
//                                        }
//
//                                    },t->{
//                                        HttpErrorUtils.Companion.handleError(context, t);
//                                    });
//                        } else {//非专家 php接口
//                            startAssistantChat(context, toUid, cmd, dialog, listener, isUseUm, isSaveUserInfo, isFromQingShu);
//                        }
//                    } else {
//                        if (dialog.isVisible()) {
//                            dialog.dismissAllowingStateLoss();
//                        }
//                        ToastUtil.toastShort(res.msg);
//                    }
//                }, throwable -> {
//                    if (dialog.isVisible()) {
//                        dialog.dismissAllowingStateLoss();
//                    }
//                    HttpErrorUtils.Companion.handleError(context, throwable);
//                });
    }

    /**
     * 专家私聊
     */
    public static void startExpertChat(AppCompatActivity context, String toUid, LoadingDialogFragment dialog,
                                       ExpertDataFetchListener listener, boolean isUseUm, boolean isSaveUserInfo, int isFromQingShu) {
        Disposable disposable = ImRetrofitApi.Companion.getImJavaApi().getPersonalChat(toUid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    if (null != dialog && dialog.isVisible()) {
                        dialog.dismissAllowingStateLoss();
                    }
                    if (listener != null) {
                        listener.onDataFetched(resp);
                        return;
                    }
                    if (resp.code == 200) {
                        IMExpertBuild expert = resp.data;
                        if (isSaveUserInfo) {
                            UserInfoCache.getInstance().saveYDLUser(expert.shareData.toUid, expert.shareData.doctorName, expert.shareData.cover);
                        }
                        P2PCustomActionHandlerImpl P2PCustomActionHandlerImpl = new P2PCustomActionHandlerImpl(toUid, expert);
                        P2PCustomActionHandlerImpl.isFromQingShu = isFromQingShu;
                        SessionHelper.startP2PSession(context, expert.shareData.user_type, toUid, null, P2PCustomActionHandlerImpl);
                    } else {
                        UpLoadLogUtils.INSTANCE.upLoadLog("consult/get-expert", resp.code, resp.msg);
                        if (resp.code == ImConstants.HTTP_CODE_UNLOGIN) {
                            context.startActivity(ImIn.INSTANCE.loginWayIntent(context));
                            ToastUtil.toastShort(resp.msg);
                        } else if (resp.code == ImConstants.SILENCED_CODE) {     //禁言
                            showSilencedDialog(context, resp.data.tips, resp.data.url);
                        } else {
                            ToastUtil.toastShort(resp.msg);
                        }
                    }
                }, throwable -> {
                    if (null != dialog && dialog.isVisible()) {
                        dialog.dismissAllowingStateLoss();
                    }
                    HttpErrorUtils.Companion.handleError(context, throwable);
                    if (throwable instanceof HttpException) {
                        UpLoadLogUtils.INSTANCE.upLoadLog("consult/get-expert", ((HttpException) throwable).code(), throwable.getMessage());
                    }
                });
    }

    /**
     * 助理私聊
     */
    public static void startAssistantChat(AppCompatActivity context, String toUid, GetExpert cmd, LoadingDialogFragment dialog, ExpertDataFetchListener listener
            , boolean isUseUm, boolean isSaveUserInfo, int isFromQingShu) {
        Disposable disposable = ImRetrofitApi.Companion.getImRetrofitApi().getExpert(NetworkParamsUtils.getMaps(cmd)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    if (null != dialog && dialog.isVisible()) {
                        dialog.dismissAllowingStateLoss();
                    }
                    if (listener != null) {
                        listener.onDataFetched(resp);
                        return;
                    }
                    if (resp.code == 0) {
                        IMExpertBuild expert = resp.data;
                        if (isSaveUserInfo) {
                            UserInfoCache.getInstance().saveYDLUser(expert.shareData.toUid, expert.shareData.doctorName, expert.shareData.cover);
                        }
                        P2PCustomActionHandlerImpl p2PCustomActionHandlerImpl = new P2PCustomActionHandlerImpl(toUid, expert);
                        p2PCustomActionHandlerImpl.isFromQingShu = isFromQingShu;
                        SessionHelper.startP2PSession(context, expert.shareData.user_type, toUid, null, p2PCustomActionHandlerImpl);
                    } else {
                        UpLoadLogUtils.INSTANCE.upLoadLog("consult/get-expert", resp.code, resp.msg);
                        if (resp.code == ImConstants.HTTP_CODE_UNLOGIN) {
                            context.startActivity(ImIn.INSTANCE.loginWayIntent(context));
                            ToastUtil.toastShort(resp.msg);
                        } else if (resp.code == ImConstants.SILENCED_CODE) {     //禁言
                            showSilencedDialog(context, resp.data.tips, resp.data.url);
                        } else {
                            ToastUtil.toastShort(resp.msg);
                        }
                    }
                }, throwable -> {
                    if (null != dialog && dialog.isVisible()) {
                        dialog.dismissAllowingStateLoss();
                    }
                    HttpErrorUtils.Companion.handleError(context, throwable);
                    if (throwable instanceof HttpException) {
                        UpLoadLogUtils.INSTANCE.upLoadLog("consult/get-expert", ((HttpException) throwable).code(), throwable.getMessage());
                    }
                });
    }

    public static void showSilencedDialog(Context context, String tips, String url) {

        CommonDialog.create(context)
                .setMessage(tips)
                .setLeftOnclick(context.getString(R.string.im_details), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String realUrl = TextUtils.isEmpty(url) ? ImConstants.HELP_URL : url;
                        H5Params params = new H5Params(realUrl, "");
                        NewH5Activity.start(context, params);
                    }
                })
                .setRightClick(context.getString(R.string.im_approval), null)
                .show();
    }

}
