package com.gh.gamecenter.libao;

import static com.gh.gamecenter.common.constant.Constants.LIST_FOOTER_ITEM;
import static com.gh.gamecenter.common.constant.Constants.LIST_HEAD_ITEM;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import com.gh.common.util.LibaoUtils;
import com.gh.gamecenter.feature.utils.PlatformUtils;
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.OnListClickListener;
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.databinding.LibaoItemBinding;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.LibaoEntity;
import com.gh.gamecenter.feature.entity.LibaoStatusEntity;
import com.gh.gamecenter.feature.game.GameItemViewHolder;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.common.retrofit.Response;
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 2016/12/12.
 */
class Libao2FragmentAdapter extends BaseRecyclerAdapter<ViewHolder> {

    private OnRequestCallBackListener mCallBackListener;
    private OnListClickListener mListListener;

    private List<LibaoEntity> mLibaoList;

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

    private String mEntrance;

    private int skipPosition;
    private int mPage;

    Libao2FragmentAdapter(Context context, OnRequestCallBackListener listener,
                          OnListClickListener listListener, String entrance) {
        super(context);
        mCallBackListener = listener;
        mListListener = listListener;

        mEntrance = entrance;

        mLibaoList = new ArrayList<>();

        skipPosition = -1;
        mPage = 1;

        isLoading = false;
        isNetworkError = false;
        isOver = false;
    }

    // 加载数据
    public void addList() {
        if (TextUtils.isEmpty(UserManager.getInstance().getToken())) {
            mCallBackListener.loadDone(null);
            return;
        }

        if (isLoading) {
            return;
        }

        isLoading = true;
        notifyItemChanged(getItemCount() - 1);
        RetrofitManager.getInstance().getApi().getConcernLibao(UserManager.getInstance().getUserId(), mPage)
                .map(new Function<List<LibaoEntity>, List<LibaoEntity>>() {
                    @Override
                    public List<LibaoEntity> apply(List<LibaoEntity> list) {
                        // 去掉重复数据
                        return LibaoUtils.removeDuplicateData(mLibaoList, list);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<LibaoEntity>>() {
                    @Override
                    public void onResponse(List<LibaoEntity> response) {
                        mLibaoList.addAll(response);
                        mCallBackListener.loadDone();
                        if (response.size() < 20) {
                            isOver = true;
                        }

                        if (mLibaoList.size() == 0) {
                            mCallBackListener.loadEmpty();
                        } else {
                            mCallBackListener.loadDone();
                        }
//                        notifyDataSetChanged();
                        isLoading = false;
                        mPage++;

                        if (response.size() != 0) {
                            getLibaoStatus(response);
                        }

                    }

                    @Override
                    public void onFailure(HttpException e) {
                        isLoading = false;
                        if (mLibaoList.size() == 0) {
                            mCallBackListener.loadError();
                        } else {
                            isNetworkError = true;
                            notifyItemChanged(getItemCount() - 1);
                        }
                    }
                });
    }

    //获取礼包状态
    private void getLibaoStatus(List<LibaoEntity> response) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0, size = response.size(); i < size; i++) {
            builder.append(response.get(i).getId());
            builder.append("-");
        }
        if (builder.length() == 0) return;
        builder.deleteCharAt(builder.length() - 1);
        String ids = builder.toString();

        LibaoUtils.getLibaoStatus(ids, new LibaoUtils.PostLibaoListener() {
            @Override
            public void postSucceed(Object response) {
                List<LibaoStatusEntity> statusList = (List<LibaoStatusEntity>) response;

                LibaoUtils.initLiBaoEntity(statusList, mLibaoList);

                notifyItemRangeChanged(0, getItemCount());
            }

            @Override
            public void postFailed(Throwable error) {

            }
        });
    }

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

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof LibaoNormalViewHolder) {
            initLibaoViewHolder((LibaoNormalViewHolder) holder, position);
        } else if (holder instanceof FooterViewHolder) {
            initFooterViewHolder((FooterViewHolder) holder);
        }
    }

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

    @Override
    public int getItemCount() {
        if (mLibaoList.size() == 0) {
            return LIST_HEAD_ITEM;
        }

        return mLibaoList.size() + LIST_FOOTER_ITEM;
    }

    private void initLibaoViewHolder(final LibaoNormalViewHolder holder, final int position) {
        LibaoEntity libaoEntity = mLibaoList.get(position);
        holder.setClickData(libaoEntity);
        ExtensionsKt.setRootBackgroundColor(holder.binding.getRoot(), com.gh.gamecenter.common.R.color.ui_surface);
        holder.binding.libaoName.setText(libaoEntity.getName());
        holder.binding.libaoGameIcon.displayGameIcon(libaoEntity.getIcon(), libaoEntity.getIconSubscript(), libaoEntity.getGame().getIconFloat());
        if (TextUtils.isEmpty(libaoEntity.getPlatform())) {
            holder.binding.libaoGameName.setText(libaoEntity.getGame().getName());
        } else {
            holder.binding.libaoGameName.setText(libaoEntity.getGame().getName() + " - " + PlatformUtils.getInstance(mContext)
                    .getPlatformName(libaoEntity.getPlatform()));
        }

        String content;
        if (libaoEntity.getContent().contains("<br/>")) {
            content = libaoEntity.getContent().replaceAll("<br/>", " ");
        } else {
            content = libaoEntity.getContent();
        }
        holder.binding.libaoDes.setText(content);

        if (libaoEntity.getStatus() != null) {
            LibaoUtils.initLibaoBtn(mContext, holder.binding.libaoBtnStatus, libaoEntity, false, null, true, mEntrance + "+(礼包中心:关注)", "礼包中心-关注", new LibaoUtils.OnLibaoStatusChangeListener() {
                @Override
                public void onLibaoStatusChange() {
                    notifyItemChanged(position);
                }
            });
            if (libaoEntity.getPackageName() != null && !libaoEntity.getPackageName().isEmpty()) {
                holder.binding.libaoBtnStatus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mListListener.onListClick(holder.binding.libaoBtnStatus, position, libaoEntity);
                    }
                });
            }
//            LibaoUtils.setLiBaoBtnStatusRound(holder.libaoBtnStatus, libaoEntity, true, mContext);
        }

        GameEntity gameEntity = libaoEntity.getGame().toGameEntity();
        GameItemViewHolder.initGameSubtitleAndAdLabel(gameEntity, holder.binding.gameSubtitleTv, null, null, false, null, false, null);
    }

    private void initFooterViewHolder(FooterViewHolder holder) {
        holder.initItemPadding();

        holder.initFooterViewHolder(isLoading, isNetworkError, isOver, v -> {
            if (isNetworkError) {
                isNetworkError = false;
                notifyItemChanged(getItemCount() - 1);
                addList();
            }
        });
    }

    public boolean isNetworkError() {
        return isNetworkError;
    }

    public boolean isOver() {
        return isOver;
    }

    public boolean isLoading() {
        return isLoading;
    }

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

    public int getSkipPosition() {
        return skipPosition;
    }

    public void setSkipPosition(int position) {
        skipPosition = position;
    }
}
