package com.yidianling.uikit.business.session.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.ydl.ydlcommon.data.http.RxUtils;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.nimbase.api.model.session.SessionCustomization;
import com.yidianling.nimbase.business.preference.UserPreferences;
import com.yidianling.nimbase.business.session.constant.Extras;
import com.yidianling.nimbase.common.activity.UI;
import com.yidianling.nimbase.common.util.sys.ScreenUtil;
import com.yidianling.uikit.business.session.fragment.YDLMessageFragment;
import com.yidianling.uikit.custom.bridge.ActionHandlerStorage;
import com.yidianling.uikit.custom.bridge.IP2PCustomActionHandler;
import com.yidianling.uikit.custom.http.ServiceImpl;
import com.yidianling.uikit.custom.widget.TitleBarBottom;

import java.net.URLEncoder;
import java.util.List;

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

/**
 * Created by zhoujianghua on 2015/9/10.
 */
public abstract class YDLBaseMessageActivity extends UI {

    protected String sessionId;

    private SessionCustomization customization;

    public YDLMessageFragment messageFragment;

    public YDLMessageFragment getYDLMessageFragment() {
        return messageFragment;
    }

    protected abstract YDLMessageFragment fragment();

    protected abstract int getContentViewId();

    protected abstract void initToolBar();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getContentViewId());
        parseIntent();
        initToolBar();

        if (ActionHandlerStorage.getL(sessionId) != null) {
            ActionHandlerStorage.getL(sessionId).put(this);
        }

        messageFragment = (YDLMessageFragment) switchContent(fragment());
    }

    @Override
    public void onBackPressed() {
        if (messageFragment == null || !messageFragment.onBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (messageFragment != null) {
            messageFragment.onActivityResult(requestCode, resultCode, data);
        }

        if (customization != null) {
            customization.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    private void parseIntent() {
        sessionId = getIntent().getStringExtra(Extras.EXTRA_ACCOUNT);
        customization = (SessionCustomization) getIntent().getSerializableExtra(Extras.EXTRA_CUSTOMIZATION);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null == ActionHandlerStorage.getL(sessionId)) {
            return;
        }
        ActionHandlerStorage.getL(sessionId).resumeUm(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null == ActionHandlerStorage.getL(sessionId)) {
            return;
        }
        ActionHandlerStorage.getL(sessionId).pauseUm(this);
    }


    protected TitleBarBottom tb;

    //==================== ChatUI Override ====================

    @SuppressLint("CheckResult")
    public void setToolBar(int toolBarId) {
        tb = (TitleBarBottom) findViewById(toolBarId);
        if (ActionHandlerStorage.getL(sessionId) != null && ActionHandlerStorage.getL(sessionId).getInfo() != null) {
            tb.setTitle(ActionHandlerStorage.getL(sessionId).getInfo().name);
        }
        if (ActionHandlerStorage.getL(sessionId) != null) {
            ActionHandlerStorage.getL(sessionId).setmActivity(this);
        }

        if (!UserPreferences.isEarPhoneModeEnable()) {
            tb.setTitleRightDraw(null);
        } else {
            tb.setTitleRightDraw(getResources().getDrawable(R.drawable.im_erduoxiaolv));
        }
        IP2PCustomActionHandler actionHandler = ActionHandlerStorage.getL(sessionId);
        //获取私聊对方在线状态
        if (null != actionHandler) {
            IP2PCustomActionHandler.DocInfo docInfo = actionHandler.getInfo();
            if (null != docInfo && ("14".equals(docInfo.toUid) || "4108805".equals(docInfo.toUid))) {
                //小壹客服  不显示是否在线
                tb.setmMinTitleVisiable(View.GONE);
            } else {

                if (ActionHandlerStorage.getL(sessionId).getUserType() == 2) {
                    // 专家
                    // 调取接口获取专家状态
                    Disposable dis = ServiceImpl.Companion.getInstance()
                            .getDoctorChatStatus(Long.parseLong(ActionHandlerStorage.getL(sessionId).getInfo().toUid))
                            .compose(RxUtils.applySchedulers())
                            .subscribe(chatStatusBean -> {

                                if (ActionHandlerStorage.getL(sessionId) != null) {

                                    int status = chatStatusBean.data.getStatus();
                                    ActionHandlerStorage.getL(sessionId).setDoctorStatus(status);
                                    ActionHandlerStorage.getL(sessionId).setDoctorBusyNum(chatStatusBean.data.getBusyTotal());

                                    //1.在线，2.离线，3.忙碌 4咨询中， 5倾述中  6咨询前准备

                                    if (status == 2) {
                                        //离线
                                        tb.setMinTitleText("离线");
                                        tb.setMinTitleColor(getResources().getColor(R.color.platform_color_666666));
                                        tb.setMinTitleDrawable(getResources().getDrawable(R.drawable.im_background_chat_top_status_off_line));
                                    } else if (status == 4 || status == 5) {
                                        //服务中
                                        tb.setMinTitleText("服务中");
                                        tb.setMinTitleColor(getResources().getColor(R.color.platform_color_666666));
                                        tb.setMinTitleDrawable(getResources().getDrawable(R.drawable.im_background_chat_top_status_online_server));
                                    } else {
                                        //在线  1，3，6..
                                        tb.setMinTitleText("在线");
                                        tb.setMinTitleColor(getResources().getColor(R.color.platform_color_666666));
                                        tb.setMinTitleDrawable(getResources().getDrawable(R.drawable.im_background_chat_top_status_online));
                                    }

                                    initSystemMessage(chatStatusBean.data.getPromptRule(), status);
                                }

                            }, throwable -> {
                                LogUtil.i("getDoctorChatStatus throwable:"+throwable);
                            });
                } else if (ActionHandlerStorage.getL(sessionId).getUserType() == 3) {
                    // 助理
                    // 调取接口获取助理状态
                    ServiceImpl.Companion.getInstance().getAssistantChatStatus(Long.parseLong(ActionHandlerStorage.getL(sessionId).getInfo().toUid))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(res -> {
                                if (ActionHandlerStorage.getL(sessionId) != null) {
                                    if (res.data == 1) {
                                        //在线
                                        tb.setMinTitleText("在线");
                                        tb.setMinTitleColor(getResources().getColor(R.color.platform_color_666666));
                                        tb.setMinTitleDrawable(getResources().getDrawable(R.drawable.im_background_chat_top_status_online));
                                    } else {
                                        //离线
                                        tb.setMinTitleText("离线");
                                        tb.setMinTitleColor(getResources().getColor(R.color.platform_color_666666));
                                        tb.setMinTitleDrawable(getResources().getDrawable(R.drawable.im_background_chat_top_status_off_line));
                                    }
                                }
                            }, throwable -> {
                            });
                } else {
                    tb.setmMinTitleVisiable(View.GONE);
                }
            }
        }
        if (customization != null) {
            addRightCustomViewOnActionBar(this, customization.buttons);
        }
    }

    // promptRule 判断是否推荐专家  4，5直接不走文本提示和推荐逻辑，1，3不走推荐逻辑
    //初始化 根据专家在线状态来发送提示消息或者推荐消息
    private void initSystemMessage(int promptRule, int status) {
        if (!(promptRule == 4 || promptRule == 5)) {

            boolean showExpertList = !(promptRule == 1 || promptRule == 3);
            if (ActionHandlerStorage.getL(sessionId).getUserType() == 2 && status == 2) {
                //当该专家离线时
                sendRecommendExpertListMessage(1, showExpertList);

            } else if (ActionHandlerStorage.getL(sessionId).getUserType() == 2 && status >= 3) {
                //当该专家忙碌时
                sendRecommendExpertListMessage(2, showExpertList);
            }
        }
    }

    /**
     * 发送推荐专家列表
     */
    @SuppressLint("CheckResult")
    public void sendRecommendExpertListMessage(int type, boolean showExpertList) {

        // 调取接口获取推荐专家列表
        ServiceImpl.Companion.getInstance().getRecommendExpertList(
                Long.parseLong(ActionHandlerStorage.getL(sessionId).getInfo().toUid),
                URLEncoder.encode(ActionHandlerStorage.getL(sessionId).getInfo().tag1),
                3)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    //发送推荐专家列表消息
                    if (ActionHandlerStorage.getL(sessionId) != null) {
                        ActionHandlerStorage.getL(sessionId).sendRecommendExpertListMessage(sessionId, res.data, type, showExpertList);
                    }
                }, throwable -> {
                    ToastUtil.toastShort(throwable.toString());
                });
    }

    // 添加action bar的右侧按钮及响应事件
    private void addRightCustomViewOnActionBar(Activity activity, List<SessionCustomization.OptionsButton> buttons) {
        if (buttons == null || buttons.size() == 0) {
            return;
        }
        TitleBarBottom tb = getTitleBarBottom();
        if (tb == null) {
            return;
        }

        LinearLayout view = (LinearLayout) LayoutInflater.from(activity).inflate(R.layout.im_nim_action_bar_custom_view, null);


        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        for (final SessionCustomization.OptionsButton button : buttons) {
            ImageView imageView = new ImageView(activity);
            imageView.setImageResource(button.iconId);
            imageView.setPadding(ScreenUtil.dip2px(10), 0, ScreenUtil.dip2px(20), 0);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    button.onClick(YDLBaseMessageActivity.this, v, sessionId);
                }
            });
            view.addView(imageView, params);
        }

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        tb.addView(view, layoutParams);
    }

    public TitleBarBottom getTitleBarBottom() {
        return tb;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        IP2PCustomActionHandler actionHandler = ActionHandlerStorage.getL(sessionId);
        if (null == actionHandler) {
            return;
        }
        if (null == actionHandler.getmActivity()) {
            actionHandler.setmActivity(this);
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if (null == tb) {
            return;
        }
        tb.setTitle(title.toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
