package com.yidianling.im.ui.activity;

import android.graphics.Color;
import android.view.View;
import android.widget.ListView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.TitleBar;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.im.bean.MsgData;
import com.yidianling.im.config.constants.ImConstants;
import com.yidianling.im.http.ImHttp;
import com.yidianling.im.http.ImHttpImpl;
import com.yidianling.im.message.param.MsgListParam;
import com.yidianling.im.message.param.ReadParam;
import com.yidianling.im.ui.adapter.MsgListAdapter;

import org.jetbrains.annotations.NotNull;

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

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import io.reactivex.disposables.Disposable;

/**
 * 动态消息列表
 */
public class OtherMsgDetailActivity extends BaseActivity implements PtrHandler {

    String title = "";

    PtrFrameLayout store_house_ptr_frame;
    ListView lv_content;
    View ll_empty;

    TitleBar titlebar;

    MsgListAdapter adapter;
    //消息类别
    int type;


    int page = 0;
    boolean hasMore = true;
    List<MsgData> msgDatas;

    @Override
    protected int layoutResId() {
        return R.layout.im_activity_other_msg_detail;
    }

    @Override
    protected void initDataAndEvent() {
        store_house_ptr_frame = findViewById(R.id.store_house_ptr_frame);
        lv_content = findViewById(R.id.lv_content);
        ll_empty = findViewById(R.id.ll_empty);
        titlebar = findViewById(R.id.title_bar);
        type = getIntent().getIntExtra("type", 0);
        title = getIntent().getStringExtra("title");
        httpHelper = ImHttpImpl.Companion.getInstance();
        init();
    }

    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true, true);
    }

    void init() {
        if (title != null && !title.equals("")) {
            titlebar.setTitle(title);
        }
        //反馈页面
        if (type == 14) {
            titlebar.setTitle("通知");
            titlebar.setmRightText("投诉反馈");
        }
        titlebar.setRightTextColor(Color.parseColor("#666666"));
        titlebar.setOnRightTextClick((view, isActive) -> {
                    if (type == 14) {
                        ARouter.getInstance().build("/mine/FeedBackActivity").navigation();
                    } else {
                        allMarkReaded();
                    }
                }
        );
        // header
        final MaterialHeader header = new MaterialHeader(this);
        int[] colors = getResources().getIntArray(R.array.ydl_colors);
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        int padding = (int) this.getResources().getDimension(R.dimen.im_default_dis_size);
        header.setPadding(0, padding, 0, padding);
        header.setPtrFrameLayout(store_house_ptr_frame);
        store_house_ptr_frame.setHeaderView(header);
        store_house_ptr_frame.setPtrHandler(this);
        store_house_ptr_frame.addPtrUIHandler(header);

        adapter = new MsgListAdapter(this, type, this);

        lv_content.setAdapter(adapter);
        lv_content.setEmptyView(ll_empty);

        getMsgData(false);
    }

    private ImHttp httpHelper;

    private void allMarkReaded() {
        showProgressDialog("");
        Disposable disposable = httpHelper.updateRead(new ReadParam(type))
                .compose(RxUtils.applySchedulers(this))
                .compose(RxUtils.resultData())
                .subscribe(updateStatusBean -> {
                    dismissProgressDialog();
                    if (updateStatusBean != null) {
                        if (updateStatusBean.update_status == 1) {//更新成功
                            ToastUtil.toastShort("已全部标记为已读");
                            adapter.updataAll();
                        } else {
                            ToastUtil.toastShort("已全部标记为已读");
                        }
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        dismissProgressDialog();
                    }
                });

    }

    private void getMsgData(final boolean loadMore) {
        if (loadMore) {
            page++;
        } else {
            page = 1;
        }

        Disposable dis = httpHelper.getMsgList(new MsgListParam(page + "", type))
                .compose(RxUtils.applySchedulers(this))
                .compose(RxUtils.resultData())
                .subscribe(msgData -> {
                    LogUtil.d("data fetch compelete");
                    store_house_ptr_frame.refreshComplete();
                    msgDatas = msgData;
                    if (msgDatas.size() == 0) {
                        return;
                    }
                    if (msgDatas == null || msgDatas.size() < ImConstants.PAGE_SIZE) {
                        hasMore = false;
                    }
                    if (!loadMore) {
                        Collections.reverse(msgDatas);
                        adapter.setDataList(msgDatas);
                        //第一次加载滚动到底部
                        lv_content.setSelection(msgDatas.size() - 1);
                    } else if (msgDatas != null) {
                        //临时存放list
                        List<MsgData> tempList = new ArrayList<>();
                        List<MsgData> old = adapter.getDataList();
                        //将原数据倒序
                        Collections.reverse(old);
                        //老数据加入最新数据集合
                        tempList.addAll(old);
                        tempList.addAll(msgDatas);

                        Collections.reverse(tempList);
                        adapter.update(tempList);
                        tempList.clear();

                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        LogUtil.d("data fetch failed");
                        store_house_ptr_frame.refreshComplete();
                        ToastHelper.Companion.show(msg);
                    }
                });
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, lv_content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        getMsgData(true);
    }

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

    @Override
    protected void onPause() {
        super.onPause();
    }
}
