package com.bc_chat.im.redpackage;

import android.content.Context;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bc_chat.bc_base.http.Encryption;
import com.bc_chat.bc_base.http.RetrofitHelper;
import com.bc_chat.im.R;
import com.bc_chat.im.activity.envelopes.ChatRedDetailsActivity;
import com.bc_chat.im.activity.envelopes.MucRedDetailsActivity;
import com.bc_chat.im.activity.envelopes.RedDialog;
import com.google.gson.JsonObject;
import com.jrmf360.rylib.common.util.LogUtil;
import com.jrmf360.rylib.common.util.ToastUtil;
import com.jrmf360.rylib.common.util.p;
import com.jrmf360.rylib.rp.extend.CurrentUser;
import com.jrmf360.rylib.rp.extend.SendUser;
import com.zhaohaoting.framework.abs.entity.ResultEntity;
import com.zhaohaoting.framework.requset.HttpCode;
import com.zhaohaoting.framework.utils.ToastUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;
import io.rong.imkit.RongContext;
import io.rong.imkit.model.ProviderTag;
import io.rong.imkit.model.UIMessage;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imkit.widget.provider.IContainerItemProvider;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;

@ProviderTag(
        messageContent = RCRedPackageMessage.class,
        showReadState = false
)
public class RCRedPackageMessageProvider extends IContainerItemProvider.MessageProvider<RCRedPackageMessage> {

    private RedDialog mRedDialog;
    private UserInfo userInfo;
    private Conversation.ConversationType currentConversationType;

