package com.gh.gamecenter;

import static com.gh.gamecenter.common.constant.Constants.LOGIN_TAG;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.view.MotionEventCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.ViewSkeletonScreen;
import com.gh.base.DownloadToolbarActivity;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.common.history.HistoryHelper;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.CollectionUtils;
import com.gh.common.util.DataCollectionUtils;
import com.gh.common.util.DetailDownloadUtils;
import com.gh.common.util.NewLogUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.adapter.viewholder.DetailViewHolder;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.eventbus.EBNetworkState;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.ShareUtils;
import com.gh.gamecenter.common.view.FixLinearLayoutManager;
import com.gh.gamecenter.common.view.VerticalItemDecoration;
import com.gh.gamecenter.core.utils.ClickUtils;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.entity.NewsDetailEntity;
import com.gh.gamecenter.eventbus.EBConcernChanged;
import com.gh.gamecenter.eventbus.EBAddComment;
import com.gh.gamecenter.eventbus.EBDeleteComment;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.MeEntity;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.feature.utils.ApkActiveUtils;
import com.gh.gamecenter.newsdetail.NewsDetailAdapter;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.lightgame.download.DataWatcher;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.DownloadStatus;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashSet;

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


/**
 * 文章详情页面 要启动该页面 需要传入一下参数 放入 EssayEntity中传过来 文章 id 文章标题 title 文章发表时间 time
 *
 * @author 黄壮华
 */
public class NewsDetailActivity extends DownloadToolbarActivity implements OnClickListener, OnRequestCallBackListener {

    RecyclerView mDetailRv;
    LinearLayout mDetailBottomLl;
    LinearLayout mReuseLoading;
    LinearLayout mNoConn;
    LinearLayout mNoneData;
    LinearLayout mExceptionDataView;
    TextView mNoneDataTv;
    RelativeLayout mDetailCommentLl;
    RelativeLayout mSkeletonView;
    View mCommentContainer;
    View mDownloadContainer;
    View mBottomContainer;

    MenuItem mNewsShare;
    MenuItem mNewsCollection;

    private NewsDetailAdapter adapter;

    private static final String KEY_COLLECTIONNEWS = "isCollectionNews";

    private boolean isSentReport = false;
    private boolean isSecondDown = false;
    private boolean mIsCollectionNews;
    private float Y11, Y12, Y21, Y22;
    private float X11, X12, X21, X22;
    private double R11;
    private int fontsize;
    private int scrollSize = 300;//滑动距离超过300触发事件（放大缩小字体）
    private long start = 0L;

    private String newsId;

    private SharedPreferences sp;

    private GameEntity gameEntity;
    private NewsEntity mNewsEntity;
    private DownloadEntity mDownloadEntity;

    private Boolean mHideUselessInfo = false;  // 是否需要隐藏一些额外的信息（评论按钮等）

    private Handler handler = new Handler();

    private long[] mHits = new long[2];

    private ViewSkeletonScreen mViewSkeletonScreen;

    private RecyclerView.ItemDecoration mItemDecoration;

