package com.ym.chat.fragment;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;

import androidx.annotation.Nullable;

import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.qcloud.tuicore.TUIConstants;
import com.tencent.qcloud.tuicore.TUICore;
import com.tencent.qcloud.tuicore.component.action.PopActionClickListener;
import com.tencent.qcloud.tuicore.component.action.PopDialogAdapter;
import com.tencent.qcloud.tuicore.component.action.PopMenuAction;
import com.tencent.qcloud.tuicore.component.interfaces.IUIKitCallback;
import com.tencent.qcloud.tuicore.util.ScreenUtil;
import com.tencent.qcloud.tuicore.util.ToastUtil;
import com.tencent.qcloud.tuikit.tuiconversation.bean.ConversationInfo;
import com.tencent.qcloud.tuikit.tuiconversation.presenter.ConversationPresenter;
import com.tencent.qcloud.tuikit.tuiconversation.ui.view.ConversationLayout;
import com.tencent.qcloud.tuikit.tuiconversation.ui.view.ConversationListLayout;
import com.ym.chat.R;
import com.ym.chat.contract.ChatContract;
import com.ym.chat.utils.TUIUtils;
import com.zxhl.cms.common.C2CChatBean;
import com.zxhl.cms.common.base.BaseFragment;
import com.zxhl.cms.net.ApiClient;
import com.zxhl.cms.net.RxSchedulers;
import com.zxhl.cms.net.SettingPreference;
import com.zxhl.cms.net.callback.BaseObserver;
import com.zxhl.cms.net.model.box.AppInEntity;
import com.zxhl.cms.net.model.chat.ChatMessageChargeOrNotEntity;
import com.zxhl.cms.net.model.chat.ChatStausEvent;
import com.zxhl.cms.net.model.chat.ChatUpMessageTemplateEntity;
import com.zxhl.cms.pay.StarCoinPayActivity;
import com.zxhl.cms.utils.ActivityManager;
import com.zxhl.cms.utils.AdCallback;
import com.zxhl.cms.utils.ChatCallback;
import com.zxhl.cms.utils.ChatMessageChargeUtils;
import com.zxhl.cms.utils.EventUtils;
import com.zxhl.cms.utils.JumpUtils;
import com.zxhl.cms.utils.Utils;
import com.zxhl.cms.widget.ChatDialogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by lidandan
 * Date : 2021/12/25
 * Description :
 */
public class ChatFragment extends BaseFragment implements ChatContract.View, V2TIMCallback {

    //    private ChatPresenter mPresenter = null;
    private String assistFlags = "";
    private String startIndex = "";
    private String timeStamp = "";
    private String topStartIndex = "";
    private String topTimeStamp = "";
    private ConversationLayout mConversationLayout;
    private ConversationPresenter mConversationPresenter;
    private ListView mConversationPopList;
    private PopupWindow mConversationPopWindow;
    private PopDialogAdapter mConversationPopAdapter;
    private List<PopMenuAction> mConversationPopActions = new ArrayList<>();
    private boolean isFirstLoad = false;

    private String dialogContent = "开启会员解锁无限发送消息权限";
    private String dialogTipContent = "星币解锁本次消息发送";

    @Override
    public int layoutID() {
        return R.layout.fragment_layout_chat;
    }

    @Override
    public void init(View view) {
//        mPresenter = new ChatPresenter(this);
//        mPresenter.getMessageList(assistFlags, startIndex, timeStamp, topStartIndex, topTimeStamp);
        view.findViewById(R.id.id_ll_guest).setOnClickListener(v -> {
            EventUtils.INSTANCE.onEvent("CheckedMyViewers", "查看访客");
            JumpUtils.VisitorJump();
        });
        view.findViewById(R.id.id_ll_system).setOnClickListener(v -> {
            JumpUtils.SystemMsgJump();
        });

        mConversationLayout = view.findViewById(R.id.conversation_layout);
        mConversationPresenter = new ConversationPresenter();
        mConversationPresenter.setConversationListener();
        mConversationLayout.setPresenter(mConversationPresenter);

        EventBus.getDefault().register(this);
    }

