package com.cooleshow.teacher.ui.message;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.cooleshow.base.bean.RouteBean;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.constanst.RouteConstants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.GsonUtils;
import com.cooleshow.base.utils.JumpUtils;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MessageBoxAdapter;
import com.cooleshow.teacher.bean.CountOfUnreadBean;
import com.cooleshow.teacher.bean.SystemMessageBean;
import com.cooleshow.teacher.contract.MessageBoxContract;
import com.cooleshow.teacher.databinding.ActivityMessageBoxBinding;
import com.cooleshow.teacher.presenter.message.MessageBoxPresenter;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

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

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/5/24 11:14
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MessageCenter.TEACHER_MESSAGE_MESSAGEBOX)
public class MessageBoxActivity extends BaseMVPActivity<ActivityMessageBoxBinding, MessageBoxPresenter> implements MessageBoxContract.MessageBoxView, View.OnClickListener {
    //SYSTEM：系统消息 COURSE:课程信息 NOTICE:公告
    private String group = "";

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cl_all:
                if (group.equals("")) {
                    break;
                }
                group = "";
                defaultTextColor();
                viewBinding.tvAll.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
                currentPage = 1;
                queryList(true);
                break;
            case R.id.cl_course:
                if (group.equals("COURSE")) {
                    break;
                }
                group = "COURSE";
                defaultTextColor();
                viewBinding.tvCourse.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
                currentPage = 1;
                queryList(true);
                break;
            case R.id.cl_system:
                if (group.equals("SYSTEM")) {
                    break;
                }
                group = "SYSTEM";
                defaultTextColor();
                viewBinding.tvSystem.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
                currentPage = 1;
                queryList(true);
                break;
            case R.id.tv_right:
            case R.id.tv_right_text:
                presenter.batchSetRead();
                break;
        }
    }

    private void defaultTextColor() {
        viewBinding.tvAll.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
        viewBinding.tvCourse.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
        viewBinding.tvSystem.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }

    private MessageBoxAdapter messageBoxAdapter;

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "消息盒子");
        viewBinding.clAll.setOnClickListener(this);
        viewBinding.clCourse.setOnClickListener(this);
        viewBinding.clSystem.setOnClickListener(this);
        viewBinding.tvAll.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
        viewBinding.toolbarInclude.tvRightText.setVisibility(View.VISIBLE);
        viewBinding.toolbarInclude.tvRightText.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_999999));
        viewBinding.toolbarInclude.tvRightText.setTextSize(11);
        viewBinding.toolbarInclude.tvRightText.setText("全部已读");
        viewBinding.toolbarInclude.tvRightText.setOnClickListener(this);
        viewBinding.toolbarInclude.tvRight.setVisibility(View.VISIBLE);
        viewBinding.toolbarInclude.tvRight.setBackgroundResource(R.drawable.icon_message_read_all);
        viewBinding.toolbarInclude.tvRight.setOnClickListener(this);
        RecyclerView rvAddress = viewBinding.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvAddress.setLayoutManager(manager);
        messageBoxAdapter = new MessageBoxAdapter();
        LayoutInflater inflater = LayoutInflater.from(this);
        View emptyLayout = inflater.inflate(R.layout.layout_empty_conent, null);
        ImageView im_empty_logo = emptyLayout.findViewById(R.id.im_empty_logo);
        im_empty_logo.setBackgroundResource(R.drawable.icon_empty_message_box);
        messageBoxAdapter.setEmptyView(emptyLayout);
        rvAddress.setAdapter(messageBoxAdapter);
        messageBoxAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (null != adapter && null != adapter.getData() && adapter.getData().size() > position) {
                    SystemMessageBean.RowsBean item = (SystemMessageBean.RowsBean) adapter.getItem(position);
                    if (item.readStatus == 0) {
                        presenter.setCurrentRead(item.id);
                    }
                    if (!TextUtils.isEmpty(item.memo)) {
                        try {
                            RouteBean routeBean = GsonUtils.fromJson(item.memo, RouteBean.class);
                            if (TextUtils.equals(routeBean.pageTag, RouteConstants.PAGE_TAG_MESSAGE)) {
                                return;
                            }
                            JumpUtils.jump(routeBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        });
    }

    @Override
    protected ActivityMessageBoxBinding getLayoutView() {
        return ActivityMessageBoxBinding.inflate(getLayoutInflater());
    }

    @Override
    protected MessageBoxPresenter createPresenter() {
        return new MessageBoxPresenter();
    }

    private int currentPage;

    @Override
    public void initData() {
        super.initData();
        viewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                queryList(true);
            }
        });
        messageBoxAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //上拉加载
                if (hasNext) {
                    currentPage++;
                    queryList(false);
                } else {
                    messageBoxAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        });
        currentPage = 1;
        queryList(true);
    }

    @Override
    public void sysMessageListSuccess(int page, SystemMessageBean data) {
        if (data != null) {
            if (page == 1) {
                viewBinding.refreshLayout.finishRefresh();
                messageBoxAdapter.getData().clear();
                messageBoxAdapter.notifyDataSetChanged();
                if (data.rows != null && data.rows.size() > 0) {
                    checkHasNext(data.rows.size());
                    messageBoxAdapter.setNewInstance(data.rows);
                } else {
                    messageBoxAdapter.notifyDataSetChanged();
                }
            } else {
                if (data.rows != null && data.rows.size() > 0) {
                    messageBoxAdapter.addData(data.rows);
                    messageBoxAdapter.getLoadMoreModule().loadMoreComplete();
                    checkHasNext(data.rows.size());
                } else {
                    messageBoxAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        }
    }

    private boolean hasNext = true;

    /**
     * 检查是否还有下一页
     *
     * @param dataSize
     */
    private void checkHasNext(int dataSize) {
        hasNext = dataSize >= Constants.DEFAULT_DATA_SIZE;
    }

    private void queryList(boolean isLoading) {
        presenter.sysMessageList(isLoading, currentPage, group);
    }


    @Override
    public void sysMessageListError(int page) {
        if (page == 1) {
            viewBinding.refreshLayout.finishRefresh();
        } else {
            if (messageBoxAdapter != null) {
                currentPage--;
                messageBoxAdapter.getLoadMoreModule().loadMoreFail();
            }
        }
    }

    @Override
    public void setCurrentReadSuccess(long id) {
        for (SystemMessageBean.RowsBean rowsBean : messageBoxAdapter.getData()) {
            if (rowsBean.id == id) {
                rowsBean.readStatus = 1;
                break;
            }
        }
        presenter.queryCountOfUnread();
        messageBoxAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.queryCountOfUnread();
    }

    @Override
    public void queryCountOfUnreadSuccess(List<CountOfUnreadBean> data) {
        if (null == data || data.size() == 0) {
            viewBinding.tvAllUnread.setVisibility(View.GONE);
            viewBinding.tvCourseUnread.setVisibility(View.GONE);
            viewBinding.tvSystemUnread.setVisibility(View.GONE);
            return;
        }
        int totalCount = 0;
        int courseCount = 0;
        int systemCount = 0;
        for (CountOfUnreadBean datum : data) {
            if (datum.key.equals("COURSE")) {
                courseCount = datum.value;
            } else if (datum.key.equals("SYSTEM")) {
                systemCount = datum.value;
            }
        }
        totalCount = courseCount + systemCount;
        if (totalCount > 0) {
            viewBinding.tvAllUnread.setVisibility(View.VISIBLE);
            viewBinding.tvAllUnread.setText(totalCount + "");
        } else {
            viewBinding.tvAllUnread.setVisibility(View.GONE);
        }
        if (courseCount > 0) {
            viewBinding.tvCourseUnread.setVisibility(View.VISIBLE);
            viewBinding.tvCourseUnread.setText(courseCount + "");
        } else {
            viewBinding.tvCourseUnread.setVisibility(View.GONE);
        }
        if (systemCount > 0) {
            viewBinding.tvSystemUnread.setVisibility(View.VISIBLE);
            viewBinding.tvSystemUnread.setText(systemCount + "");
        } else {
            viewBinding.tvSystemUnread.setVisibility(View.GONE);
        }
    }

    @Override
    public void batchSetReadSuccess() {
        presenter.queryCountOfUnread();
        currentPage = 1;
        queryList(false);
    }
}
