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.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
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.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.util.ConcernUtils;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.NewsUtils;
import com.gh.common.util.RandomUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.util.TokenUtils;
import com.gh.common.util.Utils;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.ViewImageActivity;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.NewsDetailEntity;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.gamedetail.GameDetailTopViewHolder;
import com.gh.gamecenter.listener.OnCallBackListener;
import com.gh.gamecenter.manager.ConcernManager;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by LGT on 2016/9/13.
 */
public class NewsDetailAdapter extends RecyclerView.Adapter {

	private Context context;
	private OnCallBackListener listener;

	private GameEntity gameEntity;
	private NewsDetailEntity newsDetailEntity;

	private ConcernManager concernManager;
	private WebSettings webSettings;

	private String id;
	private String type;
	private String title;
	private String entrance;

	public NewsDetailAdapter(NewsDetailActivity activity, String entrance) {
		this.context = activity;
		this.listener = activity;
		this.entrance = entrance;

		concernManager = new ConcernManager(context);
	}

	public void getNewsDetail() {
		JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
				Config.HOST + "v1d45/news/" + id + "/detail",
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {

						Gson gson = new Gson();
						newsDetailEntity = gson.fromJson(response.toString(), NewsDetailEntity.class);
						newsDetailEntity.setId(id);
						newsDetailEntity.setType(type);
						newsDetailEntity.setTitle(title);

						notifyDataSetChanged();
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// 无网络连接和访问超时
						if (error.getClass().equals(NoConnectionError.class)
								|| error.getClass().equals(TimeoutError.class)) {
							listener.loadError();
						}
					}
				});
		AppController.addToRequestQueue(request, NewsDetailActivity.TAG);
	}

	private void getNewsMore() {
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
				TimestampUtils.addTimestamp(
						Config.HOST + "v1d45/news/" + newsDetailEntity.getId() + "/suggestion",
						Constants.NEWS_CD),
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						Type listType = new TypeToken<ArrayList<NewsEntity>>() {}.getType();
						Gson gson = new Gson();
						List<NewsEntity> list = gson.fromJson(response.toString(), listType);
						// 去除与当前文章重复的文章
						for (int i = 0, size = list.size(); i < size; i++) {
							if (newsDetailEntity.getId().equals(list.get(i).getId())) {
								list.remove(i);
								break;
							}
						}
						List<NewsEntity> more = new ArrayList<>();
						// TODO 随机三篇文章
						int[] index = RandomUtils.getRandomArray(list.size() > 3 ? 3 : list.size(), list.size());
						for (int i : index) {
							more.add(list.get(i));
						}
						newsDetailEntity.setMore(more);
						notifyItemInserted(getItemCount() - 1);
					}
				}, null);
		AppController.addToRequestQueue(request, NewsDetailActivity.TAG);
	}

	@Override
	public int getItemCount() {
		if (newsDetailEntity == null) {
			return 0;
		}
		int count = 1;
		if (gameEntity != null) {
			count++;
		}
		if (newsDetailEntity.getMore() != null && newsDetailEntity.getMore().size() != 0) {
			count++;
		}
		return count;
	}

	@Override
	public int getItemViewType(int position) {
		if (gameEntity != null && position == 1) {
			return 1;
		} else if (gameEntity == null && position == 1) {
			return 2;
		}
		return position;
	}

	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		if (viewType == 0) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.newsdetail_item_content, parent, false);
			return new NewsDetailContentViewHolder(view);
		} else if (viewType == 1) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.gamedetail_item_top, parent, false);
			return new GameDetailTopViewHolder(view);
		} else if (viewType == 2) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.newsdetail_item_news_more, parent, false);
			return new NewsDetailNewsMoreViewHolder(view);
		}
		return null;
	}

	@Override
	public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
		if (holder instanceof NewsDetailContentViewHolder) {
			initNewsDetailContentViewHolder((NewsDetailContentViewHolder) holder);
		} else if (holder instanceof GameDetailTopViewHolder) {
			initGameDetailTopViewHolder((GameDetailTopViewHolder) holder);
		} else if (holder instanceof NewsDetailNewsMoreViewHolder) {
			initNewsDetailNewsMoreViewHolder((NewsDetailNewsMoreViewHolder) holder);
		}
	}

	private void initNewsDetailNewsMoreViewHolder(final NewsDetailNewsMoreViewHolder viewHolder) {
		if (viewHolder.newsdetail_item_ll_news_more.getTag() == null) {
			for (int i = 0; i < newsDetailEntity.getMore().size(); i++) {
				final NewsEntity newsEntity = newsDetailEntity.getMore().get(i);
				View view = View.inflate(context, R.layout.gamedetail_news_item, null);
				TextView tv_tag = (TextView) view.findViewById(R.id.gamedetail_news_item_tag);
				TextView tv_title = (TextView) view.findViewById(R.id.gamedetail_news_item_title);
				tv_tag.setText(newsEntity.getType());
				tv_title.setText(newsEntity.getTitle());
				tv_title.setTextColor(Color.parseColor("#3a3a3a"));
				view.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Map<String, Object> kv = new HashMap<>();
						kv.put("名字", newsEntity.getTitle());
						kv.put("位置", String.valueOf(viewHolder.getPosition() + 1));
						DataUtils.onEvent(context, "点击", "新闻详情-相关推荐", kv);

						Map<String, Object> map = new HashMap<>();
						map.put("location", "相关推荐");
						map.put("page", "新闻详情");
						map.put("news", newsEntity.getTitle());
						map.put("news_id", newsEntity.getId());
						DataCollectionManager.onEvent(context, "click-item", map);

						// 统计阅读量
						NewsUtils.statNewsViews(newsEntity.getId());
						NewsUtils.startNewsActivity(context, newsEntity, entrance + "+(新闻详情:相关推荐)");
					}
				});
				viewHolder.newsdetail_item_ll_news_more.addView(view);
			}
			viewHolder.newsdetail_item_ll_news_more.setTag("done");
		}
	}

	private void initGameDetailTopViewHolder(GameDetailTopViewHolder viewHolder) {
		ImageUtils.getInstance(context).displayFile(gameEntity.getIcon(), viewHolder.gamedetail_iv_thumb);
		viewHolder.gamedetail_tv_name.setText(gameEntity.getName());
		if (gameEntity.getApk() != null && gameEntity.getApk().size() != 0) {
			for (int i = 0, size = gameEntity.getApk().size(); i < size; i++) {
				ApkEntity apkEntity = gameEntity.getApk().get(i);
				if ("9u".equals(apkEntity.getPlatform())) {
					viewHolder.gamedetail_tv_info.setText(String.format("V%s | %s", apkEntity.getVersion(), apkEntity.getSize()));
					break;
				}
				if (i == size - 1) {
					viewHolder.gamedetail_tv_info.setText(String.format("V%s | %s", apkEntity.getVersion(), apkEntity.getSize()));
				}
			}
		}
		if (concernManager.isConcern(gameEntity.getId())) {
			viewHolder.gamedetail_tv_concern.setText("取消关注");
			viewHolder.gamedetail_tv_concern.setBackgroundResource(R.drawable.border_red_bg);
			viewHolder.gamedetail_tv_concern.setTextColor(Color.parseColor("#ff4147"));
		} else {
			viewHolder.gamedetail_tv_concern.setText("关注");
			viewHolder.gamedetail_tv_concern.setBackgroundResource(R.drawable.textview_concern_red_style);
			viewHolder.gamedetail_tv_concern.setTextColor(Color.WHITE);
		}
		viewHolder.gamedetail_tv_concern.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final TextView concern = ((TextView) v);
				String str = concern.getText().toString();
				if ("关注".equals(str)) {

					Map<String, Object> kv = new HashMap<>();
					kv.put("状态", "关注");
					DataUtils.onEvent(context, "游戏关注", gameEntity.getName(), kv);

					Map<String, Object> kv2 = new HashMap<>();
					kv2.put("点击", "关注");
					DataUtils.onEvent(context, "插件数据", gameEntity.getName(), kv2);

					Map<String, Object> map = new HashMap<>();
					map.put("game", gameEntity.getName());
					map.put("game_id", gameEntity.getId());
					map.put("type", "关注");
					DataCollectionManager.onEvent(context, "concern", map);

					concernManager.addByEntity(gameEntity);
					concern.setText("取消关注");
					concern.setBackgroundResource(R.drawable.border_red_bg);
					concern.setTextColor(Color.parseColor("#ff4147"));

					Toast.makeText(context, "关注成功", Toast.LENGTH_SHORT).show();

					//添加关注
					String uuid = TokenUtils.getDeviceId(context);
					ConcernUtils.postConcernGameId(gameEntity.getId(), Config.HOST + "v2d0/device/" + uuid + "/concern",
							new ConcernUtils.DownJsonListener() {
								@Override
								public void downSucced(String str) {
									Utils.log("关注提交成功==游戏详情");
								}

								@Override
								public void downFailed() {
									Utils.log("关注提交失败==游戏详情");
								}
							});
				} else {
					Map<String, Object> kv = new HashMap<>();
					kv.put("状态", "取消关注");
					DataUtils.onEvent(context, "游戏关注", gameEntity.getName(), kv);

					Map<String, Object> kv2 = new HashMap<>();
					kv2.put("点击", "取消关注");
					DataUtils.onEvent(context, "插件数据", gameEntity.getName(), kv2);

					Map<String, Object> map = new HashMap<>();
					map.put("game", gameEntity.getName());
					map.put("game_id", gameEntity.getId());
					map.put("type", "取消关注");
					DataCollectionManager.onEvent(context, "concern", map);
					DialogUtils.showCancelDialog(context, new DialogUtils.ConfiremListener() {
						@Override
						public void onConfirem() {
							Map<String, Object> kv = new HashMap<>();
							kv.put("状态", "取消关注");
							DataUtils.onEvent(context, "游戏关注", gameEntity.getName(), kv);

							Map<String, Object> map = new HashMap<>();
							map.put("game", gameEntity.getName());
							map.put("game_id", gameEntity.getId());
							map.put("type", "关注");
							DataCollectionManager.onEvent(context, "concern", map);

							concernManager.deleteConcern(gameEntity.getId());
							concern.setText("关注");
							concern.setBackgroundResource(R.drawable.textview_concern_red_style);
							concern.setTextColor(Color.WHITE);

							//取消关注
							String uuid = TokenUtils.getDeviceId(context);
							ConcernUtils.deleteConcernData(Config.HOST + "v2d0/device/" + uuid + "/concern/" + gameEntity.getId(),
									new ConcernUtils.DownJsonListener() {
										@Override
										public void downSucced(String str) {
											Utils.log("删除提交成功==游戏详情");
										}

										@Override
										public void downFailed() {
											Utils.log("删除提交失败==游戏详情");
										}
									});
						}
					});
				}
			}
		});
		viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Map<String, Object> kv = new HashMap<>();
				kv.put("名字", gameEntity.getName());
				kv.put("位置", "游戏信息");
				DataUtils.onEvent(context, "点击", "新闻详情", kv);

				Map<String, Object> map = new HashMap<>();
				map.put("location", "游戏信息");
				map.put("page", "新闻详情");
				map.put("game", gameEntity.getName());
				map.put("game_id", gameEntity.getId());
				map.put("news", newsDetailEntity.getTitle());
				map.put("news_id", newsDetailEntity.getId());
				DataCollectionManager.onEvent(context, "click-item", map);

				Intent intent = new Intent(context, GameDetailActivity.class);
				intent.putExtra("gameId", gameEntity.getId());
				intent.putExtra("entrance", entrance + "+(新闻详情)");
				context.startActivity(intent);
			}
		});
	}

	private void initNewsDetailContentViewHolder(NewsDetailContentViewHolder viewHolder) {
		viewHolder.newsdetail_item_tv_title.setText(newsDetailEntity.getTitle());
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
		try {
			long today = format.parse(format.format(new Date())).getTime();
			long day = Long.valueOf(newsDetailEntity.getTime() + "000");
			if (day >= today && day < today + 86400 * 1000) {
				format.applyPattern("HH:mm");
				viewHolder.newsdetail_item_tv_time.setText("今天 " + format.format(day));
			} else if (day >= today - 86400 * 1000 && day < today) {
				format.applyPattern("HH:mm");
				viewHolder.newsdetail_item_tv_time.setText("昨天 " + format.format(day));
			} else {
				format.applyPattern("yyyy年MM月dd日 HH:mm");
				viewHolder.newsdetail_item_tv_time.setText(format.format(day));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			format.applyPattern("yyyy年MM月dd日 HH:mm");
			viewHolder.newsdetail_item_tv_time.setText(format.format(Long.valueOf(newsDetailEntity.getTime() + "000")));
		}
		if (!TextUtils.isEmpty(newsDetailEntity.getAuthor())) {
			viewHolder.newsdetail_item_tv_author.setText(newsDetailEntity.getAuthor());
		}

		if (viewHolder.newsdetail_item_wv_content.getTag() == null) {
			viewHolder.newsdetail_item_wv_content.setBackgroundColor(0xFFEDF2F4);
			viewHolder.newsdetail_item_wv_content.addJavascriptInterface(new JsInterface(context), "imagelistener");
			webSettings = viewHolder.newsdetail_item_wv_content.getSettings();
			webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
			webSettings.setJavaScriptEnabled(true);
			SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Activity.MODE_PRIVATE);
			webSettings.setTextZoom(defaultTextZoom + sp.getInt("fontsize", 1) * 15);
			viewHolder.newsdetail_item_wv_content.loadDataWithBaseURL(null, newsDetailEntity.getContent(), "text/html", "utf-8", null);
			viewHolder.newsdetail_item_wv_content.setWebViewClient(new WebViewClient() {
				@Override
				public void onPageFinished(WebView view, String url) {
					view.loadUrl("javascript:(function(){"
							+ "var imgs = document.getElementsByTagName(\"img\");"
							+ "for (var i = 0; i < imgs.length - 1; i++) {"
							+ "    window.imagelistener.addImage(imgs[i].src);"
							+ "}"
							+ "for (var i = 0; i < imgs.length - 1; i++) {"
							+ "    imgs[i].onclick = function() {"
							+ "        window.imagelistener.openImage(this.src);"
							+ "    }"
							+ "}"
							+ "var as = document.getElementsByTagName(\"a\");"
							+ "for (var i = 0; i < as.length; i++) {"
							+ "    as[i].onclick = function() {"
							+ "        window.imagelistener.skip(this.id, this.type);"
							+ "    }"
							+ "}"
							+ "})()");
					super.onPageFinished(view, url);
					listener.loadDone(newsDetailEntity.getGameId());
					// 获取相关推荐
					getNewsMore();
				}
			});
			viewHolder.newsdetail_item_wv_content.setTag("show");
		}
	}

	public class JsInterface {
		private Context context;
		private ArrayList<String> imgs = new ArrayList<>();

		public JsInterface(Context context) {
			this.context = context;
		}

		@JavascriptInterface
		public void openImage(String url) {
			int current = 0;
			for (int i = 0, size = imgs.size(); i < size; i++) {
				if (url.equals(imgs.get(i))) {
					current = i;
				}
			}
			Intent checkIntent = new Intent(context, ViewImageActivity.class);
			checkIntent.putExtra("urls", imgs);
			checkIntent.putExtra("current", current);
			checkIntent.putExtra("ScaleType", "FIT_CENTER");
			context.startActivity(checkIntent);
		}

		@JavascriptInterface
		public void addImage(String url) {
			if (!imgs.contains(url)) {
				imgs.add(url);
			}
		}

		@JavascriptInterface
		public void skip(String id, String type) {
			if ("game".equals(type)) {
				Intent intent = new Intent(context, GameDetailActivity.class);
				intent.putExtra("gameId", id);
				intent.putExtra("entrance", entrance);
				context.startActivity(intent);
			} else if ("news".equals(type)) {
				Intent intent = new Intent(context, NewsDetailActivity.class);
				intent.putExtra("newsId", id);
				intent.putExtra("entrance", entrance);
				context.startActivity(intent);
			}
		}

	}

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

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

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

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

	public NewsDetailEntity getNewsDetailEntity() {
		return newsDetailEntity;
	}

	private int defaultTextZoom = 85;

	public void setFontSize(int fontsize) {
		webSettings.setTextZoom(defaultTextZoom + 15 * fontsize);
	}

}
