package com.gh.gamecenter.newsdetail;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.text.Layout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

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

import com.gh.common.DefaultUrlHandler;
import com.gh.common.databind.BindingAdapters;
import com.gh.common.history.HistoryHelper;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.CommentUtils;
import com.gh.common.util.DataCollectionUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DirectUtils;
import com.gh.common.util.NewsUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.view.RichEditor;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.ImageViewerActivity;
import com.gh.gamecenter.MessageDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.CommentViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameDetailNewsViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsDetailCommentListViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsDetailGameViewHolder;
import com.gh.gamecenter.adapter.viewholder.UnAvaliableWebviewViewHolder;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.DarkModeUtils;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.TextHelper;
import com.gh.gamecenter.common.view.DrawableView;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.NumberUtils;
import com.gh.gamecenter.core.utils.RandomUtils;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.databinding.FragmentWebWarningBinding;
import com.gh.gamecenter.databinding.GamedetailItemNewsBinding;
import com.gh.gamecenter.databinding.NewsDetailCommentBinding;
import com.gh.gamecenter.databinding.NewsdetailItemContentBinding;
import com.gh.gamecenter.databinding.NewsdetailItemGameBinding;
import com.gh.gamecenter.entity.NewsDetailEntity;
import com.gh.gamecenter.feature.entity.ApkEntity;
import com.gh.gamecenter.feature.entity.ArticleCommentParent;
import com.gh.gamecenter.feature.entity.ColorEntity;
import com.gh.gamecenter.feature.entity.CommentEntity;
import com.gh.gamecenter.feature.entity.CommentnumEntity;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.feature.eventbus.EBDeleteComment;
import com.gh.gamecenter.feature.utils.ConcernUtils;
import com.gh.gamecenter.qa.editor.OnLinkClickListener;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.adapter.BaseRecyclerAdapter;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

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

/**
 * Created by LGT on 2016/9/13.
 * 新闻详情数据适配器
 */
public class NewsDetailAdapter extends BaseRecyclerAdapter<ViewHolder> {

    private ArrayList<String> mNewsImgs = new ArrayList<>();

    private OnRequestCallBackListener mListener;

    private List<CommentEntity> mCommentEntityList;
    private GameEntity mGameEntity;
    private NewsDetailEntity mNewsDetailEntity;

    private WebSettings mWebSettings;

    private RichEditor mRichEditor;

    private String mId;
    private String mType;
    private String mTitle;
    private String mEntrance;

    private boolean mIsHotComment;
    private boolean mHideUselessInfo;

    private int defaultTextZoom = 85;

    private int mCommentNum;

    public NewsDetailAdapter(Context context, OnRequestCallBackListener listener, boolean hideUselessInfo, String entrance) {
        super(context);
        mListener = listener;
        mEntrance = entrance;
        mHideUselessInfo = hideUselessInfo;
    }

