package com.gh.gamecenter.info;

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

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

import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.common.util.ConcernContentUtils;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.common.util.LibaoUtils;
import com.gh.common.util.NewsUtils;
import com.gh.gamecenter.core.utils.NumberUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsDigestViewHolder;
import com.gh.gamecenter.databinding.NewsDigestItemBinding;
import com.gh.gamecenter.entity.CommentnumEntity;
import com.gh.gamecenter.entity.ConcernEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.LibaoStatusEntity;
import com.gh.gamecenter.entity.MeEntity;
import com.gh.gamecenter.entity.UserDataLibaoEntity;
import com.gh.gamecenter.entity.ViewsEntity;
import com.gh.gamecenter.game.GameItemViewHolder;
import com.gh.gamecenter.manager.CommentManager;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.manager.VisitManager;
import com.gh.gamecenter.common.retrofit.JSONObjectResponse;
import com.gh.gamecenter.common.retrofit.ObservableUtil;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.adapter.BaseRecyclerAdapter;
import com.lightgame.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

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

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

/**
 * Created by khy on 2016/8/15.
 * 资讯-关注-数据适配器
 */
class ConcernAdapter extends BaseRecyclerAdapter<ViewHolder> {

    private OnRequestCallBackListener listener;
    private OnListClickListener mListListener;

    private List<ConcernEntity> concernList;

    private List<LibaoStatusEntity> libaoStatusList;

    private int itemCount;
    private int skipPosition;

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

    private int mPage;

    ConcernAdapter(Context context, OnRequestCallBackListener listener, OnListClickListener mistListener) {
        super(context);
        this.listener = listener;
        this.mListListener = mistListener;

        concernList = new ArrayList<>();
        libaoStatusList = new ArrayList<>();

        itemCount = 0;
        skipPosition = -1;
        mPage = 1;

        isNetworkError = false;
        isOver = false;
        isLoading = false;
        addList();
    }