    @Override
    public void bindView(View view, int i, RCRedPackageMessage redPackageMessage, UIMessage uiMessage) {
        ViewHolder holder = (ViewHolder) view.getTag();
        if (uiMessage.getMessageDirection() == Message.MessageDirection.SEND) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                holder.bri_bg.setBackground(RongContext.getInstance().getDrawable(R.drawable.m_bg_from_hongbao2));
            }
            holder.tv_bri_target.setPadding(p.a(RongContext.getInstance(), 60.0F), 0, 0, 0);
            holder.tv_bri_target.setText(RongContext.getInstance().getString(R.string.jrmf_rp_look_rp));
            holder.tv_bri_name.setPadding(28, 0, 0, 0);
            holder.tv_bri_mess.setPadding(p.a(RongContext.getInstance(), 60.0F), 0, p.a(RongContext.getInstance(), 10.0F), 0);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                holder.bri_bg.setBackground(RongContext.getInstance().getDrawable(R.drawable._bg_to_hongbao2));
            }
            holder.tv_bri_target.setPadding(p.a(RongContext.getInstance(), 65.0F), 0, 0, 0);
            holder.tv_bri_target.setText(RongContext.getInstance().getString(R.string.jrmf_rp_receive_rp));
            holder.tv_bri_name.setPadding(48, 0, 0, 0);
            holder.tv_bri_mess.setPadding(p.a(RongContext.getInstance(), 65.0F), 0, p.a(RongContext.getInstance(), 5.0F), 0);
        }
        holder.tv_bri_mess.setText(redPackageMessage.getBribery_Message());
        holder.tv_bri_name.setText(redPackageMessage.getBribery_Name());
    }

    @Override
    public Spannable getContentSummary(RCRedPackageMessage rcVibrationMessage) {
        if (rcVibrationMessage == null)
            return null;
        return new SpannableString(TextUtils.isEmpty(rcVibrationMessage.getContent()) ? "[红包]" : rcVibrationMessage.getContent());
    }

    @Override
    public void onItemClick(View view, int i, RCRedPackageMessage redPackageMessage, UIMessage uiMessage) {
        SendUser.sendUserId = uiMessage.getSenderUserId();
        SendUser.conversationType = uiMessage.getConversationType();
        SendUser.targetId = uiMessage.getTargetId();
        userInfo = uiMessage.getUserInfo();
        if (userInfo == null) {
            userInfo = RongUserInfoManager.getInstance().getUserInfo(uiMessage.getSenderUserId());
        }
        if (RongIMClient.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED)) {
            if (uiMessage.getConversationType().equals(Conversation.ConversationType.PRIVATE)) {
                currentConversationType = Conversation.ConversationType.PRIVATE;
                //单聊开红包
                if (SendUser.sendUserId.equals(CurrentUser.getUserId())) {
                    //自己打开自己发送的红包 - 查看详情
                    ChatRedDetailsActivity.start(view.getContext(), redPackageMessage.getBribery_ID(), true);
                } else {
                    //自己打开好友发的红包
                    isOpenRedPacket(view.getContext(), redPackageMessage.getBribery_ID(), redPackageMessage.getBribery_Message());
                }
            } else if (uiMessage.getConversationType().equals(Conversation.ConversationType.GROUP)) {
                currentConversationType = Conversation.ConversationType.GROUP;
                isOpenRedPacket(view.getContext(), redPackageMessage.getBribery_ID(), redPackageMessage.getBribery_Message());
            }
        } else {
            ToastUtil.showToast(RongContext.getInstance(), RongContext.getInstance().getString(R.string.net_error_l));
        }
    }

    private DisposableSubscriber subscriber;

    //是否已经打开过红包了
    private void isOpenRedPacket(Context context, String briberyId, String briberyMessage) {
        Map<String, Object> params = new HashMap<>();
        params.put("packet_id", briberyId);
        try {
            Flowable<ResultEntity<JsonObject>> flowable = RetrofitHelper.Companion.getApi().isTakeRedPacket(Encryption.INSTANCE.encryption(params));
            subscriber = flowable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(new DisposableSubscriber<ResultEntity<JsonObject>>() {
                        @Override
                        public void onNext(ResultEntity<JsonObject> resultEntity) {
                            LogUtil.d(resultEntity.toString());
                            if (resultEntity.getError() == HttpCode.EXCEPTION_CODE_1012 || resultEntity.getMessage().equals("未领取过该红包")) {
                                //未领取过该红包
                                if (currentConversationType == Conversation.ConversationType.PRIVATE) {
                                    showSingleRedPackageDialog(context, briberyId, userInfo, briberyMessage);
                                } else if (currentConversationType == Conversation.ConversationType.GROUP) {
                                    showGroupRedPackageDialog(context, briberyId, userInfo, briberyMessage);
                                }
                            } else if (resultEntity.getError() == HttpCode.EXCEPTION_CODE_1011 || resultEntity.getMessage().equals("已领取该红包")) {
                                //已经领取过红包
                                if (currentConversationType == Conversation.ConversationType.PRIVATE) {
                                    ChatRedDetailsActivity.start(context, briberyId, true);
                                } else if (currentConversationType == Conversation.ConversationType.GROUP) {
                                    MucRedDetailsActivity.start(context, briberyId, true);
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable t) {
                            ToastUtils.show(t.getMessage());
                        }

                        @Override
                        public void onComplete() {
                            LogUtil.d("onComplete");
                        }
                    });

        } catch (Exception e) {
            LogUtil.d(e.getMessage());
        }
    }

    private void showSingleRedPackageDialog(Context context, String bribery_ID, UserInfo userInfo, String messageContent) {
        mRedDialog = new RedDialog(context, () -> {
            ChatRedDetailsActivity.start(context, bribery_ID, false);
            mRedDialog.dismiss();
        }, userInfo, messageContent);
        mRedDialog.show();
    }

    private void showGroupRedPackageDialog(Context context, String bribery_ID, UserInfo userInfo, String messageContent) {
        mRedDialog = new RedDialog(context, () -> {
            MucRedDetailsActivity.start(context, bribery_ID, false);
            mRedDialog.dismiss();
        }, userInfo, messageContent);
        mRedDialog.show();
    }

    @Override
    public void onItemLongClick(View view, int position, RCRedPackageMessage rcVibrationMessage, UIMessage message) {
        super.onItemLongClick(view, position, rcVibrationMessage, message);
    }

    @Override
    public View newView(Context context, ViewGroup viewGroup) {
        View view = LayoutInflater.from(context).inflate(R.layout.m_bribery_item, (ViewGroup) null);
        RCRedPackageMessageProvider.ViewHolder viewHolder = new RCRedPackageMessageProvider.ViewHolder();
        viewHolder.layout = (RelativeLayout) view.findViewById(R.id.layout);
        viewHolder.tv_bri_mess = (TextView) view.findViewById(R.id.tv_bri_mess);
        viewHolder.tv_bri_target = (TextView) view.findViewById(R.id.tv_bri_target);
        viewHolder.tv_bri_name = (TextView) view.findViewById(R.id.tv_bri_name);
        viewHolder.bri_bg = (RelativeLayout) view.findViewById(R.id.bri_bg);
        view.setTag(viewHolder);
        return view;
    }

    private class ViewHolder {
        RelativeLayout layout;
        RelativeLayout bri_bg;
        TextView tv_bri_mess;
        TextView tv_bri_target;
        TextView tv_bri_name;

        ViewHolder() {
        }
    }

}