    private DataWatcher dataWatcher = new DataWatcher() {
        @Override
        public void onDataChanged(DownloadEntity downloadEntity) {
            if (gameEntity != null && gameEntity.getApk().size() == 1) {
                String url = gameEntity.getApk().get(0).getUrl();
                if (url.equals(downloadEntity.getUrl())) {
                    if (!"pause".equals(DownloadManager.getInstance().
                            getStatus(downloadEntity.getUrl()))) {
                        mDownloadEntity = downloadEntity;
                        DetailDownloadUtils.detailInvalidate(getDetailViewHolder());
                    }
                }
            } else if (gameEntity != null && gameEntity.getApk().size() > 1) {
                if (DownloadStatus.downloading.equals(downloadEntity.getStatus())) {
                    if (getDetailViewHolder().mDownloadTips.getVisibility() == View.GONE || !getDetailViewHolder().mDownloadTips.isAnimating()) {
                        getDetailViewHolder().mDownloadTips.setVisibility(View.VISIBLE);
                        ExtensionsKt.setDownloadTipsAnimation(getDetailViewHolder().mDownloadTips, true);
                    }
                } else if (DownloadStatus.waiting.equals(downloadEntity.getStatus()) || DownloadStatus.done.equals(downloadEntity.getStatus()) ||
                        DownloadStatus.pause.equals(downloadEntity.getStatus()) || DownloadStatus.timeout.equals(downloadEntity.getStatus()) ||
                        DownloadStatus.subscribe.equals(downloadEntity.getStatus()) || DownloadStatus.overflow.equals(downloadEntity.getStatus()) ||
                        DownloadStatus.neterror.equals(downloadEntity.getStatus())) {
                    getDetailViewHolder().mDownloadTips.setVisibility(View.VISIBLE);
                    ExtensionsKt.setDownloadTipsAnimation(getDetailViewHolder().mDownloadTips, false);
                } else {
                    getDetailViewHolder().mDownloadTips.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onDataInit(@NonNull DownloadEntity downloadEntity) {
            onDataChanged(downloadEntity);
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (newsId != null) {
                getNewsDigest(newsId);
            } else {
                if (mNewsEntity == null) return;
                if (mNewsEntity.getType() != null) {
                    setNavigationTitle(mNewsEntity.getType());
                }
                adapter.setId(mNewsEntity.getId());
                adapter.setType(mNewsEntity.getType());
                adapter.setTitle(mNewsEntity.getTitle());
                adapter.getNewsDetail();
            }
        }
    };

    private DetailViewHolder getDetailViewHolder() {
        // 每次获取需要重新创建, 防止数据刷新
        return new DetailViewHolder(mContentView, gameEntity, mDownloadEntity,
                true, mEntrance, "新闻详情", adapter.getTitle(), null); // 下载按钮ViewHolder
    }

    /**
     * 启动新闻详情页面
     */
    public static void startNewsDetailActivity(Context context, NewsEntity newsEntity, String entrance) {
        MtaHelper.onEvent("详情页面", "文章详情", newsEntity != null ? newsEntity.getTitle() : "");
        if (newsEntity != null && !TextUtils.isEmpty(newsEntity.getLink())) {
            context.startActivity(WebActivity.getIntentByNews(context, newsEntity, entrance));
        } else {
            Intent intent = new Intent(context, NewsDetailActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(EntranceConsts.KEY_ENTRANCE, entrance);
            intent.putExtra(NewsEntity.TAG, newsEntity);
            context.startActivity(intent);
        }
    }


    /**
     * 在收藏启动新闻详情页面
     */
    public static void startNewsDetailByCollection(Context context, NewsEntity newsEntity, String entrance) {
        MtaHelper.onEvent("详情页面", "文章详情", newsEntity != null ? newsEntity.getTitle() : "");
        if (newsEntity != null && !TextUtils.isEmpty(newsEntity.getLink())) {
            Intent intent = WebActivity.getIntentByNews(context, newsEntity, entrance);
            context.startActivity(intent);
        } else {
            Intent intent = new Intent(context, NewsDetailActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(EntranceConsts.KEY_ENTRANCE, entrance);
            intent.putExtra(NewsEntity.TAG, newsEntity);
            intent.putExtra(KEY_COLLECTIONNEWS, true);
            context.startActivity(intent);
        }

    }

    @NonNull
    public static Intent getIntentById(Context context, String newsId, boolean isCollectionNews, String entrance) {
        Intent intent = new Intent(context, NewsDetailActivity.class);
        intent.putExtra(EntranceConsts.KEY_ENTRANCE, entrance);
        intent.putExtra(KEY_COLLECTIONNEWS, isCollectionNews);
        intent.putExtra(EntranceConsts.KEY_NEWSID, newsId);
        return intent;
    }

    @NonNull
    public static Intent getIntentById(Context context, String newsId, String entrance) {
        Intent intent = new Intent(context, NewsDetailActivity.class);
        intent.putExtra(EntranceConsts.KEY_ENTRANCE, entrance);
        intent.putExtra(EntranceConsts.KEY_NEWSID, newsId);
        return intent;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageViewerActivity.REQUEST_FOR_VIEWED_IMAGE && resultCode == Activity.RESULT_OK) {
            HashSet<Integer> imageSet = (HashSet<Integer>) data.getExtras().get(ImageViewerActivity.VIEWED_IMAGE);
            adapter.replaceDefaultImage(imageSet);
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_news_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExtensionsKt.updateStatusBarColor(this, R.color.background_white, R.color.background_white);

        mDetailRv = findViewById(R.id.news_detail_rv_show);
        mDetailBottomLl = findViewById(R.id.news_detail_ll_bottom);
        mReuseLoading = findViewById(R.id.reuse_ll_loading);
        mNoConn = findViewById(R.id.reuse_no_connection);
        mNoneData = findViewById(R.id.reuse_none_data);
        mExceptionDataView = findViewById(R.id.reuse_data_exception);
        mNoneDataTv = findViewById(R.id.reuseNoneDataTv);
        mDetailCommentLl = findViewById(R.id.news_detail_ll_coment);
        mSkeletonView = findViewById(R.id.news_skeleton);
        mCommentContainer = findViewById(R.id.commentContainer);
        mDownloadContainer = findViewById(R.id.detail_ll_bottom);
        mBottomContainer = findViewById(R.id.bottomContainer);

        mViewSkeletonScreen = Skeleton.bind(mSkeletonView).shimmer(false).load(R.layout.news_detail_skeleton).show();
        // init toolbar
        setNavigationTitle("");
        mNoneDataTv.setText("页面不见了");

        // init RecyclerView
        mDetailRv.setHasFixedSize(true);
        mDetailRv.setLayoutManager(new FixLinearLayoutManager(this));
        mItemDecoration = new VerticalItemDecoration(this, 8, false);
        mDetailRv.addItemDecoration(mItemDecoration);

        mHideUselessInfo = getIntent().getBooleanExtra(EntranceConsts.KEY_HIDE_USELESS_INFO, false);

        setToolbarMenu(R.menu.menu_news_detail);
        mNewsShare = getMenuItem(R.id.menu_share);
        mNewsCollection = getMenuItem(R.id.menu_collect);
        mNewsShare.setVisible(false);
        mNewsCollection.setVisible(false);

        if (mHideUselessInfo) {
            getMenuItem(R.id.menu_download).setVisible(false);
            mCommentContainer.setVisibility(View.GONE);
        }

        adapter = new NewsDetailAdapter(this, this, mHideUselessInfo, mEntrance);
        mDetailRv.setAdapter(adapter);

        newsId = getIntent().getStringExtra(EntranceConsts.KEY_NEWSID);
        mIsCollectionNews = getIntent().getBooleanExtra(KEY_COLLECTIONNEWS, false);

        if (newsId == null) {
            mNewsEntity = getIntent().getParcelableExtra(NewsEntity.TAG);
            if (mNewsEntity != null) {
                if (mNewsEntity.getType() != null) {
                    setNavigationTitle(mNewsEntity.getType());
                }

                HistoryHelper.insertNewsEntity(mNewsEntity);
                adapter.setId(mNewsEntity.getId());
                adapter.setType(mNewsEntity.getType());
                adapter.setTitle(mNewsEntity.getTitle());
                adapter.getNewsDetail();
                if (!mHideUselessInfo) {
                    mNewsShare.setVisible(true);
                    setTitleCenter();
                }
            }
        } else {
            getNewsDigest(newsId);
        }

        start = System.currentTimeMillis();

        View view = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        if (view != null) {
            view.setOnClickListener(v -> {
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                if (mHits[0] >= (SystemClock.uptimeMillis() - 1000)) {
                    mDetailRv.scrollToPosition(0);
                }
            });
        }

        sp = PreferenceManager.getDefaultSharedPreferences(this);
        fontsize = sp.getInt(Constants.SP_FONT_SIZE, 1);
        if (fontsize == 0) {
            fontsize = 1;
        }

        mNoConn.setOnClickListener(this);
        mDetailCommentLl.setOnClickListener(this);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_share:
                if (adapter != null && adapter.getNewsDetailEntity() != null && !ClickUtils.isFastDoubleClick(R.id.menu_question_post)) {
                    DataCollectionUtils.uploadClick(NewsDetailActivity.this, "分享", "新闻详情"
                            , adapter.getNewsDetailEntity().getTitle());

                    String url = getString(R.string.share_news_article_url, adapter.getNewsDetailEntity().getShortId());

                    String shareIcon;
                    if (gameEntity == null) {
                        shareIcon = getString(R.string.gh_icon_url);
                    } else {
                        shareIcon = gameEntity.getIcon();
                    }
                    showShare(url, shareIcon, adapter.getNewsDetailEntity().getTitle(),
                            "来自光环助手（最强卡牌神器）", ShareUtils.ShareEntrance.news, adapter.getNewsDetailEntity().getId());
                }
                break;
            case R.id.menu_collect:
                CheckLoginUtils.checkLogin(this, "资讯文章详情-收藏", () -> {
                    final NewsDetailEntity newsDetailEntity = adapter.getNewsDetailEntity();
                    mNewsCollection.setEnabled(false);
                    if (newsDetailEntity.getMe() != null && newsDetailEntity.getMe().isArticleFavorite()) {
                        CollectionUtils.INSTANCE.deleteCollection(mNewsEntity.getId(),
                                CollectionUtils.CollectionType.ARTICLE,
                                new CollectionUtils.OnCollectionListener() {
                                    @Override
                                    public void onSuccess() {
                                        newsDetailEntity.getMe().setArticleFavorite(false);
                                        mNewsCollection.setEnabled(true);
                                        mNewsCollection.setIcon(R.drawable.community_content_detail_collect_unselect);
                                        toast(R.string.collection_cancel);
                                    }

                                    @Override
                                    public void onError() {
                                        mNewsCollection.setEnabled(true);
                                        toast(R.string.collection_cancel_failure);
                                    }
                                });

                    } else {
                        CollectionUtils.INSTANCE.postCollection(mNewsEntity.getId(),
                                CollectionUtils.CollectionType.ARTICLE,
                                new CollectionUtils.OnCollectionListener() {
                                    @Override
                                    public void onSuccess() {
                                        MeEntity userData = newsDetailEntity.getMe();
                                        if (userData == null) {
                                            userData = new MeEntity();
                                            newsDetailEntity.setMe(userData);
                                        }
                                        userData.setArticleFavorite(true);
                                        mNewsCollection.setEnabled(true);
                                        mNewsCollection.setIcon(R.drawable.community_content_detail_collect_select);
                                        toast(R.string.collection_success);
                                    }

                                    @Override
                                    public void onError() {
                                        mNewsCollection.setEnabled(true);
                                        toast(R.string.collection_failure);
                                    }
                                });
                    }
                });
                break;
        }
        return super.onMenuItemClick(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        DownloadManager.getInstance().removeObserver(dataWatcher);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!isSentReport) {
            long end = System.currentTimeMillis();

            int seconds = (int) ((end - start) / 1000);

            if (adapter.getNewsDetailEntity() != null && seconds > 0) {
                DataCollectionUtils.uploadNews(this, adapter.getNewsDetailEntity(), gameEntity, seconds, mEntrance);
            }

            isSentReport = true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (gameEntity != null
                && (gameEntity.getApk().size() == 1 || gameEntity.isReservable())) {
            DetailDownloadUtils.detailInitDownload(getDetailViewHolder(), true);
        }
        DownloadManager.getInstance().addObserver(dataWatcher);
    }

    @Override
    public void loadDone() { // 通知更新收藏按钮
        if (!mHideUselessInfo) {
            mNewsCollection.setVisible(true);
            setTitleCenter();
            NewsDetailEntity newsDetailEntity = adapter.getNewsDetailEntity();
            if (newsDetailEntity.getMe() != null && newsDetailEntity.getMe().isArticleFavorite()) {
                mNewsCollection.setIcon(R.drawable.community_content_detail_collect_select);
            } else {
                mNewsCollection.setIcon(R.drawable.community_content_detail_collect_unselect);
            }
        }
    }

    @Override
    public void loadDone(Object obj) {
        if (mReuseLoading != null) {
            mReuseLoading.setVisibility(View.GONE);
            mDetailRv.setVisibility(View.VISIBLE);
            mViewSkeletonScreen.hide();
        }
        getGameDetail((String) obj);
    }

    @Override
    public void loadError() {
        mDetailRv.setVisibility(View.GONE);
        mReuseLoading.setVisibility(View.GONE);
        mDetailBottomLl.setVisibility(View.GONE);
        mNoConn.setVisibility(View.VISIBLE);
        mNoneData.setVisibility(View.GONE);
        mExceptionDataView.setVisibility(View.GONE);
        mViewSkeletonScreen.hide();
    }

    @Override
    public void loadNotFound() {
        mDetailRv.setVisibility(View.GONE);
        mReuseLoading.setVisibility(View.GONE);
        mDetailBottomLl.setVisibility(View.GONE);
        mNoConn.setVisibility(View.GONE);
        mNoneData.setVisibility(View.GONE);
        mExceptionDataView.setVisibility(View.VISIBLE);
        mViewSkeletonScreen.hide();
    }

    @Override
    public void loadEmpty() {
        mDetailRv.setVisibility(View.GONE);
        mReuseLoading.setVisibility(View.GONE);
        mDetailBottomLl.setVisibility(View.GONE);
        mNoConn.setVisibility(View.GONE);
        mNoneData.setVisibility(View.VISIBLE);
        mExceptionDataView.setVisibility(View.GONE);
        mViewSkeletonScreen.hide();
    }

    private void getNewsDigest(final String newsId) {
        RetrofitManager.getInstance().getApi().getNewsDigest(newsId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<NewsEntity>() {
                    @Override
                    public void onResponse(NewsEntity response) {
                        if (mIsCollectionNews && mNewsEntity != null && response != null) { // 对比查看收藏文章是否修改
                            return;
                        }
                        if (response == null) return;

                        mNewsEntity = response;
                        if (response.getType() != null) {
                            setNavigationTitle(response.getType());
                        }

                        adapter.setId(newsId);
                        adapter.setType(response.getType());
                        adapter.setTitle(response.getTitle());
                        adapter.getNewsDetail();

                        if (!mHideUselessInfo) {
                            mNewsShare.setVisible(true);
                            setTitleCenter();
                        }

                        HistoryHelper.insertNewsEntity(mNewsEntity);

                        MtaHelper.onEvent("详情页面", "文章详情", response.getTitle());
                    }

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

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteComment(EBDeleteComment event) {
        adapter.getNewsCommentNum();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddComment(EBAddComment event) {
        adapter.getNewsCommentNum();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction() & MotionEventCompat.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                isSecondDown = false;
                int pointerIndex = MotionEventCompat.findPointerIndex(ev, MotionEventCompat.getPointerId(ev, 0));
                Y11 = MotionEventCompat.getY(ev, pointerIndex);
                X11 = MotionEventCompat.getX(ev, pointerIndex);
                break;
            case MotionEvent.ACTION_UP:
                final int actionUpIndex = MotionEventCompat.getActionIndex(ev);
                int pointerIndex2 = MotionEventCompat.findPointerIndex(ev, MotionEventCompat.getPointerId(ev, actionUpIndex));
                Y12 = MotionEventCompat.getY(ev, pointerIndex2);
                X12 = MotionEventCompat.getX(ev, pointerIndex2);
                float X2 = Math.abs(X12 - X22);
                float Y2 = Math.abs(Y12 - Y22);
                float R2 = (X2 * X2) + (Y2 * Y2);
                double R12 = Math.sqrt(R2);
                if (adapter != null && isSecondDown) {
                    if ((R11 - R12) > scrollSize && fontsize > 1) {
                        fontsize--;
                        adapter.setFontSize(fontsize);
                        sp.edit().putInt(Constants.SP_FONT_SIZE, fontsize).apply();
                        String fontSizeText = getFontSize(fontsize);
                        Utils.toast(this, fontSizeText);
                    }
                    if ((R11 - R12) < -scrollSize && fontsize < 4) {
                        fontsize++;
                        adapter.setFontSize(fontsize);
                        sp.edit().putInt(Constants.SP_FONT_SIZE, fontsize).apply();
                        String fontSizeText = getFontSize(fontsize);
                        Utils.toast(this, fontSizeText);
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (isSecondDown) {
                    return true;
                }
                break;
            case MotionEventCompat.ACTION_POINTER_DOWN:
                isSecondDown = true;
                final int pointerIndexDown = MotionEventCompat.getActionIndex(ev);
                int pointerIndex1 = MotionEventCompat.findPointerIndex(ev, MotionEventCompat.getPointerId(ev, pointerIndexDown));
                Y21 = MotionEventCompat.getY(ev, pointerIndex1);
                X21 = MotionEventCompat.getX(ev, pointerIndex1);
                float X1 = Math.abs(X11 - X21);
                float Y1 = Math.abs(Y11 - Y21);
                float R1 = (X1 * X1) + (Y1 * Y1);
                R11 = Math.sqrt(R1);
                break;
            case MotionEventCompat.ACTION_POINTER_UP:
                final int pointerIndexUp = MotionEventCompat.getActionIndex(ev);
                int pointerIndex21 = MotionEventCompat.findPointerIndex(ev, MotionEventCompat.getPointerId(ev, pointerIndexUp));
                Y22 = MotionEventCompat.getY(ev, pointerIndex21);
                X22 = MotionEventCompat.getX(ev, pointerIndex21);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onClick(final View v) {
        if (v == mNoConn) {
            mDetailRv.setVisibility(View.VISIBLE);
            mReuseLoading.setVisibility(View.VISIBLE);
            mNoConn.setVisibility(View.GONE);
            handler.postDelayed(runnable, 1000);
        } else if (v == mDetailCommentLl) {
            CheckLoginUtils.checkLogin(this, "资讯文章详情-写评论", () -> {
                Intent intent = MessageDetailActivity.getIntentById(NewsDetailActivity.this, adapter.getId(), null, true
                        , mEntrance + "(新闻详情[" + adapter.getTitle() + "])");
                startActivity(intent);
            });
        }
    }

    private String getFontSize(int i) {
        switch (i) {
            case 1:
                return "小字号";
            case 2:
                return "中字号";
            case 3:
                return "大字号";
            case 4:
                return "特大字号";
            default:
                return "未知字号";
        }
    }

    private void getGameDetail(String gameId) {
        if (RegionSettingHelper.shouldThisGameBeFiltered(gameId)) {
            return;
        }

        if (TextUtils.isEmpty(gameId)) {
            mDetailBottomLl.setVisibility(View.GONE);
            return;
        }
        RetrofitManager.getInstance().getApi().getGameNewsDigest(gameId)
                .map(ApkActiveUtils.filterMapper)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<GameEntity>() {
                    @Override
                    public void onResponse(GameEntity response) {
                        ApkActiveUtils.filterHideApk(response);
                        gameEntity = response;

                        if (!mHideUselessInfo) {
                            adapter.setGameEntity(gameEntity);
                            adapter.notifyItemInserted(1);

                            mDetailBottomLl.setVisibility(View.VISIBLE);
                            mDownloadContainer.setVisibility(View.VISIBLE);
                            mBottomContainer.setVisibility(View.VISIBLE);
                        } else {
                            mCommentContainer.setVisibility(View.GONE);

                            // 关联了光环的文章不显示下载按钮
                            if ("光环助手".equals(gameEntity.getName())) {
                                mDetailBottomLl.setVisibility(View.GONE);
                                mBottomContainer.setVisibility(View.GONE);
                            } else {
                                mBottomContainer.setVisibility(View.VISIBLE);
                                mDetailBottomLl.setVisibility(View.VISIBLE);
                            }
                        }

                        DetailDownloadUtils.detailInitDownload(getDetailViewHolder(), true);
                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mEntrance.contains("板块成员") || mEntrance.contains("论坛详情")) {
            long stayTime = (System.currentTimeMillis() - startPageTime) / 1000;
            NewLogUtils.INSTANCE.logActivityPause("版规说明", "jump_layout_description", stayTime, "", "", "", "");
        }
    }

    // 关注事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBConcernChanged changed) {
        NewsDetailEntity newsDetailEntity = adapter.getNewsDetailEntity();
        if (newsDetailEntity != null && gameEntity != null && changed.isSingle() && changed.getGameId().equals(gameEntity.getId())) {
            if (newsDetailEntity.getMe() == null) {
                newsDetailEntity.setMe(new MeEntity());
            }
            newsDetailEntity.getMe().setGameConcerned(changed.isConcern());
            adapter.notifyItemChanged(1);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBNetworkState busNetworkState) {
        if (busNetworkState.isNetworkConnected()) {
            if (mNoConn.getVisibility() == View.VISIBLE) {
                mDetailRv.setVisibility(View.VISIBLE);
                mReuseLoading.setVisibility(View.VISIBLE);
                mDetailRv.setPadding(0, 0, 0, DisplayUtils.dip2px(getApplicationContext(), 60));
                mNoConn.setVisibility(View.GONE);
                handler.postDelayed(runnable, 1000);
            }
        }
    }

    // 接收下载被删除消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EBDownloadStatus status) {
        if ("delete".equals(status.getStatus()) && gameEntity != null && gameEntity.getApk().size() == 1) {
            String url = gameEntity.getApk().get(0).getUrl();
            if (url.equals(status.getUrl())) {
                DetailDownloadUtils.detailInitDownload(getDetailViewHolder(), false);
            }
        }
    }

    // 接受安装、卸载消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBPackage busFour) {
        if (gameEntity != null && gameEntity.getApk().size() == 1) {
            String packageName = gameEntity.getApk().get(0).getPackageName();
            if (packageName.equals(busFour.getPackageName())) {
                DetailDownloadUtils.detailInitDownload(getDetailViewHolder(), false);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBReuse reuse) {
        if (reuse.getType().equals(LOGIN_TAG) && adapter != null) { // 登入
            adapter.getNewsDetail();
        }
    }

    @Override
    protected boolean showDownloadMenu() {
        return true;
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        ExtensionsKt.updateStatusBarColor(this, R.color.background_white, R.color.background_white);
        mNewsShare.setIcon(R.drawable.icon_share_black);
        mNewsCollection.setIcon(R.drawable.community_content_detail_collect_unselect);
        mDetailRv.removeItemDecoration(mItemDecoration);
        mItemDecoration = new VerticalItemDecoration(this, 8, false);
        mDetailRv.addItemDecoration(mItemDecoration);
        if (mContentView != null) {
            mContentView.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
            findViewById(R.id.bottomContainer).setBackgroundColor(ContextCompat.getColor(this, R.color.background_white));
            ((TextView) findViewById(R.id.commentTv)).setTextColor(ContextCompat.getColor(this, R.color.text_subtitle));
        }
        if (adapter != null) {
            adapter.notifyItemRangeChanged(0, adapter.getItemCount());
        }
    }

    @Override
    public Pair<String, String> getBusinessId() {
        if (getIntent().getStringExtra(EntranceConsts.KEY_NEWSID) != null) {
            return new Pair(getIntent().getStringExtra(EntranceConsts.KEY_NEWSID), "");
        } else if (mNewsEntity != null) {
            return new Pair(mNewsEntity.getId(), "");
        } else {
            return super.getBusinessId();
        }
    }
}