    public void getNewsDetail() {
        RetrofitManager.getInstance().getApi().getNewsDetail(mId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<NewsDetailEntity>() {
                    @Override
                    public void onResponse(NewsDetailEntity response) {
                        mNewsDetailEntity = response;
                        mNewsDetailEntity.setId(mId);
                        mNewsDetailEntity.setType(mType);
                        mNewsDetailEntity.setTitle(mTitle);

                        mListener.loadDone(); // 通知更新收藏按钮

                        notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        if (e != null && e.code() == 404) {
                            mListener.loadNotFound();
                            HistoryHelper.deleteNewsEntity(mId);
                        } else {
                            mListener.loadError();
                        }

                    }
                });
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case 0:
                boolean isWebViewInstalled = PackageUtils.checkWebViewIsAvailable(mContext);
                if (isWebViewInstalled) {
                    return new NewsDetailContentViewHolder(NewsdetailItemContentBinding.inflate(mLayoutInflater, parent, false));
                } else {
                    FragmentWebWarningBinding binding = FragmentWebWarningBinding.inflate(mLayoutInflater, parent, false);
                    return new UnAvaliableWebviewViewHolder(binding);
                }
            case 1:
                return new NewsDetailGameViewHolder(NewsdetailItemGameBinding.inflate(mLayoutInflater, parent, false));
            case 2:
                return new GameDetailNewsViewHolder(GamedetailItemNewsBinding.inflate(mLayoutInflater, parent, false));
            case 100:
                return new NewsDetailCommentListViewHolder(NewsDetailCommentBinding.inflate(mLayoutInflater, parent, false));
            default:
                return null;
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof NewsDetailContentViewHolder) {
            initNewsDetailContentViewHolder((NewsDetailContentViewHolder) holder);
        } else if (holder instanceof NewsDetailGameViewHolder) {
            initGameViewHolder((NewsDetailGameViewHolder) holder);
        } else if (holder instanceof GameDetailNewsViewHolder) {
            initNewsDetailNewsViewHolder((GameDetailNewsViewHolder) holder);
            ((GameDetailNewsViewHolder) holder).binding.gamedetailItemNewsTitle.setText("大家都在看");
        } else if (holder instanceof NewsDetailCommentListViewHolder) {
            initNewsDetailNewsCommentViewHolder((NewsDetailCommentListViewHolder) holder);
        } else if (holder instanceof UnAvaliableWebviewViewHolder) {
            ((UnAvaliableWebviewViewHolder) holder).bindView(480f);
            if (mCommentEntityList == null) {
                mListener.loadDone(mNewsDetailEntity.getGameId());
                getNewsMore();
            }
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1 && mGameEntity != null && mGameEntity.getId() != null
                && !mGameEntity.getId().isEmpty() && mCommentEntityList != null && mCommentEntityList.size() != 0) {
            return 100;
        }
        if (mGameEntity != null && position == 1) {
            return 1;
        } else if (mGameEntity == null && position == 1) {
            return 2;
        }
        return position;
    }

    @Override
    public int getItemCount() {
        if (mNewsDetailEntity == null) {
            return 0;
        }
        int count = 1;
        if (mGameEntity != null) {
            count++;
        }
        if (mGameEntity != null && mGameEntity.getId() != null && !mGameEntity.getId().isEmpty()
                && mCommentEntityList != null && mCommentEntityList.size() != 0) {
            count++;
        }
        if (!mHideUselessInfo) {
            if (mNewsDetailEntity.getMore() != null && mNewsDetailEntity.getMore().size() != 0) {
                count++;
            }
        }
        return count;
    }

    private void initNewsDetailContentViewHolder(NewsDetailContentViewHolder viewHolder) {
        viewHolder.binding.getRoot().setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_surface));
        viewHolder.binding.newsdetailItemTvTitle.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_black));
        viewHolder.binding.newsdetailItemTvTime.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.hint));
        viewHolder.binding.newsdetailItemTvAuthor.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.hint));
        viewHolder.binding.newsdetailItemTvTitle.setText(mNewsDetailEntity.getTitle());

        if (mHideUselessInfo) {
            viewHolder.binding.newsdetailItemTvTime.setVisibility(View.GONE);
        }
        NewsUtils.setNewsPublishOn(viewHolder.binding.newsdetailItemTvTime, mNewsDetailEntity.getTime());

        if (!TextUtils.isEmpty(mNewsDetailEntity.getAuthor())) {
            if (mHideUselessInfo) {
                viewHolder.binding.newsdetailItemTvAuthor.setVisibility(View.GONE);
            }
            viewHolder.binding.newsdetailItemTvAuthor.setText(mNewsDetailEntity.getAuthor());
        }

        mRichEditor = viewHolder.binding.newsdetailItemWvContent;
        if (viewHolder.binding.newsdetailItemWvContent.getTag() == null) {
            viewHolder.binding.newsdetailItemWvContent.setOnLinkClickListener(new OnLinkClickListener(mContext, mEntrance, "", mNewsDetailEntity.getTitle(), "新闻详情"));
            viewHolder.binding.newsdetailItemWvContent.setImageListener(new ImageListener(viewHolder.binding.newsdetailItemWvContent));
            mWebSettings = viewHolder.binding.newsdetailItemWvContent.getSettings();
            mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
            mWebSettings.setTextZoom(defaultTextZoom + sp.getInt(Constants.SP_FONT_SIZE, 1) * 15);
            ExtensionsKt.enableForceDark(viewHolder.binding.newsdetailItemWvContent, DarkModeUtils.INSTANCE.isDarkModeOn(mContext));
            ExtensionsKt.setTransparentBackground(viewHolder.binding.newsdetailItemWvContent);
            viewHolder.binding.newsdetailItemWvContent.setHtml(mNewsDetailEntity.getContent(), true);
//            viewHolder.binding.newsdetailItemWvContent.initArticleVideo();
            viewHolder.binding.newsdetailItemWvContent.setInputEnabled(false);
            viewHolder.binding.newsdetailItemWvContent.setChromeClientListener(new RichEditor.WebChromeClientListener() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    mListener.loadDone(mNewsDetailEntity.getGameId());
                    // 获取相关推荐
                    getNewsMore();
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (mHideUselessInfo) {
                        DirectUtils.directToWebView(mContext, url, "新闻详情");
                        return true;
                    }

                    boolean b = DefaultUrlHandler.transformNormalScheme(mContext, url, StringUtils.buildString(mEntrance, "+(新闻详情[", mNewsDetailEntity.getTitle(), "])"), "");
                    if (!b) {
                        return DefaultUrlHandler.interceptUrl(mContext, url, StringUtils.buildString(mEntrance, "+(新闻详情[", mNewsDetailEntity.getTitle(), "])"), "");
                    }

                    return true;
                }
            });
            viewHolder.binding.newsdetailItemWvContent.setTag("show");
        }
    }

    private void initGameViewHolder(final NewsDetailGameViewHolder viewHolder) {
        viewHolder.binding.getRoot().setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_surface));
        viewHolder.binding.gameTvName.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_black));
        viewHolder.binding.gameServerType.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_white));
        viewHolder.binding.gameTvInfo.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.hint));
        viewHolder.binding.gameTvConcern.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_white));
        viewHolder.binding.gameTvConcern.setBackground(ContextCompat.getDrawable(mContext, R.drawable.textview_blue_style));

        BindingAdapters.setGame(viewHolder.binding.gameIvThumb, mGameEntity);
        viewHolder.binding.gameTvName.setText(mGameEntity.getName());
        if (mGameEntity.getApk() != null && mGameEntity.getApk().size() != 0) {
            for (int i = 0, size = mGameEntity.getApk().size(); i < size; i++) {
                ApkEntity apkEntity = mGameEntity.getApk().get(i);
                if ("9u".equals(apkEntity.getPlatform())) {
                    viewHolder.binding.gameTvInfo.setText(String.format("V%s | %s", apkEntity.getVersion(), apkEntity.getSize()));
                    break;
                }
                if (i == size - 1) {
                    viewHolder.binding.gameTvInfo.setText(String.format("V%s | %s", apkEntity.getVersion(), apkEntity.getSize()));
                }
            }
        }
        if (mNewsDetailEntity.getMe() != null && mNewsDetailEntity.getMe().isGameConcerned()) {
            viewHolder.binding.gameTvConcern.setText(R.string.cancel_concern);
            viewHolder.binding.gameTvConcern.setBackgroundResource(R.drawable.button_normal_border);
            viewHolder.binding.gameTvConcern.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
        } else {
            viewHolder.binding.gameTvConcern.setText(com.gh.gamecenter.feature.R.string.concern);
            viewHolder.binding.gameTvConcern.setBackgroundResource(R.drawable.button_normal_style);
            viewHolder.binding.gameTvConcern.setTextColor(Color.WHITE);
        }

        ColorEntity serverLabel = mGameEntity.getServerLabel();
        if (serverLabel != null) {
            viewHolder.binding.gameServerType.setVisibility(View.INVISIBLE);
            viewHolder.binding.gameServerType.setText(serverLabel.getValue());
            viewHolder.binding.gameServerType.setBackground(DrawableView.getServerDrawable(serverLabel.getColor()));
        } else {
            viewHolder.binding.gameServerType.setVisibility(View.GONE);
        }

        viewHolder.binding.gameTvName.post(() -> {
            if (viewHolder.binding.gameServerType.getVisibility() == View.INVISIBLE) {
                int nameWidth = viewHolder.binding.gameTvName.getWidth();
                int typeWidth = viewHolder.binding.gameServerType.getWidth();

                Layout layout = viewHolder.binding.gameTvName.getLayout();
                if (layout != null) {
                    float lineRight = layout.getLineRight(layout.getLineCount() - 1);
                    int margin = DisplayUtils.dip2px(2);
                    if (nameWidth - lineRight > typeWidth + margin) {
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) viewHolder.binding.gameServerType.getLayoutParams();
                        layoutParams.leftMargin = (int) (lineRight + margin);
                        viewHolder.binding.gameServerType.setLayoutParams(layoutParams);
                    } else {
                        viewHolder.binding.gameTvName.setMinLines(layout.getLineCount() + 1);
                    }
                    viewHolder.binding.gameServerType.setVisibility(View.VISIBLE);
                }
            }
        });

        viewHolder.binding.gameTvConcern.setOnClickListener(v -> {
            final TextView concern = ((TextView) v);
            CheckLoginUtils.checkLogin(mContext, "资讯文章详情-[关注]游戏", () -> {
                String str = concern.getText().toString();
                viewHolder.binding.gameTvConcern.setEnabled(false);
                if (mContext.getString(com.gh.gamecenter.feature.R.string.concern).equals(str)) {
                    // 添加关注
                    ConcernUtils.INSTANCE.postConcernGameId(mGameEntity.getId()
                            , new ConcernUtils.OnConcernListener() {
                                @Override
                                public void onSuccess() {
                                    DataCollectionUtils.uploadConcern(mContext, mGameEntity.getName(), mGameEntity.getId(), mContext.getString(com.gh.gamecenter.feature.R.string.concern));

                                    concern.setText(R.string.cancel_concern);
                                    concern.setBackgroundResource(R.drawable.button_normal_border);
                                    concern.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));

                                    Utils.toast(mContext, com.gh.gamecenter.feature.R.string.concern_success);
                                    viewHolder.binding.gameTvConcern.setEnabled(true);
                                }

                                @Override
                                public void onError() {
                                    Utils.toast(mContext, com.gh.gamecenter.feature.R.string.concern_failure);
                                    viewHolder.binding.gameTvConcern.setEnabled(true);
                                }
                            }, false);
                } else {
                    DialogHelper.showCancelDialog(mContext, () -> {
                        //取消关注
                        ConcernUtils.INSTANCE.deleteConcernData(mGameEntity.getId()
                                , new ConcernUtils.OnConcernListener() {
                                    @Override
                                    public void onSuccess() {
                                        DataCollectionUtils.uploadConcern(mContext,
                                                mGameEntity.getName(), mGameEntity.getId(), mContext.getString(R.string.cancel_concern));

                                        concern.setText(mContext.getString(com.gh.gamecenter.feature.R.string.concern));
                                        concern.setBackgroundResource(R.drawable.button_normal_style);
                                        concern.setTextColor(Color.WHITE);
                                        viewHolder.binding.gameTvConcern.setEnabled(true);
                                    }

                                    @Override
                                    public void onError() {
                                        Utils.toast(mContext, R.string.cancel_concern_failure);
                                        viewHolder.binding.gameTvConcern.setEnabled(true);
                                    }
                                });
                        return null;
                    }, () -> {
                        viewHolder.binding.gameTvConcern.setEnabled(true);
                        return null;
                    });
                }
            });
        });
        viewHolder.binding.getRoot().setOnClickListener(v -> {
            DataCollectionUtils.uploadClick(mContext, "游戏信息", "新闻详情", mNewsDetailEntity.getTitle());

            GameDetailActivity.startGameDetailActivity(mContext, mGameEntity.getId(), mEntrance + "+(新闻详情[" + mNewsDetailEntity.getTitle() + "])", null);
        });
    }

    private void initNewsDetailNewsViewHolder(GameDetailNewsViewHolder viewHolder) {
        viewHolder.binding.getRoot().setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_surface));
        viewHolder.binding.gamedetailItemLineNews1.setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.cutting_line));
        viewHolder.binding.gamedetailItemLineNews2.setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.cutting_line));
        viewHolder.binding.gamedetailItemLineNews3.setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.cutting_line));
        viewHolder.binding.gamedetailItemNews1.setBackground(ContextCompat.getDrawable(mContext, com.gh.gamecenter.common.R.drawable.reuse_listview_item_style));
        viewHolder.binding.gamedetailItemNews2.setBackground(ContextCompat.getDrawable(mContext, com.gh.gamecenter.common.R.drawable.reuse_listview_item_style));
        viewHolder.binding.gamedetailItemNews3.setBackground(ContextCompat.getDrawable(mContext, com.gh.gamecenter.common.R.drawable.reuse_listview_item_style));
        viewHolder.binding.gamedetailItemNewsType1.setBackground(ContextCompat.getDrawable(mContext, R.drawable.button_normal_border));
        viewHolder.binding.gamedetailItemNewsType2.setBackground(ContextCompat.getDrawable(mContext, R.drawable.button_normal_border));
        viewHolder.binding.gamedetailItemNewsType3.setBackground(ContextCompat.getDrawable(mContext, R.drawable.button_normal_border));
        viewHolder.binding.gamedetailItemNewsTitle.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_black));
        viewHolder.binding.allTv.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
        viewHolder.binding.gamedetailItemNewsType1.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_white));
        viewHolder.binding.gamedetailItemNewsTitle1.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_3a3a3a));
        viewHolder.binding.gamedetailItemNewsType2.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_white));
        viewHolder.binding.gamedetailItemNewsTitle2.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_3a3a3a));
        viewHolder.binding.gamedetailItemNewsType3.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_white));
        viewHolder.binding.gamedetailItemNewsTitle3.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_3a3a3a));

        final List<NewsEntity> newsList = mNewsDetailEntity.getMore();

        // 有点乱 先在这么做点击事件
        View.OnClickListener onClickListener = view -> {
            int newPosition = -1;
            switch (view.getId()) {
                case R.id.gamedetail_item_news1:
                    newPosition = 0;
                case R.id.gamedetail_item_news2:
                    if (newPosition == -1) newPosition = 1;
                case R.id.gamedetail_item_news3:
                    if (newPosition == -1) newPosition = 2;
                    break;
            }
            NewsEntity newsEntity = newsList.get(newPosition);
            DataCollectionUtils.uploadClick(mContext, "相关推荐", "新闻详情", newsEntity.getTitle());

            // 统计阅读量
            NewsUtils.statNewsViews(newsEntity.getId());
            NewsDetailActivity.startNewsDetailActivity(mContext, newsEntity
                    , StringUtils.buildString(mEntrance, "+(新闻详情[", mTitle, "]:相关推荐[", String.valueOf(newPosition + 1), "])"));
        };

        viewHolder.binding.gamedetailItemNewsMore.setVisibility(View.GONE);
        for (int i = 0; i < newsList.size(); i++) {
            NewsEntity newsEntity = newsList.get(i);
            switch (i) {
                case 0:
                    viewHolder.binding.gamedetailItemLineNews1.setVisibility(View.VISIBLE);
                    viewHolder.binding.gamedetailItemNews1.setVisibility(View.VISIBLE);
                    viewHolder.binding.gamedetailItemNews1.setOnClickListener(onClickListener);
                    viewHolder.binding.gamedetailItemNewsTitle1.setText(newsEntity.getTitle());
                    NewsUtils.setNewsType(viewHolder.binding.gamedetailItemNewsType1, newsEntity.getType(), 0, 0);
                    break;
                case 1:
                    viewHolder.binding.gamedetailItemLineNews2.setVisibility(View.VISIBLE);
                    viewHolder.binding.gamedetailItemNews2.setVisibility(View.VISIBLE);
                    viewHolder.binding.gamedetailItemNews2.setOnClickListener(onClickListener);
                    viewHolder.binding.gamedetailItemNewsTitle2.setText(newsEntity.getTitle());
                    NewsUtils.setNewsType(viewHolder.binding.gamedetailItemNewsType2, newsEntity.getType(), 0, 0);
                    break;
                case 2:
                    viewHolder.binding.gamedetailItemLineNews3.setVisibility(View.VISIBLE);
                    viewHolder.binding.gamedetailItemNews3.setVisibility(View.VISIBLE);
                    viewHolder.binding.gamedetailItemNews3.setOnClickListener(onClickListener);
                    viewHolder.binding.gamedetailItemNewsTitle3.setText(newsEntity.getTitle());
                    NewsUtils.setNewsType(viewHolder.binding.gamedetailItemNewsType3, newsEntity.getType(), 0, 0);
                    break;
            }
        }
    }

    private void initNewsDetailNewsCommentViewHolder(final NewsDetailCommentListViewHolder holder) {
        holder.binding.getRoot().setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_surface));
        holder.binding.newsdetailCommentLine.setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.cutting_line));
        holder.binding.newsdetailCommentTitle.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_3a3a3a));

        AtomicBoolean isChildLongClick = new AtomicBoolean(false);
        holder.binding.newsdetailCommentList.removeAllViews();
        if (mIsHotComment) {
            holder.binding.newsdetailCommentTitle.setText(R.string.comment_hot);
        } else {
            holder.binding.newsdetailCommentTitle.setText(R.string.comment_new);
        }

        for (final CommentEntity commentEntity : mCommentEntityList) {
            View contentView = mLayoutInflater.inflate(R.layout.comment_item, null);
            final CommentViewHolder viewHolder = new CommentViewHolder(contentView);

            viewHolder.commentLikeCountTv.setText(NumberUtils.transSimpleCount(commentEntity.getVote()));
            holder.binding.newsdetailCommentList.addView(contentView);

            TextHelper.highlightTextThatIsWrappedInsideWrapperByDefault(
                    viewHolder.commentContentTv,
                    commentEntity.getContent(),
                    Constants.DEFAULT_TEXT_WRAPPER,
                    new TextHelper.DirectToWebViewHighlightedTextClick(mContext, mEntrance)
            );
            ArticleCommentParent parent = commentEntity.getParent();
            if (parent != null && !TextUtils.isEmpty(parent.getUser().getName())) {
                viewHolder.quoteContainer.setVisibility(View.VISIBLE);
                viewHolder.quoteAuthorTv.setText(String.format("@%s", parent.getUser().getName()));
                if (commentEntity.getParent().getUser().getBadge() != null) {
                    viewHolder.quoteAuthorBadgeSdv.setVisibility(View.VISIBLE);
                    ImageUtils.display(viewHolder.quoteAuthorBadgeSdv, commentEntity.getParent().getUser().getBadge().getIcon());
                } else {
                    viewHolder.quoteAuthorBadgeSdv.setVisibility(View.GONE);
                }
                String content;
                if (parent.getActive()) {
                    content = parent.getComment();
                    viewHolder.quoteContentTv.setTextColor(mContext.getResources().getColor(com.gh.gamecenter.common.R.color.text_5d5d5d));
                } else {
                    content = mContext.getString(R.string.comment_hide_hint);
                    viewHolder.quoteContentTv.setTextColor(mContext.getResources().getColor(com.gh.gamecenter.common.R.color.text_d5d5d5));
                }

                TextHelper.highlightTextThatIsWrappedInsideWrapperByDefault(
                        viewHolder.quoteContentTv,
                        content,
                        Constants.DEFAULT_TEXT_WRAPPER,
                        new TextHelper.DirectToWebViewHighlightedTextClick(mContext, mEntrance)
                );
            } else {
                viewHolder.quoteContainer.setVisibility(View.GONE);
            }

            if (commentEntity.getPriority() != 0) {
                viewHolder.commentBadge.setVisibility(View.VISIBLE);
            } else {
                viewHolder.commentBadge.setVisibility(View.GONE);
            }

            NewsUtils.setNewsDetailTime(viewHolder.commentTimeTv, commentEntity.getTime());
            if (commentEntity.getSource() != null && !commentEntity.getSource().getRegion().isEmpty()) {
                viewHolder.commentTimeTv.setText(viewHolder.commentTimeTv.getText() + " · " + commentEntity.getSource().getRegion());
            }

            CommentUtils.setCommentUserView(mContext, viewHolder, commentEntity);

            viewHolder.commentLikeContainer.setOnClickListener(v ->
                    CheckLoginUtils.checkLogin(mContext, "资讯文章详情-评论-点赞",
                            () -> CommentUtils.postVote(mContext, commentEntity,
                                    viewHolder.commentLikeCountTv,
                                    viewHolder.commentLikeIv, null)));

            // 资讯文章详情回复 直接跳转至评论详情
            viewHolder.itemView.setOnClickListener(v -> {
                if (isChildLongClick.get()) {
                    isChildLongClick.set(false);
                    return;
                }
                if (viewHolder.commentReply.getVisibility() == View.VISIBLE) {
                    CheckLoginUtils.checkLogin(mContext, "资讯文章详情-评论-回复", () -> {
                        mContext.startActivity(MessageDetailActivity.getMessageDetailIntent(mContext, commentEntity, mNewsDetailEntity.getId()));
                    });
                }
            });
            viewHolder.commentContentTv.setOnLongClickListener(v -> {
                isChildLongClick.set(true);
                ExtensionsKt.copyTextAndToast(viewHolder.commentContentTv.getText().toString(), "复制成功");
                return true;
            });
            viewHolder.quoteContentTv.setOnLongClickListener(v -> {
                isChildLongClick.set(true);
                ExtensionsKt.copyTextAndToast(viewHolder.quoteContentTv.getText().toString(), "复制成功");
                return true;
            });
            viewHolder.commentMore.setOnClickListener(v ->
                    CommentUtils.showMorePopupWindow(
                            viewHolder.commentMore,
                            commentEntity,
                            true,
                            "资讯文章详情-评论",
                            () -> {
                                EventBus.getDefault().post(new EBDeleteComment(commentEntity));
                            }
                    )
            );

            viewHolder.commentUserNameTv.setOnClickListener(v -> DirectUtils.directToHomeActivity(mContext, commentEntity.getUser().getId(), mEntrance, "文章-评论列表"));
            viewHolder.commentUserIconDv.setOnClickListener(v -> DirectUtils.directToHomeActivity(mContext, commentEntity.getUser().getId(), mEntrance, "文章-评论列表"));

            viewHolder.userBadgeSdv.setOnClickListener(v -> {
                DialogUtils.showViewBadgeDialog(mContext, commentEntity.getUser().getBadge(),
                        () -> {
                            MtaHelper.onEvent("进入徽章墙_用户记录", "资讯文章-评论详情", commentEntity.getUser().getName() + "（" + commentEntity.getUser().getId() + "）");
                            MtaHelper.onEvent("徽章中心", "进入徽章中心", "资讯文章-评论详情");
                            DirectUtils.directToBadgeWall(mContext, commentEntity.getUser().getId(), commentEntity.getUser().getName(), commentEntity.getUser().getIcon());
                        });
            });
            viewHolder.badgeNameTv.setOnClickListener(v -> viewHolder.userBadgeSdv.performClick());
            viewHolder.quoteAuthorBadgeSdv.setOnClickListener(v -> {
                DialogUtils.showViewBadgeDialog(mContext, commentEntity.getParent().getUser().getBadge(),
                        () -> {
                            MtaHelper.onEvent("进入徽章墙_用户记录", "资讯文章-评论详情", commentEntity.getParent().getUser().getName() + "（" + commentEntity.getParent().getUser().getId() + "）");
                            MtaHelper.onEvent("徽章中心", "进入徽章中心", "资讯文章-评论详情");
                            DirectUtils.directToBadgeWall(mContext, commentEntity.getParent().getUser().getId(), commentEntity.getParent().getUser().getName(), commentEntity.getParent().getUser().getIcon());
                        });
            });
        }

        LinearLayout linearLayout = new LinearLayout(mContext);
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                , ViewGroup.LayoutParams.WRAP_CONTENT));
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        View view = new View(mContext);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                , DisplayUtils.dip2px(mContext, 1));
        view.setLayoutParams(params);
        view.setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.cutting_line));
        linearLayout.addView(view);

        TextView textView = new TextView(mContext);
        textView.setGravity(Gravity.CENTER);
        textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                , ViewGroup.LayoutParams.WRAP_CONTENT));
        textView.setText(("查看全部评论（" + NumberUtils.transSimpleCount(mCommentNum) + "）"));
        textView.setPadding(0, DisplayUtils.dip2px(mContext, 12), 0, DisplayUtils.dip2px(mContext, 12));
        textView.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
        textView.setTextSize(15);
        linearLayout.addView(textView);

        holder.binding.newsdetailCommentList.addView(linearLayout);

        linearLayout.setOnClickListener(v -> {
            Intent intent = MessageDetailActivity.getIntentById(mContext, mId, null, null, mEntrance + "+(新闻详情[" + mTitle + "])");
            mContext.startActivity(intent);
        });
    }

    private void getNewsMore() {
        RetrofitManager.getInstance().getApi().getNewsSuggestion(mNewsDetailEntity.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<NewsEntity>>() {
                    @Override
                    public void onResponse(List<NewsEntity> response) {
                        // 去除与当前文章重复的文章
                        for (int i = 0, size = response.size(); i < size; i++) {
                            if (mNewsDetailEntity.getId().equals(response.get(i).getId())) {
                                response.remove(i);
                                break;
                            }
                        }
                        if (response.size() != 0) {
                            List<NewsEntity> more = new ArrayList<>();
                            // 随机三篇文章
                            int[] index = RandomUtils.getRandomArray(response.size() > 3 ? 3 : response.size(), response.size());
                            for (int i : index) {
                                more.add(response.get(i));
                            }
                            mNewsDetailEntity.setMore(more);
                            notifyItemInserted(getItemCount() - 1);
                        }

                        getNewsCommentNum();
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        getNewsCommentNum();
                    }
                });
    }

    public void getNewsCommentNum() {
        RetrofitManager.getInstance().getApi()
                .getNewsCommentnum(mNewsDetailEntity.getId(), Utils.getTime(mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<CommentnumEntity>>() {

                    @Override
                    public void onResponse(List<CommentnumEntity> response) {
                        mCommentNum = response.get(0).getNum();
                        getNewsHotComment();
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        getNewsHotComment();
                    }
                });
    }

    public void getNewsHotComment() {
        RetrofitManager.getInstance().getApi()
                .getHotComment(mId, 3, 0)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<CommentEntity>>() {
                    @Override
                    public void onResponse(List<CommentEntity> response) {
                        if (response.size() >= 3) {
                            mCommentEntityList = response;
                            mIsHotComment = true;
                            notifyDataSetChanged();
                        } else {
                            getNewsComment();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        getNewsComment();
                    }
                });
    }

    private void getNewsComment() {
        RetrofitManager.getInstance().getApi()
                .getComment(mId, 3, 1, Utils.getTime(mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<CommentEntity>>() {
                    @Override
                    public void onResponse(List<CommentEntity> response) {
                        if (response.size() >= 1) {
                            mIsHotComment = false;
                        }
                        mCommentEntityList = response;
                        notifyDataSetChanged();
                    }
                });
    }

    public void setId(String id) {
        this.mId = id;
    }

    public String getId() {
        return mId;
    }

    public String getTitle() {
        return mTitle;
    }

    public void setTitle(String title) {
        this.mTitle = title;
    }

    public void setType(String type) {
        this.mType = type;
    }

    public void setGameEntity(GameEntity gameEntity) {
        this.mGameEntity = gameEntity;
    }

    public NewsDetailEntity getNewsDetailEntity() {
        return mNewsDetailEntity;
    }

    public void setFontSize(int fontsize) {
        if (mWebSettings != null) {
            mWebSettings.setTextZoom(defaultTextZoom + 15 * fontsize);
        }
    }

    public class ImageListener implements RichEditor.ImageListener {
        private RichEditor editor;

        public ImageListener(RichEditor editor) {
            this.editor = editor;
        }

        @Override
        public void onImageClick(String url) {
            if (url.contains("web_load_dfimg_icon.png")) {
                editor.post(() -> editor.replaceAllDfImageExcludeGif());
            } else {
                int current = 0;
                for (int i = 0, size = mNewsImgs.size(); i < size; i++) {
                    if (url.contains(mNewsImgs.get(i))) {
                        current = i;
                    }
                }
                Intent intent = ImageViewerActivity.getIntent(mContext, mNewsImgs, current, mEntrance + "+(新闻详情[" + mTitle + "])");
                if (mContext instanceof Activity) {
                    ((Activity) mContext).startActivityForResult(intent, ImageViewerActivity.REQUEST_FOR_VIEWED_IMAGE);
                }
            }
        }

        @Override
        public void onImageLoad(String url) {
            String defUrl = url.split("\\?")[0];
            //web_load_dfimg_icon.png 查看大图按钮
            if (!mNewsImgs.contains(defUrl) && !url.contains("web_load_dfimg_icon.png")) {
                mNewsImgs.add(defUrl);
            }
        }
    }

    public void replaceDefaultImage(HashSet<Integer> imageSet) {
        // 返回时把点过的图片变为大图
        if (imageSet != null && mNewsImgs != null && mNewsImgs.size() > 0) {
            if (imageSet.size() == mNewsImgs.size()) {
                mRichEditor.replaceAllDfImage();
            } else {
                for (int i : imageSet) {
                    String url = mNewsImgs.get(i);
                    mRichEditor.replaceDfImageByUrl(url);
                }
            }
        }
    }
}
