package com.common.im.ui.activity;

import android.os.Bundle;
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.alibaba.android.arouter.launcher.ARouter;
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.common.im.adapter.NoticeListAdapter;
import com.common.im.adapter.NoticePopuListAdapter;
import com.common.im.bean.GroupNoticeBean;
import com.common.im.contract.NoticeContract;
import com.common.im.presenter.NoticePresenter;
import com.common.im_ui.R;
import com.common.im_ui.databinding.ActivityNoticeBinding;
import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.PopupUtil;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.widgets.DensityUtil;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/6/11 17:52
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.ChatCenter.CHAT_GROUP_NOTICE)
public class NoticeActivity extends BaseMVPActivity<ActivityNoticeBinding, NoticePresenter> implements NoticeContract.NoticeView, View.OnClickListener {

    private int currentPage;

    private String targetId = "";


    @Override
    public void onClick(View v) {
        if (v.getId() == com.cooleshow.base.R.id.tv_right) {
            ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_GROUP_NOTICE_EDIT)
                    .withString("targetId", targetId)
                    .navigation();
        }
    }

    RecyclerView recyclerView;
    ImageView floatbutton;

    List<GroupNoticeBean.RowsBean> noticeData = new ArrayList<>();
    private NoticeListAdapter mAdapter;

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "群公告");
        if (BaseApplication.Companion.isTeacherClient()) {
            viewBinding.toolbarInclude.tvRight.setImageResource(R.drawable.icon_chat_group_notice_add);
            viewBinding.toolbarInclude.tvRight.setVisibility(View.VISIBLE);
            viewBinding.toolbarInclude.tvRight.setOnClickListener(this);
        } else {
            //学生不可修改群公告
            viewBinding.toolbarInclude.tvRight.setVisibility(View.GONE);
        }
        targetId = getIntent().getStringExtra("targetId");
        recyclerView = viewBinding.recyclerView;
        floatbutton = viewBinding.floatbutton;
        floatbutton.setOnClickListener(this);
        viewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                queryData();
            }
        });

        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        mAdapter = new NoticeListAdapter(noticeData);
        EmptyViewLayout emptyViewLayout = new EmptyViewLayout(this);
        emptyViewLayout.setContent(R.drawable.icon_empty_content, "暂无群公告");
        mAdapter.setEmptyView(emptyViewLayout);
        recyclerView.setAdapter(mAdapter);

        mAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //上拉加载
                if (hasNext) {
                    currentPage++;
                    queryData();
                } else {
                    mAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        });
        mAdapter.setmSettingClickListener(new NoticeListAdapter.SettingClickListener() {
            @Override
            public void onSettingClick(View v, GroupNoticeBean.RowsBean bean) {
                List<String> popuList = new ArrayList<>();
                popuList.clear();
                popuList.add("编辑公告");
                if (bean.topFlag) {
                    popuList.add("取消置顶");
                } else {
                    popuList.add("置顶");
                }
                popuList.add("删除");
                initPopu(popuList, v, bean);
            }
        });

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }


    @Override
    public void initData() {
        super.initData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        currentPage = 1;
        queryData();
    }

    private void initPopu(List<String> popuList, View view, GroupNoticeBean.RowsBean bean) {
        PopupUtil.showInDropWrapNObg(this, R.layout.notice_on_popu, view,
                SizeUtils.dp2px(20), SizeUtils.dp2px(20), (view1, popupWindow) -> {
                    RecyclerView recyclerView = view1.findViewById(R.id.recyclerView);
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(NoticeActivity.this);
                    recyclerView.setLayoutManager(linearLayoutManager);
                    NoticePopuListAdapter adapter = new NoticePopuListAdapter(popuList);
                    recyclerView.setAdapter(adapter);
                    adapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                            if (position == 0) {
                                ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_GROUP_NOTICE_EDIT)
                                        .withString("targetId", targetId)
                                        .withString("title", bean.title)
                                        .withString("notice", bean.content)
                                        .withBoolean("isTop", bean.topFlag)
                                        .withLong("id", bean.id)
                                        .navigation();
                            }
                            if (position == 1) {
                                if (popuList.get(position).equals("置顶")) {
                                    presenter.noticeUpdate(bean.id, targetId, bean.title, bean.content, true);
                                } else {
                                    presenter.noticeUpdate(bean.id, targetId, bean.title, bean.content, false);
                                }
                            }
                            if (position == 2) {
                                presenter.noticeDel(String.valueOf(bean.id));
                            }
                            popupWindow.dismiss();
                        }
                    });


                });
    }


    private boolean hasNext = true;

    private void queryData() {
        //根据默认筛选条件查询
        presenter.queryGroupNotice(targetId, currentPage);
    }

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

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

    @Override
    public void queryGroupNoticeSuccess(int page, GroupNoticeBean dataList) {
        if (dataList != null) {
            if (page == 1) {
                //第一页
                viewBinding.refreshLayout.finishRefresh();
                if (mAdapter != null) {
                    mAdapter.getData().clear();
                    mAdapter.notifyDataSetChanged();
                    if (dataList.rows != null && dataList.rows.size() > 0) {
                        checkHasNext(dataList.rows.size());
                        mAdapter.setNewInstance(dataList.rows);
                    }
                }
            } else {
                //加载更多
                if (mAdapter != null) {
                    if (dataList.rows != null && dataList.rows.size() > 0) {
                        mAdapter.getLoadMoreModule().loadMoreComplete();
                        checkHasNext(dataList.rows.size());
                        mAdapter.addData(dataList.rows);
                    } else {
                        mAdapter.getLoadMoreModule().loadMoreEnd();
                    }
                }
            }
        }
    }

    private void checkHasNext(int dataSize) {
        hasNext = dataSize >= Constants.DEFAULT_DATA_SIZE;
    }

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

    @Override
    public void updateGroupNoticeSuccess() {
        if (!checkActivityExist()) {
            return;
        }
        currentPage = 1;
        queryData();
    }

    @Override
    public void delGroupNoticeSuccess() {
        if (!checkActivityExist()) {
            return;
        }
        currentPage = 1;
        queryData();
    }
}
