package com.gh.gamecenter.libao;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import com.gh.common.util.LibaoUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.LibaoNormalViewHolder;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.databinding.LibaoItemBinding;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.LibaoEntity;
import com.gh.gamecenter.feature.entity.MeEntity;
import com.gh.gamecenter.feature.entity.UserDataLibaoEntity;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.feature.game.GameItemViewHolder;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.adapter.BaseRecyclerAdapter;

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

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * Created by khy on 2017/2/28.
 */
public class LibaoHistoryAdapter extends BaseRecyclerAdapter<ViewHolder> {

    private OnRequestCallBackListener mCallBackListener;

    private List<LibaoEntity> mLibaoList;

    private boolean isOver;
    private boolean isLoading;
    private boolean isNetworkError;

    private int mPage;

    public LibaoHistoryAdapter(Context context, OnRequestCallBackListener callBackListener) {
        super(context);
        mCallBackListener = callBackListener;
        mLibaoList = new ArrayList<>();
        mPage = 1;
        loadList();
    }

    public void loadList() {
        if (isLoading) return;
        isLoading = true;
        notifyItemChanged(getItemCount() - 1);
        RetrofitManager.getInstance().getApi()
                .getHistoryLibao(UrlFilterUtils.getFilterQuery("history", "true"), mPage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<List<LibaoEntity>, List<LibaoEntity>>() {
                    @Override
                    public List<LibaoEntity> apply(List<LibaoEntity> libaoEntities) {
                        // 去掉重复数据
                        return LibaoUtils.removeDuplicateData(mLibaoList, libaoEntities);
                    }
                })
                .subscribe(new Response<List<LibaoEntity>>() {
                    @Override
                    public void onResponse(List<LibaoEntity> response) {
                        super.onResponse(response);
                        mLibaoList.addAll(response);

                        if (response.size() < 20) {
                            isOver = true;
                            mCallBackListener.loadDone("TAG");
                        }

                        if (mLibaoList.size() == 0) {
                            mCallBackListener.loadDone("NULL");
                        }

                        mPage++;
                        isLoading = false;
                        isNetworkError = false;
                        if (response.size() != 0) {
                            getLibaoStatus(response);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        super.onFailure(e);
                        isNetworkError = true;
                        isLoading = false;
                    }
                });


    }

    private void getLibaoStatus(List<LibaoEntity> response) {
        for (LibaoEntity entity : response) {
            MeEntity userData = entity.getMe();
            if (userData != null && userData.getUserDataLibaoList() != null && userData.getUserDataLibaoList().size() > 0) {
                List<UserDataLibaoEntity> userDataLibaoList = userData.getUserDataLibaoList();
                UserDataLibaoEntity userDataLibaoEntity = userDataLibaoList.get(userDataLibaoList.size() - 1);
                String status = userDataLibaoEntity.getType();
                if ("ling".equals(status)) {
                    entity.setStatus("linged");
                } else {
                    entity.setStatus("taoed");
                }
            }
        }
        notifyItemRangeChanged(0, getItemCount() - 1);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ItemViewType.LIBAO_NORMAL) {
            View view = mLayoutInflater.inflate(R.layout.libao_item, parent, false);
            return new LibaoNormalViewHolder(LibaoItemBinding.bind(view));
        } else {
            View view = mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof LibaoNormalViewHolder) {
            LibaoNormalViewHolder viewHolder = (LibaoNormalViewHolder) holder;
            LibaoEntity libaoEntity = mLibaoList.get(position);
            ExtensionsKt.setRootBackgroundColor(viewHolder.binding.getRoot(), com.gh.gamecenter.common.R.color.ui_surface);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                    , LinearLayout.LayoutParams.WRAP_CONTENT);
            if (position == 0 || position == getItemCount() - 1) {
                if (position == 0) {
                    params.setMargins(0, DisplayUtils.dip2px(mContext, 5), 0, 0);
                } else {
                    params.setMargins(0, 0, 0, DisplayUtils.dip2px(mContext, 5));
                }
            } else {
                params.setMargins(0, 0, 0, 0);
            }
            viewHolder.itemView.setLayoutParams(params);
            viewHolder.itemView.setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.libao_history_bg));

            viewHolder.binding.libaoName.setText(libaoEntity.getName());
            viewHolder.binding.libaoDes.setText(libaoEntity.getContent());
            viewHolder.binding.libaoGameName.setText(libaoEntity.getGame().getName());
            viewHolder.binding.libaoGameIcon.displayGameIcon(libaoEntity.getIcon(), libaoEntity.getIconSubscript(), libaoEntity.getGame().getIconFloat());

            //领取状态
            if (TextUtils.isEmpty(libaoEntity.getStatus())) {
                libaoEntity.setStatus("unshelve");
            }
            LibaoUtils.setLiBaoBtnStatusRound(viewHolder.binding.libaoBtnStatus,
                    libaoEntity, true, mContext);

            GameEntity gameEntity = libaoEntity.getGame().toGameEntity();
            GameItemViewHolder.initGameSubtitleAndAdLabel(gameEntity, viewHolder.binding.gameSubtitleTv, null, null, false, null, false, null);
        } else {
            FooterViewHolder viewHolder = (FooterViewHolder) holder;
            viewHolder.initFooterViewHolder(isLoading, isNetworkError, isOver, v -> {
                if (isNetworkError) {
                    isNetworkError = false;
                    notifyItemChanged(getItemCount() - 1);
                    loadList();
                }
            });
        }

    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            return ItemViewType.LOADING;
        } else {
            return ItemViewType.LIBAO_NORMAL;
        }
    }

    @Override
    public int getItemCount() {
        return mLibaoList.size() + 1;
    }

    public boolean isOver() {
        return isOver;
    }

    public boolean isLoading() {
        return isLoading;
    }

    public boolean isNetworkError() {
        return isNetworkError;
    }

    public int getLibaoListSize() {
        return mLibaoList.size();
    }
}
