package com.gh.gamecenter.news;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.DiskBasedCache;
import com.gh.base.AppController;
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.GzipUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.NewsUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.util.Utils;
import com.gh.common.view.CardLinearLayout;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImage1ViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImage2ViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImage3ViewHolder;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.listener.OnCallBackListener;
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.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by khy on 2016/6/30.
 */
public class News2FragmentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private class ITEM_TYPE {
        public static final int normal = 0;//正常布局
        public static final int special1 = 1;//一张1:3图
        public static final int special2 = 2;//三张4:3图
        public static final int footer = 3;//页脚
    }

    private News2Fragment fragment;
    private Context context;
    private OnCallBackListener listener;

    private List<NewsEntity> newsList;
    private ArrayMap<String, Integer> viewsMap;
    private List<String> urlList;

    private boolean isLoading;
    private boolean isRemove;
    private boolean isNetworkError;

    public News2FragmentAdapter(News2Fragment fragment, boolean isLoad) {

        this.fragment = fragment;
        this.context = fragment.getActivity();
        this.listener = fragment;

        newsList = new ArrayList<>();
        viewsMap = new ArrayMap<>();
        urlList = new ArrayList<>();

        isLoading = false;
        isRemove = false;
        isNetworkError = false;

        if (isLoad) {
            load();
        }
    }

    public void load() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                addList(0);
            }
        }){}.start();
    }

    public void addList(final int offset) {
        if (isLoading) {
            return;
        }
        isLoading = true;
        final String url = Config.HOST + "v1d50/news/yuanchuang?limit=10&offset=" + offset;
        JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
                TimestampUtils.addTimestamp(url, Constants.NEWS_CD),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        isLoading = false;

                        Type listType = new TypeToken<ArrayList<NewsEntity>>() {}.getType();
                        Gson gson = new Gson();
                        List<NewsEntity> list = gson.fromJson(response.toString(), listType);
                        newsList.addAll(list);

                        if (!fragment.isHidden() && !fragment.isEverpause()) {
                            notifyItemRangeInserted(newsList.size() - list.size(), list.size());
                        } else {
                            notifyDataSetChanged();
                        }

                        listener.loadDone();

                        if (list.isEmpty() || (offset == 0 && list.size() < 10)) {
                            isRemove = true;
                            notifyItemChanged(getItemCount() - 1);
                        }

                        //获取新闻阅读量
                        getNewsViews(list, offset);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        isLoading = false;
                        // 无网络连接和访问超时
                        if (error.getClass().equals(NoConnectionError.class)
                                || error.getClass().equals(TimeoutError.class)) {
                            if (offset == 0) {
                                listener.loadError();
                            } else {
                                Toast.makeText(context, "加载失败，请检查网络状态", Toast.LENGTH_SHORT).show();
                                isNetworkError = true;
                                notifyItemChanged(getItemCount() - 1);
                            }
                        }
                    }
                });
        AppController.addToRequestQueue(request, News2Fragment.TAG);
    }

    private void getNewsViews(final List<NewsEntity> list, final int start) {
        if (list == null || list.isEmpty()) {
            return;
        }
        StringBuilder ids = new StringBuilder();
        for (int i = 0, size = list.size(); i < size; i++) {
            ids.append(list.get(i).getId());
            ids.append("-");
        }
        final String url = "http://data.ghzhushou.com/v1d46/news/" + ids.substring(0, ids.length() - 1) + "/visit";
        if (!urlList.contains(url)) {
            urlList.add(url);
        }
        JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Utils.log("response = " + response);
                        try {
                            JSONObject jsonObject;
                            for (int i = 0, size = response.length(); i < size; i++) {
                                jsonObject = response.getJSONObject(i);
                                viewsMap.put(jsonObject.getString("id"), jsonObject.getInt("views"));
                            }
                            notifyItemRangeChanged(start, start + list.size() - 1);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
        AppController.addToRequestQueue(request, News2Fragment.TAG);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE.normal) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.fm_read_item, parent, false);
            return new NewsImage1ViewHolder(view);
        } else if (viewType == ITEM_TYPE.special1) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.fm_read2_special1, parent, false);
            return new NewsImage3ViewHolder(view);
        } else if (viewType == ITEM_TYPE.special2) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.fm_read2_special2, parent, false);
            return new NewsImage2ViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof NewsImage1ViewHolder) {
            initNewsImage1ViewHolder((NewsImage1ViewHolder) holder, newsList.get(position), position);
        } else if (holder instanceof NewsImage3ViewHolder) {
            initNewsImage3ViewHolder((NewsImage3ViewHolder) holder, newsList.get(position), position);
        } else if (holder instanceof NewsImage2ViewHolder) {
            initNewsImage2ViewHolder((NewsImage2ViewHolder) holder, newsList.get(position), position);
        } else if (holder instanceof FooterViewHolder) {
            initFooterViewHolder((FooterViewHolder) holder);
        }
    }

    private void initNewsImage1ViewHolder(final NewsImage1ViewHolder viewHolder, final NewsEntity newsEntity, int position) {

        // 第一个
        if (position == 0) {
            ((CardLinearLayout) viewHolder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
        } else {
            ((CardLinearLayout) viewHolder.itemView).setmTop(0);
        }

        // 最后一个
        if (position + 1 == newsList.size()) {
            ((CardLinearLayout) viewHolder.itemView).setBottom(true);
        } else {
            ((CardLinearLayout) viewHolder.itemView).setBottom(false);
        }

        viewHolder.itemView.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);

                //统计阅读量
                statNewsViews(newsEntity.getId(), viewHolder.getPosition());
                NewsUtils.startNewsActivity(context, newsEntity, "(资讯-原创)");
            }
        });
        viewHolder.fm_read_tv_read.setTextColor(Color.parseColor("#9a9a9a"));
        ImageUtils.getInstance(context).display(newsEntity.getThumbnail().getUrl().get(0), viewHolder.fm_read_iv_thumb);
        viewHolder.fm_read_tv_title.setText(newsEntity.getTitle());
        Integer views = viewsMap.get(newsEntity.getId());
        if (views == null) {
            viewHolder.fm_read_tv_read.setVisibility(View.GONE);
        } else {
            viewHolder.fm_read_tv_read.setVisibility(View.VISIBLE);
            viewHolder.fm_read_tv_read.setText("阅读  " + views);
        }
        setType(viewHolder.fm_read_tv_type, newsEntity.getType());
    }

    private void initNewsImage2ViewHolder(final NewsImage2ViewHolder viewHolder, final NewsEntity newsEntity, int position) {

        // 第一个
        if (position == 0) {
            ((CardLinearLayout) viewHolder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
        } else {
            ((CardLinearLayout) viewHolder.itemView).setmTop(0);
        }

        // 最后一个
        if (position + 1 == newsList.size()) {
            ((CardLinearLayout) viewHolder.itemView).setBottom(true);
        } else {
            ((CardLinearLayout) viewHolder.itemView).setBottom(false);
        }

        DisplayMetrics outMetrics = new DisplayMetrics();
        fragment.getActivity().getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        int width = (outMetrics.widthPixels - DisplayUtils.dip2px(context, 56)) / 3;
        int height = (int) (width * 3 / 4f);
        LinearLayout.LayoutParams lparams1 = new LinearLayout.LayoutParams(width, height);
        viewHolder.fm_read2_special2_thumb1.setLayoutParams(lparams1);
        LinearLayout.LayoutParams lparams2 = new LinearLayout.LayoutParams(width, height);
        lparams2.leftMargin = DisplayUtils.dip2px(context, 8);
        viewHolder.fm_read2_special2_thumb2.setLayoutParams(lparams2);
        LinearLayout.LayoutParams lparams3 = new LinearLayout.LayoutParams(width, height);
        lparams3.leftMargin = DisplayUtils.dip2px(context, 8);
        viewHolder.fm_read2_special2_thumb3.setLayoutParams(lparams3);

        viewHolder.itemView.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);

                //统计阅读量
                statNewsViews(newsEntity.getId(), viewHolder.getPosition());
                NewsUtils.startNewsActivity(context, newsEntity, "(资讯-原创)");
            }
        });
        viewHolder.fm_read2_special2_title.setText(newsEntity.getTitle());
        ImageUtils.getInstance(context).display(newsEntity.getThumbnail().getUrl().get(0),
                viewHolder.fm_read2_special2_thumb1);
        ImageUtils.getInstance(context).display(newsEntity.getThumbnail().getUrl().get(1),
                viewHolder.fm_read2_special2_thumb2);
        ImageUtils.getInstance(context).display(newsEntity.getThumbnail().getUrl().get(2),
                viewHolder.fm_read2_special2_thumb3);
        Integer views = viewsMap.get(newsEntity.getId());
        if (views == null) {
            viewHolder.fm_read2_special2_tv_read.setVisibility(View.GONE);
        } else {
            viewHolder.fm_read2_special2_tv_read.setVisibility(View.VISIBLE);
            viewHolder.fm_read2_special2_tv_read.setText("阅读  " + views);
        }
        setType(viewHolder.fm_read2_special2_tv_type, newsEntity.getType());
    }

    private void initNewsImage3ViewHolder(final NewsImage3ViewHolder viewHolder, final NewsEntity newsEntity, int position) {

        // 第一个
        if (position == 0) {
            ((CardLinearLayout) viewHolder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
        } else {
            ((CardLinearLayout) viewHolder.itemView).setmTop(0);
        }

        // 最后一个
        if (position + 1 == newsList.size()) {
            ((CardLinearLayout) viewHolder.itemView).setBottom(true);
        } else {
            ((CardLinearLayout) viewHolder.itemView).setBottom(false);
        }

        viewHolder.itemView.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);

                //统计阅读量
                statNewsViews(newsEntity.getId(), viewHolder.getPosition());
                NewsUtils.startNewsActivity(context, newsEntity, "(资讯-原创)");
            }
        });
        viewHolder.fm_read2_special1_title.setText(newsEntity.getTitle());
        ImageUtils.getInstance(context).display(newsEntity.getThumbnail().getUrl().get(0),
                viewHolder.fm_read2_special1_thumb, R.drawable.preload, context, 40);
        Integer views = viewsMap.get(newsEntity.getId());
        if (views == null) {
            viewHolder.fm_read2_special1_tv_read.setVisibility(View.GONE);
        } else {
            viewHolder.fm_read2_special1_tv_read.setVisibility(View.VISIBLE);
            viewHolder.fm_read2_special1_tv_read.setText("阅读  " + views);
        }
        setType(viewHolder.fm_read2_special1_tv_type, newsEntity.getType());
    }

    private void initFooterViewHolder(FooterViewHolder viewHolder) {
        if (isNetworkError) {
            viewHolder.footerview_progressbar.setVisibility(View.GONE);
            viewHolder.footerview_tv_loading.setText("加载失败，点击重试");
            viewHolder.itemView.setClickable(true);
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isNetworkError = false;
                    notifyItemChanged(getItemCount() - 1);
                    addList(newsList.size());
                }
            });
        } else if (isRemove) {
            viewHolder.footerview_progressbar.setVisibility(View.GONE);
            viewHolder.footerview_tv_loading.setText("加载完毕");
            viewHolder.itemView.setClickable(false);
        } else {
            viewHolder.footerview_progressbar.setVisibility(View.VISIBLE);
            viewHolder.footerview_tv_loading.setText("加载中...");
            viewHolder.itemView.setClickable(false);
        }
    }

    @Override
    public int getItemCount() {
        if (newsList.isEmpty()){
            return 0;
        }
        return newsList.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == newsList.size()) {
            return ITEM_TYPE.footer;
        }
        NewsEntity newsEntity = newsList.get(position);
        if ("4x3".equals(newsEntity.getThumbnail().getType()) && newsEntity.getThumbnail().getUrl().size() == 3){
            return ITEM_TYPE.special2;
        }
        if ("3x1".equals(newsEntity.getThumbnail().getType())) {
            return ITEM_TYPE.special1;
        }
        return ITEM_TYPE.normal;
    }

    private void statNewsViews(final String news_id, final int position) {
        String url = "http://data.ghzhushou.com/news/stat?news_id=" + news_id;
        JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
                Request.Method.POST, url,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            if ("success".equals(response.getString("status"))) {
                                Integer views = viewsMap.get(news_id);
                                if (views == null) {
                                    views = new Integer(0);
                                }
                                views += 1;
                                viewsMap.put(news_id, views);
                                notifyItemChanged(position);

                                //修改volley缓存
                                modifyVolleyCache(news_id);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
        request.setShouldCache(false);
        AppController.addToRequestQueue(request, News2Fragment.TAG);
    }

    private static final String DEFAULT_CACHE_DIR = "volley";

    private void modifyVolleyCache(String id) {
        String key = null;
        for (int i = 0, size = urlList.size(); i < size; i++) {
            if (urlList.get(i).contains(id)) {
                key = urlList.get(i);
                break;
            }
        }
        if (key == null) {
            return;
        }
        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
        DiskBasedCache cache = new DiskBasedCache(cacheDir);
        byte[] data = cache.getData(key);
        if (data != null) {
            try {
                JSONArray jsonArray = new JSONArray(new String(GzipUtils.decompressBytes(data)));
                JSONObject jsonObject;
                for (int i = 0, size = jsonArray.length(); i < size; i++) {
                    jsonObject = jsonArray.getJSONObject(i);
                    if (jsonObject.getString("id").equals(id)) {
                        jsonObject.put("views", jsonObject.getInt("views") + 1);
                        break;
                    }
                }
                Utils.log(jsonArray.toString());
                cache.modify(key, GzipUtils.compressBytes(jsonArray.toString().getBytes()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Utils.log("modifyVolleyCache is null");
        }
    }

    private void setType(TextView textView, String type) {

        ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
        layoutParams.width = DisplayUtils.dip2px(context,28);
        layoutParams.height = DisplayUtils.dip2px(context,17);
        textView.setLayoutParams(layoutParams);

        if ("评测".equals(type)){
            textView.setTextColor(Color.WHITE);
            textView.setBackgroundResource(R.drawable.textview_red_style);
        } else if ("杂谈".equals(type)){
            textView.setTextColor(Color.WHITE);
            textView.setBackgroundResource(R.drawable.textview_orange_style);
        } else if ("专题".equals(type)) {
            textView.setTextColor(Color.WHITE);
            textView.setBackgroundResource(R.drawable.textview_blue_style);
        } else {
            textView.setTextColor(Color.WHITE);
            textView.setBackgroundResource(R.drawable.textview_blue_style);
        }
        textView.setText(type);
    }

    public boolean isRemove() {
        return isRemove;
    }

    public boolean isLoading() {
        return isLoading;
    }

    public boolean isNetworkError() {
        return isNetworkError;
    }

    public List<NewsEntity> getNewsList() {
        return newsList;
    }
}