    private void initPopMenuAction() {
        // 设置长按conversation显示PopAction
        List<PopMenuAction> conversationPopActions = new ArrayList<PopMenuAction>();
        PopMenuAction action = new PopMenuAction();
        action.setActionName(getResources().getString(com.tencent.qcloud.tuikit.tuiconversation.R.string.chat_top));
        action.setActionClickListener(new PopActionClickListener() {
            @Override
            public void onActionClick(int index, Object data) {
                mConversationLayout.setConversationTop((ConversationInfo) data, new IUIKitCallback() {
                    @Override
                    public void onSuccess(Object data) {

                    }

                    @Override
                    public void onError(String module, int errCode, String errMsg) {
                        ToastUtil.toastLongMessage(module + ", Error code = " + errCode + ", desc = " + errMsg);
                    }
                });
            }
        });
        conversationPopActions.add(action);
        action = new PopMenuAction();
        action.setActionClickListener(new PopActionClickListener() {
            @Override
            public void onActionClick(int index, Object data) {
                mConversationLayout.deleteConversation((ConversationInfo) data);
            }
        });
        action.setActionName(getResources().getString(com.tencent.qcloud.tuikit.tuiconversation.R.string.chat_delete));
        conversationPopActions.add(action);

//        action = new PopMenuAction();
//        action.setActionName(getResources().getString(com.tencent.qcloud.tuikit.tuiconversation.R.string.clear_conversation_message));
//        action.setActionClickListener(new PopActionClickListener() {
//            @Override
//            public void onActionClick(int index, Object data) {
//                mConversationLayout.clearConversationMessage((ConversationInfo) data);
//            }
//        });
//        conversationPopActions.add(action);

        mConversationPopActions.clear();
        mConversationPopActions.addAll(conversationPopActions);
    }

