package com.yidianling.dynamic.thank;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.dynamic.bean.DynamicConstants;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.common.net.DynamicApiUtils;
import com.yidianling.dynamic.model.Command;
import com.yidianling.dynamic.thank.data.ThxData;
import com.yidianling.dynamic.thank.data.ThxListDate;
import com.yidianling.dynamic.thank.view.ThankHeadView;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.data.http.RxUtils;

import org.jetbrains.annotations.NotNull;

import de.greenrobot.event.EventBus;
import in.srain.cube.views.loadmore.LoadMoreContainer;
import in.srain.cube.views.loadmore.LoadMoreHandler;
import in.srain.cube.views.loadmore.LoadMoreListViewContainer;
import in.srain.cube.views.loadmore.LoadMoreUIHandler;
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.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 感谢TA
 * Created by softrice on 15/11/25.
 */
public class ThankActivity extends BaseActivity implements PtrHandler, LoadMoreHandler {


    private PtrFrameLayout store_house_ptr_frame;
    private LoadMoreListViewContainer load_more_list_view_container;
    private ListView lv_content;
    ThxZanListAdapter adapter;

    int page = 1;
    boolean hasMore = true;
    ThankHeadView headView;
    WorryDetailAnswer worryDetailAnswer;

    int answerId;

    int listNum;

    ThxData thxData;

    WorryDetailAnswer worryDetailAnswerForEventBus;

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

    void init() {
        // 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) getResources().getDimension(R.dimen.dynamic_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);

        // 创建
        ISLoadMoreFooterView footerView = new ISLoadMoreFooterView(this);
        footerView.setVisibility(View.GONE);

        load_more_list_view_container.setLoadMoreView(footerView);
        load_more_list_view_container.setLoadMoreUIHandler(footerView);
        load_more_list_view_container.setLoadMoreHandler(this);


        adapter = new ThxZanListAdapter(this);

        headView = new ThankHeadView(this);
        if (worryDetailAnswer != null) {
            headView.setWorryDetailAnswer(worryDetailAnswer);
        }
        headView.setAnswerId(answerId);
        headView.setlistNum(listNum);
        getHeadDate();
        lv_content.addHeaderView(headView);

        lv_content.setAdapter(adapter);
        getData(false);
    }


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

    private void getHeadDate() {
        Command.GetThxHeadDate cmd = new Command.GetThxHeadDate(answerId);
        DynamicApiUtils.getThxHeadData(cmd)
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    try {
                        thxData = resp;
                        headView.setData(thxData);
                        if (thxData.countPage <= 1) {
                            hasMore = false;
                        } else {
                            hasMore = true;
                            page = 1;
                        }

                        if (thxData.zanList == null || thxData.zanList.size() == 0) {
                            setListViewNull();
                        } else {
                            adapter.setDataList(thxData.zanList);
                        }

                    } catch (Exception e) {
                        LogUtil.d(e.getMessage());
                    }
                }, throwable -> DynamicApiUtils.handleError(ThankActivity.this, throwable));
    }

    private void setListViewNull() {
        load_more_list_view_container.loadMoreFinish(true, false);
    }


   public void getData(final boolean loadMore) {
        if (loadMore && !hasMore) {
            load_more_list_view_container.loadMoreFinish(false, false);
            return;
        }
        if (loadMore) {
            page++;
        } else {
            page = 1;
            hasMore = true;
        }
        Command.GetZanList cmd = new Command.GetZanList(page, answerId);
        DynamicApiUtils.getZanList(cmd)
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    load_more_list_view_container.loadMoreFinish(false, true);
                    try {
                        ThxListDate thxListDate = resp;
                        if (thxListDate.array_name == null ||
                                thxListDate.array_name.zanList == null ||
                                thxListDate.array_name.zanList.size() < DynamicConstants.THX_REPLY_PAGE_SIZE) {
                            hasMore = false;
                            load_more_list_view_container.loadMoreFinish(false, false);
                        }
                        if (!loadMore) {
                            adapter.setDataList(thxListDate.array_name.zanList);
                        } else if (thxListDate.array_name.zanList != null) {
                            adapter.addDataList(thxListDate.array_name.zanList);
                        }
                        if (page == 1 && (thxListDate.array_name == null ||
                                thxListDate.array_name.zanList == null ||
                                thxListDate.array_name.zanList.size() == 0)) {
                            setListViewNull();
                        }
                    } catch (Exception e) {
                        LogUtil.d(e.getMessage());
                    }
                }, throwable -> DynamicApiUtils.handleError(ThankActivity.this, throwable));
    }

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

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        frame.postDelayed(new Runnable() {
            @Override
            public void run() {
                store_house_ptr_frame.refreshComplete();
            }
        }, 1800);
        getData(false);
    }


    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        getData(true);
    }

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

    @Override
    protected void initDataAndEvent() {
        bindView();

        listNum = getIntent().getIntExtra("listNum", 0);
        answerId = getIntent().getIntExtra("answerId", 0);

        try {
            worryDetailAnswer = (WorryDetailAnswer) getIntent().getSerializableExtra("worryDetailAnswer");
        } catch (Exception e) {
            e.printStackTrace();
        }

        init();
        EventBus.getDefault().register(this);
    }

    private void bindView() {
        store_house_ptr_frame = findViewById(R.id.store_house_ptr_frame);
        load_more_list_view_container = findViewById(R.id.load_more_list_view_container);
        lv_content = findViewById(R.id.lv_content);
    }

    class ISLoadMoreFooterView extends RelativeLayout
            implements LoadMoreUIHandler {

        private TextView mTextView;

        public ISLoadMoreFooterView(Context context) {
            super(context);
            setupViews();
        }

        private void setupViews() {
            LayoutInflater.from(getContext()).inflate(in.srain.cube.R.layout.cube_views_load_more_default_footer, this);
            mTextView = (TextView) findViewById(in.srain.cube.R.id.cube_views_load_more_default_footer_text_view);
            mTextView.setText("");
        }

        @Override
        public void onLoading(LoadMoreContainer container) {
            setVisibility(VISIBLE);
            mTextView.setText("正在加载...");
            mTextView.setTextColor(0xFF545454);
        }

        @Override
        public void onLoadFinish(LoadMoreContainer container, boolean empty, boolean hasMore) {
            if (!hasMore) {
                setVisibility(VISIBLE);
                if (empty) {
                    mTextView.setText("小小的鼓励，满满的收获～");
                    mTextView.setTextColor(0xFFC0C0C0);
                } else {
                    mTextView.setText("感谢大家的鼓励：）");
                    mTextView.setTextColor(0xFFC0C0C0);
                }
            } else {
                setVisibility(VISIBLE);
                mTextView.setText("感谢大家的鼓励：）");
                mTextView.setTextColor(0xFFC0C0C0);
            }
        }

        @Override
        public void onWaitToLoadMore(LoadMoreContainer container) {
            mTextView.setText("");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            ToastUtil.toastImg(this, R.drawable.dynamic_dialog_send_thx_success);
            if (worryDetailAnswerForEventBus != null) {
                worryDetailAnswerForEventBus.pIsZan = true;
                worryDetailAnswerForEventBus.pZan++;
            }
            finish();
        }
    }


    public void onEvent(WorryDetailAnswer worryDetailAnswer) {
        worryDetailAnswerForEventBus = worryDetailAnswer;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
