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

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
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 com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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.MessageAdapter;
import com.tofly.ghrq_route.common.ui.adapter.MessageSendAdapter;
import com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool;
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.InMessageBean;
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.Dialogs;
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;
import butterknife.OnClick;

/**
 * Created by Amu on 2017/2/8.
 */

public class UiMessage extends BaseUi {
    @BindView(R.id.layout_app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.layout_collapse_toolbar)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.textview_unread_count)
    TextView toolbarTextUnreadCount;
    @BindView(R.id.layout_message_sended)
    RelativeLayout layoutMsgSended;
    @BindView(R.id.textview_empty)
    TextView textEmptyView;
    @BindView(R.id.recycler_view)
    SwipeMenuRecyclerView recyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.floatbtn_new_message)
    FloatingActionButton floatBtnNewMessage;
    @BindView(R.id.tv_unread)
    TextView tvUnread;
    @BindView(R.id.tv_read)
    TextView tvRead;
    @BindView(R.id.v_unread)
    View vUnread;
    @BindView(R.id.v_read)
    View vRead;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.v_send)
    View vSend;

    private ActionMode mActionMode;
    private ActionMode.Callback mCallback;

    //private final String TAG = UiMessage.class.getSimpleName();
    private UserBean mUser;
    private MessageController messageController;
    private boolean mbIsRefreshing = false;
    private List<InMessageBean> recvMsgList, dataList;
    private MessageAdapter messageAdapter;
    private String isread = "0";
    private List<Integer> selectedPos1;
    private int count = 0;
    private MessageSendAdapter messageSendAdapter;
    private List<OutMessageBean> sendMsgList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_message);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
        EventBusUtil.register(this);
    }

    @Subscribe
    public void onMessageEvent(DeviceInfoTool.DeviceInfoToolEvent event) {
        if (event.message.equals(DeviceInfoTool.DEVICEINFO_UNREAD_MESSAGE)) {
            List<InMessageBean> messageList = (List<InMessageBean>) event.arg;
            int unreadCount = messageList.size();
            if (unreadCount > 0) {
                swipeRefreshLayout.setRefreshing(true);
                loadMessage(null);
            }
        }
    }

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

        initAppBar();
    }

    private void initAppBar() {
        // 4.4及以上版本开启
        setTranslucentStatus();
        setToolbarPadding();
        setLightStatusBar();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            collapsingToolbarLayout.setTitle(getString(R.string.darwer_menu_message));
        });
    }

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

    private void initListener() {
        swipeRefreshLayout.setOnRefreshListener(() -> {
            if (mbIsRefreshing) {
            } else {
                loadMessage(null);
                loadSendMessage(null);
            }
        });
        if (messageAdapter != null) {
            messageAdapter.setItemOpenListener((message, position) -> {
                selectedPos1 = new ArrayList<>();
                selectedPos1.add(position);
            });

            messageAdapter.setItemRemoveListener((message, position) -> {
                List<Integer> selectedPos = new ArrayList<>();
                selectedPos.add(position);
                deleteRecvMessage(selectedPos);
            });

            messageAdapter.setItemClickListener(new MessageAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (mActionMode != null) {
                        toggleSelection(position);
                    } else {
                        InMessageBean messageBean = messageAdapter.getItem(position);
                        if (messageBean != null) {
                            Intent intent = new Intent();
                            intent.putExtra("messageId", messageBean.getMessageId());
                            intent.putExtra("name", messageBean.getCreateUserName());
                            intent.putExtra("time", messageBean.getCreateDate());
                            intent.putExtra("createUserId", messageBean.getCreateUser());
                            intent.putExtra("type", messageBean.getType());
                            intent.putExtra(InMessageBean.MESSAGE_MODULE_KEY, messageBean.getModule());
                            intent.setClass(UiMessage.this, UiMessageDetail.class);
                            startActivityForResult(intent, 0x001);
                        }
                    }
                }

                @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());
                            deleteRecvMessage(selectedIds);
                            mActionMode.finish();
                            break;
/*                        case R.id.action_total_set:
                            selectedPos1 = new ArrayList<>();
                            if (count % 2 == 0) {
                                for (InMessageBean data : dataList) {
                                    selectedPos1.add(data.getMessageId());
                                }
                            }
                            mActionMode.setTitle("已选中" + selectedPos1.size() + "个");
                            messageAdapter.setSelected(selectedPos1, count);
                            count++;
                            break;*/
                        case R.id.action_read:
                            setMessageReaded();
                            mActionMode.finish();
                            break;
                    }
                    return false;
                }

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

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

                @Override
                public boolean onItemLongClick(View view, int 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);
                }
            };
        }
    }

    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(messageSendAdapter.getItem(i).getId()).append(",");
                } else {
                    ids.append(messageSendAdapter.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
    public void onBackPressed() {
        gotoSystemHome();
    }

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

    private void loadMessage(String content) {
        mbIsRefreshing = true;
        if (messageController == null)
            messageController = new MessageController(this);
        int pageindex = 1;
        int pagesize = C.DEFAULT_MAX_LOAD_PAGESIZE;
        messageController.getRecvMsgList1(mUser.getToken(), -1, pageindex, pagesize, content, new MessageCallBack() {
            @Override
            public void onGetRecvMsgList(boolean isSuccess, int errorCode, String errMsg, List<InMessageBean> messageList, int total) {
                super.onGetRecvMsgList(isSuccess, errorCode, errMsg, messageList, total);
                swipeRefreshLayout.postDelayed(() -> {
                    swipeRefreshLayout.setRefreshing(false);
                    mbIsRefreshing = false;
                }, 500);
                if (isSuccess && messageList != null) {
                    recvMsgList.clear();
                    recvMsgList = messageList;
                    dataList = new ArrayList<>();
                    for (InMessageBean inMessageBean : recvMsgList) {
                        if (inMessageBean.getFlag().equals(isread)) {
                            dataList.add(inMessageBean);
                        }
                    }
                    messageAdapter.setData(dataList);
                    if (messageList.size() > 0) {
                        recyclerView.setVisibility(View.VISIBLE);
                        textEmptyView.setVisibility(View.GONE);
                    }
                } else {
                    toast(errMsg);
                }
            }
        });
    }

    private void loadSendMessage(String searchContent) {
        mbIsRefreshing = true;
        int pageindex = 1;
        int pagesize = C.DEFAULT_MAX_LOAD_PAGESIZE;
        if (messageController == null) {
            messageController = new MessageController(this);
        }
        messageController.getSendMsgList(mUser.getToken(), pageindex, pagesize, searchContent, 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(() -> {
                    swipeRefreshLayout.setRefreshing(false);
                    mbIsRefreshing = false;
                }, 500);
                recyclerView.setVisibility(View.GONE);
                textEmptyView.setVisibility(View.VISIBLE);
                if (isSuccess && messageList != null) {
                    sendMsgList.clear();
                    sendMsgList = messageList;
                    messageSendAdapter.setData(sendMsgList);
                    if (messageList.size() > 0) {
                        recyclerView.setVisibility(View.VISIBLE);
                        textEmptyView.setVisibility(View.GONE);
                    }
                } else {
                    toast(errMsg);
                }
            }
        });
    }

    private void setMessageReaded() {
        if (selectedPos1 != null && selectedPos1.size() > 0) {
            if (messageController == null)
                messageController = new MessageController(this);
            StringBuffer ids = new StringBuffer();
            for (int i = 0; i < selectedPos1.size(); i++) {
                if (i < selectedPos1.size() - 1) {
                    ids.append(messageAdapter.getItem(i).getMessageId()).append(",");
                } else {
                    ids.append(messageAdapter.getItem(i).getMessageId());
                }
            }
            messageController.setRecvMsgReaded(mUser.getToken(), ids.toString(), new MessageCallBack() {
                @Override
                public void onSetRecvMsgReaded(boolean isSuccess, int errorCode, String errMsg) {
                    super.onSetRecvMsgReaded(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        loadMessage(null);
                    } else {
                        toast(errMsg);
                    }
                }
            });
        }
    }

    private void deleteRecvMessage(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<>();
            StringBuffer ids = new StringBuffer();
            for (int i = 0; i < selectedPos.size(); i++) {
                if (i < selectedPos.size() - 1) {
                    ids.append(messageAdapter.getItem(selectedPos.get(i)).getMessageId()).append(",");
                } else {
                    ids.append(messageAdapter.getItem(selectedPos.get(i)).getMessageId());
                }
            }
            messageController.deleteRecvMsg(mUser.getToken(), ids.toString(), new MessageCallBack() {
                @Override
                public void onDeleteRecvMsg(boolean isSuccess, int errorCode, String errMsg) {
                    super.onDeleteRecvMsg(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        messageAdapter.removeSelectedItems(selectedPos);
                        loadMessage(null);
                    } else {
                        toast(errMsg);
                    }
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_message_outbox, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_new: {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setClass(this, UIMessageNew.class);
                startActivityForResult(intent, 0x004);
            }
            break;
            case R.id.action_search:
                Dialogs.show(this, editText -> {
                    if (!TextUtils.isEmpty(editText)) {
                        if (isread.equals("2")) {
                            sendMsgList.clear();
                            recyclerView.removeAllViews();
                            recyclerView.setAdapter(messageSendAdapter);
                            loadSendMessage(editText);
                        } else {
                            recvMsgList.clear();
                            recyclerView.removeAllViews();
                            recyclerView.setAdapter(messageAdapter);
                            loadMessage(editText);
                        }
                    }
                });
                break;
//            case R.id.action_outbox: {
//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                intent.setClass(this, UiMessageSend.class);
//                startActivity(intent);
//            }
//            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({R.id.layout_message_sended, R.id.floatbtn_new_message, R.id.ll_unread, R.id.ll_read, R.id.ll_send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_unread:
                recyclerView.removeAllViews();
                recyclerView.setAdapter(messageAdapter);
                isread = "0";
                tvUnread.setTextColor(getResources().getColor(R.color.white));
                tvUnread.setTextSize(19);
                vUnread.setVisibility(View.VISIBLE);
                vRead.setVisibility(View.GONE);
                vSend.setVisibility(View.GONE);
                tvRead.setTextColor(Color.parseColor("#a6c8ff"));
                tvRead.setTextSize(17);
                tvSend.setTextSize(17);
                tvSend.setTextColor(Color.parseColor("#a6c8ff"));
                if (recvMsgList != null && recvMsgList.size() > 0) {
                    dataList = new ArrayList<>();
                    for (InMessageBean inMessageBean : recvMsgList) {
                        if (inMessageBean.getFlag().equals(isread)) {
                            dataList.add(inMessageBean);
                        }
                    }
                    messageAdapter.setData(dataList);
                }
                break;
            case R.id.ll_read:
                recyclerView.removeAllViews();
                recyclerView.setAdapter(messageAdapter);
                isread = "1";
                vRead.setVisibility(View.VISIBLE);
                vUnread.setVisibility(View.GONE);
                vSend.setVisibility(View.GONE);
                tvRead.setTextColor(getResources().getColor(R.color.white));
                tvRead.setTextSize(19);
                tvUnread.setTextColor(Color.parseColor("#a6c8ff"));
                tvUnread.setTextSize(17);
                tvSend.setTextSize(17);
                tvSend.setTextColor(Color.parseColor("#a6c8ff"));
                dataList = new ArrayList<>();
                if (recvMsgList != null && recvMsgList.size() > 0) {
                    for (InMessageBean inMessageBean : recvMsgList) {
                        if (inMessageBean.getFlag().equals(isread)) {
                            dataList.add(inMessageBean);
                        }
                    }
                    messageAdapter.setData(dataList);
                }
                break;
            case R.id.ll_send:
                isread = "2";
                recyclerView.removeAllViews();
                recyclerView.setAdapter(messageSendAdapter);
                vSend.setVisibility(View.VISIBLE);
                vUnread.setVisibility(View.GONE);
                vRead.setVisibility(View.GONE);
                tvSend.setTextColor(getResources().getColor(R.color.white));
                tvSend.setTextSize(19);
                tvUnread.setTextColor(Color.parseColor("#a6c8ff"));
                tvUnread.setTextSize(17);
                tvRead.setTextSize(17);
                tvRead.setTextColor(Color.parseColor("#a6c8ff"));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0x001:
                loadMessage(null);
                break;
            case 0x003:
                loadSendMessage(null);
                break;
            case 0x004:
                loadMessage(null);
                loadSendMessage(null);
                break;
        }
    }

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