    /**
     * 长按会话item弹框
     *
     * @param conversationInfo 会话数据对象
     */
    private void showItemPopMenu(View view, final ConversationInfo conversationInfo) {
        if (mConversationPopActions == null || mConversationPopActions.size() == 0) {
            return;
        }
        View itemPop = LayoutInflater.from(getActivity()).inflate(com.tencent.qcloud.tuikit.tuiconversation.R.layout.conversation_pop_menu_layout, null);
        mConversationPopList = itemPop.findViewById(com.tencent.qcloud.tuikit.tuiconversation.R.id.pop_menu_list);
        mConversationPopList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PopMenuAction action = mConversationPopActions.get(position);
                if (action.getActionClickListener() != null) {
                    action.getActionClickListener().onActionClick(position, conversationInfo);
                }
                mConversationPopWindow.dismiss();
                restoreConversationItemBackground();
            }
        });

        for (int i = 0; i < mConversationPopActions.size(); i++) {
            PopMenuAction action = mConversationPopActions.get(i);
            if (conversationInfo.isTop()) {
                if (action.getActionName().equals(getResources().getString(com.tencent.qcloud.tuikit.tuiconversation.R.string.chat_top))) {
                    action.setActionName(getResources().getString(com.tencent.qcloud.tuikit.tuiconversation.R.string.quit_chat_top));
                }
            } else {
                if (action.getActionName().equals(getResources().getString(com.tencent.qcloud.tuikit.tuiconversation.R.string.quit_chat_top))) {
                    action.setActionName(getResources().getString(com.tencent.qcloud.tuikit.tuiconversation.R.string.chat_top));
                }

            }
        }
        mConversationPopAdapter = new PopDialogAdapter();
        mConversationPopList.setAdapter(mConversationPopAdapter);
        mConversationPopAdapter.setDataSource(mConversationPopActions);
        mConversationPopWindow = new PopupWindow(itemPop, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        mConversationPopWindow.setBackgroundDrawable(new ColorDrawable());
        mConversationPopWindow.setOutsideTouchable(true);
        mConversationPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                restoreConversationItemBackground();
            }
        });
        int x = view.getWidth() / 2;
        int y = -view.getHeight() / 3;
        int popHeight = ScreenUtil.dip2px(45) * 3;
        if (y + popHeight + view.getY() + view.getHeight() > mConversationLayout.getBottom()) {
            y = y - popHeight;
        }
        mConversationPopWindow.showAsDropDown(view, x, y, Gravity.TOP | Gravity.START);
    }

    public void restoreConversationItemBackground() {
        if (mConversationLayout.getConversationList().getAdapter() != null &&
                mConversationLayout.getConversationList().getAdapter().isClick()) {
            mConversationLayout.getConversationList().getAdapter().setClick(false);
            mConversationLayout.getConversationList().getAdapter().notifyItemChanged(mConversationLayout.getConversationList().getAdapter().getCurrentPosition());
        }
    }

    @Override
    public void setData() {
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isFirstLoad) {
            login(SettingPreference.getUserInfoData().uid + "");
        }
        updateIMSettingInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateIMSettingInfo();
    }

    @Override
    public void onSuccess() {
        isFirstLoad = true;
        mConversationLayout.initDefault();
        // 通过API设置ConversataonLayout各种属性的样例，开发者可以打开注释，体验效果
//        ConversationLayoutHelper.customizeConversation(mConversationLayout);
        mConversationLayout.getConversationList().setOnItemClickListener(new ConversationListLayout.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, ConversationInfo conversationInfo) {
                startChatActivity(conversationInfo);
            }
        });
        mConversationLayout.getConversationList().setOnItemLongClickListener(new ConversationListLayout.OnItemLongClickListener() {
            @Override
            public void OnItemLongClick(View view, int position, ConversationInfo conversationInfo) {
                showItemPopMenu(view, conversationInfo);
            }
        });
        initPopMenuAction();
        restoreConversationItemBackground();
    }

    private void startChatActivity(ConversationInfo conversationInfo) {
        Bundle param = new Bundle();
        param.putInt(TUIConstants.TUIChat.CHAT_TYPE, conversationInfo.isGroup() ? V2TIMConversation.V2TIM_GROUP : V2TIMConversation.V2TIM_C2C);
        param.putString(TUIConstants.TUIChat.CHAT_ID, conversationInfo.getId());
        param.putString(TUIConstants.TUIChat.CHAT_NAME, conversationInfo.getTitle());
        if (conversationInfo.getDraft() != null) {
            param.putString(TUIConstants.TUIChat.DRAFT_TEXT, conversationInfo.getDraft().getDraftText());
            param.putLong(TUIConstants.TUIChat.DRAFT_TIME, conversationInfo.getDraft().getDraftTime());
        }
        param.putBoolean(TUIConstants.TUIChat.IS_TOP_CHAT, conversationInfo.isTop());

        if (conversationInfo.isGroup()) {
            param.putString(TUIConstants.TUIChat.FACE_URL, conversationInfo.getIconPath());
            param.putString(TUIConstants.TUIChat.GROUP_TYPE, conversationInfo.getGroupType());
        }
        if (conversationInfo.isGroup()) {
            TUICore.startActivity(TUIConstants.TUIChat.GROUP_CHAT_ACTIVITY_NAME, param);
        } else {
            param.putString("conversationHeadIconUrl", conversationInfo.getIconUrlList().get(0).toString());
            TUICore.startActivity(TUIConstants.TUIChat.C2C_CHAT_ACTIVITY_NAME, param);
        }
    }

    @Override
    public void onError(int code, String errorMsg) {

    }

    private void login(String userId) {
        // 获取userSig函数
        if (V2TIMManager.getInstance().getLoginStatus() == V2TIMManager.V2TIM_STATUS_LOGINING || V2TIMManager.getInstance().getLoginStatus() == V2TIMManager.V2TIM_STATUS_LOGINED) {
            onSuccess();
            return;
        }
        TUIUtils.login(userId, SettingPreference.getImSignInfo(), this);
    }

    private void updateIMSettingInfo() {
        ApiClient.INSTANCE.getHomeApi().getAppInfo()
                .compose(RxSchedulers.observableIO2Main())
                .subscribe(new BaseObserver<AppInEntity>() {

                    @Override
                    public void onSuccess(AppInEntity result) {
                        if (result != null) {
                            SettingPreference.setImReadShow(result.getIm_read_show());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String code, String errorMsg) {
                        SettingPreference.setImReadShow(0);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void startC2CChat(C2CChatBean c2CChatBean) {
        //继续聊天
        if (c2CChatBean.type == 1) {
            Bundle param = new Bundle();
            param.putInt(TUIConstants.TUIChat.CHAT_TYPE, V2TIMConversation.V2TIM_C2C);
            param.putString(TUIConstants.TUIChat.CHAT_ID, c2CChatBean.chatId);
            param.putString(TUIConstants.TUIChat.CHAT_NAME, c2CChatBean.chatName);
            param.putBoolean(TUIConstants.TUIChat.IS_TOP_CHAT, false);
            TUICore.startActivity(TUIConstants.TUIChat.C2C_CHAT_ACTIVITY_NAME, param);
        } else if (c2CChatBean.type == 0) {
            //搭讪
            ChatMessageChargeUtils.INSTANCE.getChatMessageChargeOrNot(ChatMessageChargeUtils.MESSAGE_NORMAL_TEXT + "", "", new ChatCallback<ChatMessageChargeOrNotEntity>() {
                @Override
                public void onResult(@Nullable ChatMessageChargeOrNotEntity result) {
                    //不能发送消息
                    if (!isSendMessage(result)) {
                        chatImDEduction(result, dialogContent, dialogTipContent, new AdCallback<String>() {
                            @Override
                            public void onResult(int code, String result) {
                                sendMessage(c2CChatBean);
                            }
                        });
                        return;
                    }
                    sendMessage(c2CChatBean);
                }

                @Override
                public void onError(@Nullable String code, @Nullable String errorMsg) {
                    if (TextUtils.isEmpty(errorMsg)) {
                        return;
                    }
                    Utils.showToast(getContext(), errorMsg);
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 是否可以正常发送消息
     *
     * @param entity
     * @return false 不能发送消息 true 可以正常发送消息
     */
    public static boolean isSendMessage(ChatMessageChargeOrNotEntity entity) {
        //免费发送消息
        if (entity.charge <= 0) {
            return true;
        }
        if (SettingPreference.getUserInfoData() == null) {
            return false;
        }
//        if (entity.config == null) {
//            return false;
//        }
        //永久会员
        if (SettingPreference.getUserInfoData().memberType == 2) {
            return true;
        }
        //非会员
        if (SettingPreference.getUserInfoData().memberType == 0) {
//            if (entity.config.freeTimes == -1 || entity.config.freeTimes > 0) {
//                return true;
//            }
            return false;
        }
        //时长会员
        if (SettingPreference.getUserInfoData().memberType == 1) {
//            if (entity.config.memberFreeTimes == -1 || entity.config.memberFreeTimes > 0) {
//                return true;
//            }
//            return false;
            return true;
        }
        return false;
    }

    /**
     * 扣费方法
     */
    public void chatImDEduction(ChatMessageChargeOrNotEntity result, String content, String tipContent, AdCallback<String> callback) {
        //非会员的时候，星币小于所发消息所需，则进行弹窗
        if (SettingPreference.getUserInfoData() != null && SettingPreference.getUserInfoData().memberType == 0
                && SettingPreference.getUserInfoData().starBalance < result.charge) {
            ChatDialogUtils.showMemberChargeTip(ActivityManager.getInstance().getTopActivity(), result, content, tipContent, new ChatDialogUtils.ChatDialogCallBackParams() {
                @Override
                public void confirm(int type) {
                    //兑换
                    if (type == 0) {
                        ChatDialogUtils.showMemberTrip(ActivityManager.getInstance().getTopActivity(), new ChatDialogUtils.ChatDialogCallBack() {
                            @Override
                            public void confirm() {
                                Intent intent = new Intent(getContext(), StarCoinPayActivity.class);
                                ActivityManager.getInstance().getTopActivity().startActivity(intent);
                            }

                            @Override
                            public void cancel() {

                            }
                        });
                    } else {
                        //充值会员
                        Intent intent = new Intent(getContext(), StarCoinPayActivity.class);
                        ActivityManager.getInstance().getTopActivity().startActivity(intent);
                    }
                }

                @Override
                public void cancel() {

                }
            });
            return;
        }

        ChatMessageChargeUtils.INSTANCE.chatImDEduction("", ChatMessageChargeUtils.MESSAGE_NORMAL_TEXT + "", new ChatCallback<String>() {
            @Override
            public void onResult(@Nullable String result) {
                callback.onResult(0, result);
            }

            @Override
            public void onError(@Nullable String code, @Nullable String errorMsg) {
                ChatStausEvent chatStausEvent = new ChatStausEvent();
                chatStausEvent.setChatstatus("0");
                EventBus.getDefault().post(chatStausEvent);
                //星币余额不足,弹窗dialog
                if (!TextUtils.isEmpty(code) && code.equals("105")) {

                    ChatDialogUtils.showMemberTrip(ActivityManager.getInstance().getTopActivity(), new ChatDialogUtils.ChatDialogCallBack() {
                        @Override
                        public void confirm() {
                            Intent intent = new Intent(getContext(), StarCoinPayActivity.class);
                            ActivityManager.getInstance().getTopActivity().startActivity(intent);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                }
                if (TextUtils.isEmpty(errorMsg)) {
                    return;
                }
                Utils.showToast(getContext(), errorMsg);
            }
        });
    }

    private void sendMessage(C2CChatBean c2CChatBean) {
        ApiClient.INSTANCE.getChatApi().getChatUpMessageTemplate().compose(RxSchedulers.observableIO2Main()).subscribe(new BaseObserver<ChatUpMessageTemplateEntity>() {

            @Override
            public void onSuccess(ChatUpMessageTemplateEntity result) {
                if (result != null && result.template != null && result.template.size() > 0) {
                    List<String> messageTemplateList = result.template;
                    Random random = new Random();
                    int index = random.nextInt(messageTemplateList.size());
                    String message = "";
                    try {
                        message = messageTemplateList.get(index - 1);
                    } catch (Exception e) {
                        message = messageTemplateList.get(0);
                    }
                    Bundle param = new Bundle();
                    param.putInt(TUIConstants.TUIChat.CHAT_TYPE, V2TIMConversation.V2TIM_C2C);
                    param.putString(TUIConstants.TUIChat.CHAT_ID, c2CChatBean.chatId);
                    param.putString(TUIConstants.TUIChat.CHAT_NAME, c2CChatBean.chatName);
                    param.putBoolean(TUIConstants.TUIChat.IS_TOP_CHAT, false);
                    param.putString(TUIConstants.TUIChat.MESSAGE_CONTENT, message);
                    TUICore.startActivity(TUIConstants.TUIChat.C2C_CHAT_ACTIVITY_NAME, param);

                    ChatStausEvent chatStausEvent = new ChatStausEvent();
                    chatStausEvent.setChatstatus("1");
                    EventBus.getDefault().post(chatStausEvent);
                }
            }

            @Override
            public void onFailure(Throwable e, String code, String errorMsg) {
                ChatStausEvent chatStausEvent = new ChatStausEvent();
                chatStausEvent.setChatstatus("0");
                EventBus.getDefault().post(chatStausEvent);
                if (!TextUtils.isEmpty(errorMsg)) {
                    Utils.showToast(getContext(), errorMsg);
                }
            }
        });
    }
}
