package com.tofly.ghrq_route.common.ui.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.common.ui.adapter.MessageSendAdapter;
import com.tofly.ghrq_route.module.message.controller.MessageCallBack;
import com.tofly.ghrq_route.module.message.controller.MessageController;
import com.tofly.ghrq_route.module.message.domain.OutMessageBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tubb.smrv.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Amu on 2017/2/8.
 * 已发消息
 */

public class UiMessageSend extends BaseUi {

    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.textview_unread_count)
    TextView toolbarTextUnreadCount;
    @BindView(R.id.textview_empty)
    TextView textEmptyView;
    @BindView(R.id.recycler_view)
    SwipeMenuRecyclerView recyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;

    private ActionMode mActionMode;
    private ActionMode.Callback mCallback;

    private final String TAG = UiMessageSend.class.getSimpleName();
    private UserBean mUser;
    private MessageController messageController;
    private boolean mbIsRefreshing = false;
    private List<OutMessageBean> sendMsgList;
    private MessageSendAdapter messageAdapter;
    private int pageindex = 1;
    private final int pagesize = C.DEFAULT_MAX_LOAD_PAGESIZE;

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

        setContentView(R.layout.ui_message_send);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();

        EventBusUtil.register(this);
    }

    private void initView() {
        toolbarTextUnreadCount.setVisibility(View.GONE);
    }

    private void initData() {
        mUser = BaseApp.getInstance().getLoginUser();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        sendMsgList = new ArrayList<>();
        messageAdapter = new MessageSendAdapter(this, sendMsgList);
        recyclerView.setAdapter(messageAdapter);
        swipeRefreshLayout.setRefreshing(true);
        loadMessage();
    }

    private void initListener() {
        swipeRefreshLayout.setOnRefreshListener(() -> {
            if (mbIsRefreshing) {
            } else {
                loadMessage();
            }
        });
        if (messageAdapter != null) {
//            messageAdapter.setItemOpenListener(new MessageSendAdapter.OnItemOpenListener() {
//                @Override
//                public void onItemOpened(OutMessageBean message, int position) {
//                }
//            });
//
//            messageAdapter.setItemRemoveListener(new MessageSendAdapter.OnItemRemoveListener() {
//                @Override
//                public void onItemRemoved(OutMessageBean message, int position) {
//                    List<Integer> selectedPos = new ArrayList<Integer>();
//                    selectedPos.add(position);
//                    deleteSendMessage(selectedPos);
//                }
//            });

            messageAdapter.setItemClickListener(new MessageSendAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (mActionMode != null) {
                        toggleSelection(position);
                    } else {
                        OutMessageBean messageBean = messageAdapter.getItem(position);
                        Intent intent = new Intent();
                        intent.putExtra("messageId", messageBean.getId());
                        intent.putExtra("name", messageBean.getCreateUserName());
                        intent.putExtra("time", messageBean.getCreateDate());
                        if (messageBean.getReceipt().size() > 0) {
                            StringBuilder stringBuilder1 = new StringBuilder();
                            StringBuilder stringBuilder2 = new StringBuilder();
                            List<OutMessageBean.Receipt> dataList1 = new ArrayList<>();
                            List<OutMessageBean.Receipt> dataList2 = new ArrayList<>();
                            for (OutMessageBean.Receipt data : messageBean.getReceipt()) {
                                if (data.getFlag().equals("0")) {
                                    dataList1.add(data);
                                } else {
                                    dataList2.add(data);
                                }
                            }
                            if (dataList1.size() > 0) {
                                for (int i = 0; i < dataList1.size(); i++) {
                                    if (!dataList1.get(i).getRecipient().equals(mUser.getUserid())) {
                                        if (i == dataList1.size() - 1) {
                                            stringBuilder1.append(dataList1.get(i).getRecipientName());
                                        } else {
                                            stringBuilder1.append(dataList1.get(i).getRecipientName()).append(",");
                                        }
                                    }
                                }
                                intent.putExtra("unread", stringBuilder1.toString());
                            }
                            stringBuilder2.append(mUser.getRealName());
                            if (dataList2.size() > 0) {
                                for (int i = 0; i < dataList2.size(); i++) {
                                    if (!dataList2.get(i).getRecipient().equals(mUser.getUserid())) {
                                        stringBuilder2.append(",").append(dataList2.get(i).getRecipientName());
                                    }
                                }
                            }
                            intent.putExtra("read", stringBuilder2.toString());
                        }
                        intent.setClass(UiMessageSend.this, UiMessageSDetail.class);
                        startActivityForResult(intent, 0x003);
                    }
                }

                @Override
                public boolean onItemLongClick(View view, int position) {
//                    if (mActionMode == null) {
//                        mActionMode = startSupportActionMode(mCallback);
//                        messageAdapter.enableAllSwipable(false);
//                        swipeRefreshLayout.setEnabled(false);
//                    }
//                    toggleSelection(position);
                    return true;
                }
            });

            mCallback = new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    getMenuInflater().inflate(R.menu.menu_message_remove, menu);
                    return true;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.action_remove:
                            List<Integer> selectedIds = new ArrayList<>(messageAdapter.getSelectedPositionSet());
                            deleteSendMessage(selectedIds);
                            mActionMode.finish();
                            return true;
                    }
                    return false;
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {
                    mActionMode = null;
                    messageAdapter.cancelSelected();
                    swipeRefreshLayout.setEnabled(true);
                }
            };
        }
    }

    @Subscribe
    public void onMessageEvent(UiMessageDetail.MessageDetailEvent event) {
        if (event.message.equals(UiMessageDetail.OUT_MESSAGE_DETAIL_REMOVED)) {
            swipeRefreshLayout.setRefreshing(true);
            loadMessage();
        }
    }

    private void toggleSelection(int position) {
        // 根据position ，用Adapter更新Item选中状态和背景色
        messageAdapter.toggleSelection(position);
        // 更新 ActionMode 上的计数
        int size = messageAdapter.getSelectedPositionSet().size();
        mActionMode.setTitle("已选中" + String.valueOf(size) + "个");
    }

    private void loadMessage() {
        mbIsRefreshing = true;
        if (messageController == null)
            messageController = new MessageController(this);
        messageController.getSendMsgList(mUser.getToken(), pageindex, pagesize, null, new MessageCallBack() {
            @Override
            public void onGetSendMsgList(boolean isSuccess, int errorCode, String errMsg, List<OutMessageBean> messageList, int total) {
                super.onGetSendMsgList(isSuccess, errorCode, errMsg, messageList, total);
                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                        mbIsRefreshing = false;
                    }
                }, 500);
                recyclerView.setVisibility(View.GONE);
                textEmptyView.setVisibility(View.VISIBLE);
                if (isSuccess && messageList != null) {
                    sendMsgList = messageList;
                    messageAdapter.setData(sendMsgList);
                    if (messageList.size() > 0) {
                        recyclerView.setVisibility(View.VISIBLE);
                        textEmptyView.setVisibility(View.GONE);
                    }
                } else {
                    toast(errMsg);
                }
            }
        });
    }

    private void deleteSendMessage(final List<Integer> selectedPos) {
        if (selectedPos != null && selectedPos.size() > 0) {
            String strUploading = getString(R.string.message_message_deleting);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            if (messageController == null)
                messageController = new MessageController(this);
            // List<MessageID> ids = new ArrayList<MessageID>();
            StringBuffer ids = new StringBuffer();
            for (int i = 0; i < selectedPos.size(); i++) {
                if (i < selectedPos.size() - 1) {
                    ids.append(messageAdapter.getItem(i).getId()).append(",");
                } else {
                    ids.append(messageAdapter.getItem(i).getId());
                }
            }
            messageController.deleteSendMsg(mUser.getToken(), ids.toString(), new MessageCallBack() {
                @Override
                public void onDeleteSendMsg(boolean isSuccess, int errorCode, String errMsg) {
                    super.onDeleteSendMsg(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        messageAdapter.removeSelectedItems(selectedPos);
                    } else {
                        toast(errMsg);
                    }
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x003) {
            loadMessage();
        }
    }

    @Override
    protected void onDestroy() {
        EventBusUtil.unregister(this);
        BaseApp.cancelAllRequest(getClass().getName());
        super.onDestroy();
    }
}
