package com.gh.gamecenter;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;

import com.android.volley.NoConnectionError;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.base.DetailActivity;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.eventbus.EBConcernChanged;
import com.gh.gamecenter.eventbus.EBNetworkState;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.newsdetail.NewsDetailAdapter;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

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

    public static final String TAG = NewsDetailActivity.class.getSimpleName();

    private NewsDetailAdapter adapter;

    private String newsId;

    private long start = 0L;

    private boolean isSentReport = false;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        name = "新闻详情";

        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

        detail_rv_show.setHasFixedSize(true);
        detail_rv_show.setLayoutManager(new LinearLayoutManager(this));
        adapter = new NewsDetailAdapter(this, entrance);
        detail_rv_show.setAdapter(adapter);

        newsId = getIntent().getStringExtra("newsId");
        if (newsId == null) {
            String id = getIntent().getStringExtra("id");
            String type = getIntent().getStringExtra("type");
            String title = getIntent().getStringExtra("title");
            if (type != null) {
                actionbar_tv_title.setText(type);
            }
            this.title = title;
            adapter.setId(id);
            adapter.setType(type);
            adapter.setTitle(title);
            adapter.getNewsDetail();

            iv_share.setVisibility(View.VISIBLE);
        } else {
            getNewsDigest(newsId);
        }

        start = System.currentTimeMillis();

        View view = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        if (view != null) {
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                    mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                    if (mHits[0] >= (SystemClock.uptimeMillis() - 1000)) {
                        detail_rv_show.scrollToPosition(0);
                    }
                }
            });
        }

        sp = getSharedPreferences(Config.PREFERENCE, Activity.MODE_PRIVATE);
        fontsize = sp.getInt("fontsize", 1);
        if (fontsize == 0) {
            fontsize = 1;
        }
    }


    @Override
    public void loadDone(Object obj) {
        if (reuse_ll_loading != null) {
            reuse_ll_loading.setVisibility(View.GONE);
            detail_rv_show.setVisibility(View.VISIBLE);
        }
        getGameDetail((String) obj);
    }

    @Override
    public void loadError() {
        detail_rv_show.setVisibility(View.GONE);
        reuse_ll_loading.setVisibility(View.GONE);
        detail_ll_bottom.setVisibility(View.GONE);
        detail_rv_show.setPadding(0, 0, 0, 0);
        reuse_no_connection.setVisibility(View.VISIBLE);
    }

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

    /**
     * 增加手势监听，控制字体大小
     *
     * @author 柯皓源
     */
    @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 (isSecondDown) {
                    if ((R11 - R12) > scrollSize && fontsize > 1) {
                        fontsize--;
                        adapter.setFontSize(fontsize);
                        sp.edit().putInt("fontsize", fontsize).apply();
                        String fontSizeText = getFontSize(fontsize);
                        Toast.makeText(this, fontSizeText, Toast.LENGTH_SHORT).show();
                    }
                    if ((R11 - R12) < -scrollSize && fontsize < 4) {
                        fontsize ++;
                        adapter.setFontSize(fontsize);
                        sp.edit().putInt("fontsize", fontsize).apply();
                        String fontSizeText = getFontSize(fontsize);
                        Toast.makeText(this, fontSizeText, Toast.LENGTH_SHORT).show();
                    }
                }
                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);
    }

    private void getNewsDigest(final String news_id) {
        JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
                TimestampUtils.addTimestamp(
                        Config.HOST + "v1d45/news/" + news_id + "/digest", Constants.NEWS_CD),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Gson gson = new Gson();
                        NewsEntity newsEntity = gson.fromJson(response.toString(), NewsEntity.class);
                        if (newsEntity.getType() != null) {
                            actionbar_tv_title.setText(newsEntity.getType());
                        }

                        adapter.setId(news_id);
                        adapter.setType(newsEntity.getType());
                        adapter.setTitle(newsEntity.getTitle());
                        adapter.getNewsDetail();

                        title = newsEntity.getTitle();

                        iv_share.setVisibility(View.VISIBLE);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 无网络连接和访问超时
                        if (error.getClass().equals(NoConnectionError.class)
                                || error.getClass().equals(TimeoutError.class)) {
                            if (!isDestroy) {
                                detail_rv_show.setVisibility(View.GONE);
                                reuse_ll_loading.setVisibility(View.GONE);
                                detail_ll_bottom.setVisibility(View.GONE);
                                detail_rv_show.setPadding(0, 0, 0, 0);
                                reuse_no_connection.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
        AppController.addToRequestQueue(request, TAG);
    }

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

    @Override
    public void onClick(final View v) {
        super.onClick(v);
        if (v == iv_share) {
            Map<String, Object> kv = new HashMap<>();
            kv.put("名字", adapter.getNewsDetailEntity().getTitle());
            kv.put("位置", "分享");
            DataUtils.onEvent(this, "点击", "新闻详情", kv);

            Map<String, Object> map = new HashMap<>();
            map.put("location", "分享");
            map.put("news", adapter.getNewsDetailEntity().getTitle());
            map.put("page", "新闻详情");
            DataCollectionManager.onEvent(this, "click-item", map);

            String url = "http://www.ghzhushou.com/article/" +
                    adapter.getNewsDetailEntity().getId() + ".html";
            if (gameEntity == null){
                showShare(url, adapter.getNewsDetailEntity().getTitle(),
                        "http://image.ghzhushou.com/pic/57d604808ab49e467d8b4568.png",
                        adapter.getNewsDetailEntity().getTitle(), null, entrance, "新闻");
            }else {
                showShare(url, gameEntity.getName(), gameEntity.getIcon(),
                        adapter.getNewsDetailEntity().getTitle(), gameEntity.getTag(),
                        entrance, "新闻");
            }
        } else if (v == reuse_no_connection) {
            detail_rv_show.setVisibility(View.VISIBLE);
            reuse_ll_loading.setVisibility(View.VISIBLE);
            reuse_no_connection.setVisibility(View.GONE);
            handler.postDelayed(runnable, 1000);
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (newsId != null) {
                getNewsDigest(newsId);
            } else {
                String id = getIntent().getStringExtra("id");
                String type = getIntent().getStringExtra("type");
                String title = getIntent().getStringExtra("title");
                if (type != null) {
                    actionbar_tv_title.setText(type);
                }
                adapter.setId(id);
                adapter.setType(type);
                adapter.setTitle(title);
                adapter.getNewsDetail();
            }
        }
    };

    private void getGameDetail(String gameId) {
        if (TextUtils.isEmpty(gameId)) {
            detail_ll_bottom.setVisibility(View.GONE);
            detail_rv_show.setPadding(0, 0, 0, 0);
            return;
        }
        JsonObjectExtendedRequest gameRequest = new JsonObjectExtendedRequest(
                TimestampUtils.addTimestamp(
                        Config.HOST + "v2d0/game/" + gameId + "/news_digest",
                        Constants.GAME_CD),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Gson gson = new Gson();
                        gameEntity = gson.fromJson(response.toString(), GameEntity.class);
                        if (adapter != null && gameEntity != null){
                            adapter.setGameEntity(gameEntity); //出现空指针 找不到原因
                            adapter.notifyItemInserted(1);
                            downloadAddWord = gameEntity.getDownloadAddWord();
                            initDownload(true);
                        }
                    }
                }, null);
        AppController.addToRequestQueue(gameRequest, TAG);
    }

    // 关注事件
    public void onEventMainThread(EBConcernChanged changed) {
        if (gameEntity != null && changed.getGameId().equals(gameEntity.getId())) {
            adapter.notifyItemChanged(0);
        }
    }

    public void onEventMainThread(EBNetworkState busNetworkState) {
        if (busNetworkState.isNetworkConnected()) {
            if (reuse_no_connection.getVisibility() == View.VISIBLE) {
                detail_rv_show.setVisibility(View.VISIBLE);
                reuse_ll_loading.setVisibility(View.VISIBLE);
                detail_ll_bottom.setVisibility(View.VISIBLE);
                detail_rv_show.setPadding(0, 0, 0, DisplayUtils.dip2px(getApplicationContext(), 44));
                reuse_no_connection.setVisibility(View.GONE);
                handler.postDelayed(runnable, 1000);
            }
        }
    }

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

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

            String cost;
            if (seconds < 5) {
                cost = "小于5秒";
            } else if (seconds < 30) {
                cost = "5秒－30秒";
            } else if (seconds < 60) {
                cost = "30秒－60秒";
            } else {
                cost = "大于60秒";
            }

            if (adapter.getNewsDetailEntity() != null) {
                // 阅读报告
                Map<String, Object> kv = new HashMap<>();
                kv.put("用时", cost);
                DataUtils.onEvent(NewsDetailActivity.this, "阅读文章", adapter.getNewsDetailEntity().getTitle(), kv);

                // 阅读报告
                Map<String, Object> kv1 = new HashMap<>();
                kv1.put(entrance, "阅读数");
                kv1.put(entrance, "用时:" + cost);
                DataUtils.onEvent(NewsDetailActivity.this, "文章数据", adapter.getNewsDetailEntity().getTitle(), kv1);

                if (seconds > 0) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("title", adapter.getNewsDetailEntity().getTitle());
                    map.put("type", adapter.getNewsDetailEntity().getType());
                    map.put("author", adapter.getNewsDetailEntity().getAuthor());
                    if (gameEntity != null) {
                        map.put("game", gameEntity.getName());
                        map.put("game_id", gameEntity.getId());
                    }
                    map.put("time", seconds);
                    map.put("from", entrance);
                    DataCollectionManager.onEvent(this, "news", map);
                }
            }

            isSentReport = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppController.canclePendingRequests(TAG);
        adapter = null;
    }

}