    // 加载数据
    public void addList() {
        if (isLoading) {
            return;
        }

        if (TextUtils.isEmpty(UserManager.getInstance().getToken())) {
            isLoading = true;
            listener.loadEmpty();
            return;
        }
        isLoading = true;
        notifyItemChanged(getItemCount() - 1);
        RetrofitManager.getInstance().getApi()
                .getZiXunConcern(UserManager.getInstance().getUserId(), mPage)
                .map(list -> removeDuplicateData(concernList, list))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<ConcernEntity>>() {
                    @Override
                    public void onResponse(List<ConcernEntity> response) {
                        if (response.size() != 0) {
                            concernList.addAll(response);
                            itemCount += response.size();
                            notifyItemRangeInserted(concernList.size() - response.size(), response.size());

                            getLibaoStatus(response);
                            getNewsViews(response);
                            getNewsCommentnum(response);

                        } else {
                            isOver = true;
                            if (getItemCount() > 0) {
                                notifyItemChanged(getItemCount() - 1);
                            } else {
                                notifyDataSetChanged();
                            }

                        }

                        if (mPage == 1 && listener != null) {
                            if (concernList.isEmpty()) {
                                listener.loadEmpty();
                            } else {
                                listener.loadDone();
                            }
                        }

                        isLoading = false;
                        mPage++;
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        isLoading = false;

                        // 网络错误
                        if (mPage == 1) {
                            if (listener != null) {
                                listener.loadError();
                            }
                        } else {
                            Utils.toast(mContext, R.string.loading_failed_hint);
                            isNetworkError = true;
                            notifyItemChanged(getItemCount() - 1);
                        }
                    }
                });
    }

    // 去除重复数据
    private static List<ConcernEntity> removeDuplicateData(List<ConcernEntity> sourceList, List<ConcernEntity> rawList) {
        if (sourceList == null || sourceList.isEmpty()
                || rawList == null || rawList.isEmpty()) {
            return rawList;
        }
        String id;
        for (int i = 0; i < rawList.size(); i++) {
            id = rawList.get(i).getId();
            for (ConcernEntity concernEntity : sourceList) {
                if (id.equals(concernEntity.getId())) {
                    rawList.remove(i);
                    i--;
                    break;
                }
            }
        }
        return rawList;
    }

    //获取礼包状态
    private void getLibaoStatus(List<ConcernEntity> response) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0, size = response.size(); i < size; i++) {
            if ("libao".equals(response.get(i).getType())) {
                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) {
                libaoStatusList.addAll((List<LibaoStatusEntity>) response);
                notifyDataSetChanged();
            }

            @Override
            public void postFailed(Throwable error) {

            }
        });
    }

    // 获取新闻阅读量
    private void getNewsViews(final List<ConcernEntity> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        ObservableUtil.computation(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) {
                StringBuilder builder = new StringBuilder();
                for (int i = 0, size = list.size(); i < size; i++) {
                    builder.append(list.get(i).getId());
                    builder.append("-");
                }
                builder.deleteCharAt(builder.length() - 1);
                String ids = builder.toString();
                VisitManager.getInstance().addUrl(ids);
                emitter.onNext(ids);
                emitter.onComplete();
            }

        }, new Consumer<String>() {
            @Override
            public void accept(String s) {
                RetrofitManager.getInstance().getApi()
                        .getArticlesVisits(UrlFilterUtils.getFilterQuery("article_ids", s))
                        .map((Function<List<ViewsEntity>, String>) list1 -> {
                            for (ViewsEntity viewsEntity : list1) {
                                for (ConcernEntity concernEntity : concernList) {
                                    if (viewsEntity.getId().equals(concernEntity.getId())) {
                                        concernEntity.setViews(viewsEntity.getViews());
                                        break;
                                    }
                                }
                            }
                            return "";
                        })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Response<String>() {
                            @Override
                            public void onResponse(String response) {
                                notifyDataSetChanged();
                            }
                        });
            }
        });
    }

    // 获取新闻评论数
    private void getNewsCommentnum(final List<ConcernEntity> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        ObservableUtil.computation(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) {
                StringBuilder builder = new StringBuilder();
                for (int i = 0, size = list.size(); i < size; i++) {
                    builder.append(list.get(i).getId());
                    builder.append("-");
                }
                builder.deleteCharAt(builder.length() - 1);
                CommentManager.getInstance().addUrl(builder.toString());
                emitter.onNext(builder.toString());
                emitter.onComplete();
            }
        }, new Consumer<String>() {
            @Override
            public void accept(String ids) throws Exception {
                RetrofitManager.getInstance().getApi()
                        .getNewsCommentnum(ids, Utils.getTime(mContext))
                        .map(new Function<List<CommentnumEntity>, String>() {
                            @Override
                            public String apply(List<CommentnumEntity> list) {
                                for (CommentnumEntity commentnumEntity : list) {
                                    for (ConcernEntity concernEntity : concernList) {
                                        if (commentnumEntity.getId().equals(concernEntity.getId())) {
                                            concernEntity.setCommentnum(commentnumEntity.getNum());
                                            break;
                                        }
                                    }
                                }
                                return "";
                            }
                        })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Response<String>() {
                            @Override
                            public void onResponse(String response) {
                                notifyDataSetChanged();
                            }
                        });
            }
        });
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ItemViewType.NEWS_DIGEST) {
            return new NewsDigestViewHolder(NewsDigestItemBinding.inflate(mLayoutInflater, parent, false), mListListener);
        } else if (viewType == ItemViewType.LOADING) {
            View view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        }
        return null;
    }

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

    @Override
    public int getItemViewType(int position) {
        if (position == concernList.size()) {
            return ItemViewType.LOADING;
        } else {
            return ItemViewType.NEWS_DIGEST;
        }
    }

    @Override
    public int getItemCount() {
        if (itemCount == 0) {
            return 0;
        }
        return itemCount + 1;
    }

    private void initNewsDigestViewHolder(final NewsDigestViewHolder viewHolder, int position) {
        viewHolder.binding.getRoot().setBackground(ContextCompat.getDrawable(mContext, R.drawable.reuse_listview_item_style));
        viewHolder.binding.newsDigestTitle.setTextColor(ContextCompat.getColor(mContext, R.color.text_black));
        viewHolder.binding.newsDigestTime.setTextColor(ContextCompat.getColor(mContext, R.color.hint));
        viewHolder.binding.newsDigestContent.setTextColor(ContextCompat.getColor(mContext, R.color.text_3a3a3a));
        viewHolder.binding.newsDigestLibaoHint.setTextColor(ContextCompat.getColor(mContext, R.color.hint));
        viewHolder.binding.newsDigestReadNum.setTextColor(ContextCompat.getColor(mContext, R.color.text_subtitleDesc));
        viewHolder.binding.newsDigestCommentnum.setTextColor(ContextCompat.getColor(mContext, R.color.text_subtitleDesc));

        final ConcernEntity concernEntity = concernList.get(position);
        viewHolder.setClickData(concernEntity);

        if (concernEntity.getGame() != null) {
            viewHolder.binding.newsDigestThumb.displayGameIcon(concernEntity.getGame().getIcon(), concernEntity.getGame().getIconSubscript());
        } else {
            viewHolder.binding.newsDigestThumb.displayGameIcon(concernEntity.getGameIcon(), null);
        }
        viewHolder.binding.newsDigestTitle.setText(concernEntity.getGameName());

        GameEntity gameEntity = concernEntity.getGame().toGameEntity();
        GameItemViewHolder.initGameSubtitle(gameEntity, viewHolder.binding.gameSubtitleTv, null, null, false, null);
        NewsUtils.setNewsPublishOn(viewHolder.binding.newsDigestTime, concernEntity.getTime());

        if ("libao".equals(concernEntity.getType())) {
            String content;
            if (concernEntity.getContent().contains("<br/>")) {
                content = concernEntity.getContent().replaceAll("<br/>", " ");
            } else {
                content = concernEntity.getContent();
            }

            viewHolder.binding.newsDigestLlImg.removeAllViews();

            if (TextUtils.isEmpty(concernEntity.getPlatform())) {
                viewHolder.binding.newsDigestContent.setText(StringUtils.buildString(concernEntity.getName(), "\n礼包内容：", content));
            } else {
                viewHolder.binding.newsDigestContent.setText(StringUtils.buildString(concernEntity.getName(), "（限", PlatformUtils.getInstance(mContext)
                        .getPlatformName(concernEntity.getPlatform()), "版）\n礼包内容：", content));
            }
            viewHolder.binding.newsDigestLlImg.setVisibility(View.GONE);
            viewHolder.binding.newsDigestHint.setImageResource(R.drawable.ic_libao);
            viewHolder.binding.newsDigestCountContainer.setVisibility(View.GONE);
            viewHolder.binding.newsDigestLibaoHint.setVisibility(View.VISIBLE);

            for (LibaoStatusEntity libaoStatusEntity : libaoStatusList) {
                if (TextUtils.isEmpty(libaoStatusEntity.getBeforeStatus())) {
                    libaoStatusEntity.setBeforeStatus(libaoStatusEntity.getStatus());
                }

                if (libaoStatusEntity.getId().equals(concernEntity.getId())) {
                    if ("finish".equals(libaoStatusEntity.getStatus())) {
                        viewHolder.binding.newsDigestLibaoHint.setText(R.string.libao_finish);
                    } else {
                        viewHolder.binding.newsDigestLibaoHint.setText("点击查看");
                    }
                    MeEntity userData = concernEntity.getMe();
                    if (userData != null && userData.getUserDataLibaoList() != null && userData.getUserDataLibaoList().size() > 0) {
                        List<UserDataLibaoEntity> userDataLibaoList = userData.getUserDataLibaoList();
                        UserDataLibaoEntity userDataLibaoEntity = userDataLibaoList.get(userDataLibaoList.size() - 1);
                        libaoStatusEntity.setBeforeStatus(libaoStatusEntity.getStatus());
                        if ("ling".equals(userDataLibaoEntity.getType())) { // 拿最后一次领取的状态判断
                            libaoStatusEntity.setStatus("linged");
                            viewHolder.binding.newsDigestLibaoHint.setText(R.string.libao_linged);
                        } else {
                            libaoStatusEntity.setStatus("taoed");
                            viewHolder.binding.newsDigestLibaoHint.setText(R.string.libao_taoed);
                        }
                        libaoStatusEntity.setCode(userDataLibaoEntity.getCode());
                    }
                }
            }
            return;
        }

        viewHolder.binding.newsDigestCountContainer.setVisibility(View.VISIBLE);
        viewHolder.binding.newsDigestLibaoHint.setVisibility(View.GONE);

        if (concernEntity.getLink() != null) {
            viewHolder.binding.newsDigestHint.setImageResource(R.drawable.ic_link);
        } else {
            viewHolder.binding.newsDigestHint.setImageResource(R.drawable.concern_message_icon);
        }
        if (concernEntity.getBrief() != null) {
            viewHolder.binding.newsDigestContent.setText(Html.fromHtml(concernEntity.getBrief()));
            viewHolder.binding.newsDigestContent.setMaxLines(100);
        } else {
            viewHolder.binding.newsDigestContent.setText(Html.fromHtml(concernEntity.getContent()));
            viewHolder.binding.newsDigestContent.setMaxLines(5);
        }

        if (concernEntity.getImg().isEmpty()) {
            viewHolder.binding.newsDigestLlImg.setVisibility(View.GONE);
            viewHolder.binding.newsDigestLlImg.removeAllViews();
        } else {
            viewHolder.binding.newsDigestLlImg.setVisibility(View.VISIBLE);
            viewHolder.binding.newsDigestLlImg.removeAllViews();
            ConcernContentUtils.addContentPic(mContext, viewHolder.binding.newsDigestLlImg, concernEntity.getImg(), "(资讯-关注)",
                    mContext.getResources().getDisplayMetrics().widthPixels - DisplayUtils.dip2px(mContext, 34));
        }

        int views = concernEntity.getViews();
        viewHolder.binding.newsDigestReadIcon.setVisibility(View.VISIBLE);
        viewHolder.binding.newsDigestReadNum.setText(NumberUtils.transSimpleCount(views));

        int commentnum = concernEntity.getCommentnum();
        viewHolder.binding.newsDigestCommentnum.setVisibility(View.VISIBLE);
        viewHolder.binding.newsDigestCommentnum.setText(NumberUtils.transSimpleCount(commentnum));

    }

    private void initFooterViewHolder(FooterViewHolder viewHolder) {
        viewHolder.initItemPadding();
        viewHolder.initFooterViewHolder(isLoading, isNetworkError, isOver, v -> {
            if (isNetworkError) {
                isNetworkError = false;
                notifyItemChanged(getItemCount() - 1);
                addList();
            }
        });
    }

    // 统计新闻阅读量
    public void statNewsViews(final ConcernEntity concernEntity, final int position) {
        RetrofitManager.getInstance().getApi().postArticleVisit(concernEntity.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new JSONObjectResponse() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response.length() != 0) {
                            try {
                                if ("success".equals(response.getString("status"))) {
                                    concernEntity.setViews(concernEntity.getViews() + 1);

                                    notifyItemChanged(position);

                                    // 更新okhttp缓存数据
                                    VisitManager.updateOkhttpCache(mContext, concernEntity.getId());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }


    public int getConcernListSize() {
        return concernList.size();
    }

    public ConcernEntity getSkipEntity() {
        if (skipPosition != -1) {
            return concernList.get(skipPosition);
        }
        return null;
    }

    public List<LibaoStatusEntity> getLibaoStatusList() {
        return libaoStatusList;
    }

    public boolean isNetworkError() {
        return isNetworkError;
    }

    public void setNetworkError(boolean networkError) {
        isNetworkError = networkError;
    }

    public boolean isOver() {
        return isOver;
    }

    public boolean isLoading() {
        return isLoading;
    }

    public int getSkipPosition() {
        return skipPosition;
    }

    public void setSkipPosition(int skipPosition) {
        this.skipPosition = skipPosition;
    }
}
