package com.unis.sxzcl.ui.policy;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.unis.model.DataCallback;
import com.unis.model.PolicyModel;
import com.unis.model.bean.PolicyBean;
import com.unis.sxzcl.R;
import com.unis.sxzcl.base.BaseListFragment;
import com.unis.sxzcl.databinding.FragmentBaseListTitleBinding;

import java.util.List;


/**
 * 政策制度 列表
 * 创建人: mQ
 * 时间: 2021/2/2 15:10
 */
public class PolicyListFragment extends BaseListFragment<FragmentBaseListTitleBinding> {

    private PolicyListAdapter mAdapter;

    @Override
    public void onRefreshData() {
        getData(true);
    }

    @Override
    public void onMoreData() {
        super.onMoreData();
        getData(false);
    }

    @Override
    protected FragmentBaseListTitleBinding getViewBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentBaseListTitleBinding.inflate(inflater, container, false);
    }

    @Override
    protected void init() {
        mBinding.bar.setTitle("政策制度")
                .setLeftClickListener(v -> onBack());

        mAdapter = new PolicyListAdapter();
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            // 查看详情
            Bundle bundle = new Bundle();
            bundle.putString("data", getGson().toJson(mAdapter.getItem(position)));
            navigation(R.id.policyDetailFragment, bundle);
        });

        initBaseListView(mBinding.refreshLayout, mBinding.recyclerView, mAdapter, true);
    }

    @Override
    protected void onFirstShow() {
        onRefresh();
    }

    private int page = 0;

    private void getData(boolean refresh) {
        if (refresh) page = 1;
        else page++;
        PolicyModel.get().getList(page, new DataCallback<List<PolicyBean>>() {
            @Override
            public void onSuccess(List<PolicyBean> data) {
                if (!isActive()) return;

                if (data.isEmpty()) {
                    loadEnd();
                    return;
                }
                if (page == 1) {
                    mAdapter.setList(data);
                } else {
                    mAdapter.addData(data);
                }
                loadComplete();
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (!isActive()) return;
                loadError();
            }
        });
    }
}
