package com.taikor.investment.modules;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.taikor.investment.MainActivity;
import com.taikor.investment.R;
import com.taikor.investment.adapter.HotNewAdapter;
import com.taikor.investment.adapter.MarketAdapter;
import com.taikor.investment.base.BaseFragment;
import com.taikor.investment.bean.BannerImage;
import com.taikor.investment.bean.HotNew;
import com.taikor.investment.bean.Market;
import com.taikor.investment.event.BooleanEvent;
import com.taikor.investment.modules.find.BestGroupActivity;
import com.taikor.investment.modules.find.HotNewsDescActivity;
import com.taikor.investment.modules.find.MarketDescActivity;
import com.taikor.investment.modules.find.ReportActivity;
import com.taikor.investment.modules.product.ProductSearchActivity;
import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.GlideUtils;
import com.taikor.investment.utils.Constant_URL;
import com.taikor.investment.view.ListViewForScrollView;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 发现
 * Created by Any on 2017/3/29.
 */
public class FindFragment extends BaseFragment implements
        OnBannerListener, SwipeRefreshLayout.OnRefreshListener,
        AdapterView.OnItemClickListener {

    @BindView(R.id.banner)
    Banner banner;//轮播图
    @BindView(R.id.rb_my_group)
    RadioButton rbMyGroup;//我的组合
    @BindView(R.id.rb_report)
    RadioButton rbReport;//研究报告
    @BindView(R.id.rb_best_group)
    RadioButton rbBestGroup;//最佳组合
    @BindView(R.id.lv_market)
    ListViewForScrollView lvMarket;
    @BindView(R.id.lv_news)
    ListViewForScrollView lvNews;
    @BindView(R.id.tv_market)
    TextView tvMarket;
    @BindView(R.id.tv_hot_new)
    TextView tvHotNew;
    @BindView(R.id.swipe_refresh_news)
    SwipeRefreshLayout swipeRefreshLayout;

    private MarketAdapter marketAdapter;
    private HotNewAdapter hotNewAdapter;
    private List<HotNew> news = new ArrayList<>();//热点资讯数据
    private List<Market> markets = new ArrayList<>();//市场解析数据
    private List<BannerImage> bannerImages = new ArrayList<>();//获取的轮播图数据
    private List<String> urlList = new ArrayList<>();//轮播图的图片url

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

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        //设置drawableRight的图片大小
        Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.rectangle3);
        drawable.setBounds(0, 0, 10, 50);
        tvHotNew.setCompoundDrawables(drawable, null, null, null);
        tvMarket.setCompoundDrawables(drawable, null, null, null);

        //市场解析
        marketAdapter = new MarketAdapter(getActivity());
        lvMarket.setAdapter(marketAdapter);
        lvMarket.setOnItemClickListener(this);
        //热点资讯
        hotNewAdapter = new HotNewAdapter(getActivity());
        lvNews.setAdapter(hotNewAdapter);
        lvNews.setOnItemClickListener(this);
        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(this);
        //设置图片加载器
        banner.setImageLoader(new GlideUtils());
        banner.setOnBannerListener(this);
    }

    @Override
    public void initData() {
        getBannerData(Constant_URL.BANNER);
        getMarketData(Constant_URL.MARKET);
        getNewData(Constant_URL.NEWS);
    }

    //获取轮播图的数据
    public void getBannerData(final String url) {
        OkHttpUtils.get().url(url)
                .addParams("count", "5")
                .build().execute(new Callback<List<BannerImage>>() {

            @Override
            public List<BannerImage> parseNetworkResponse(Response response, int id) throws Exception {
                Gson gson = new Gson();
                return gson.fromJson(response.body().string(), new TypeToken<List<BannerImage>>() {
                }.getType());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(List<BannerImage> response, int id) {
                if (response == null) {
                    return;
                }
                bannerImages = response;
                urlList.clear();
                for (BannerImage banners : response) {
                    urlList.add(banners.getImg());
                }
                //设置图片集合
                banner.setImages(urlList);
                //banner设置方法全部调用完毕时最后调用
                banner.start();
            }
        });
    }

    //获取市场波动解析的数据
    public void getMarketData(String url) {
        OkHttpUtils.get().url(url)
                .addParams("count", "3")
                .build().execute(new Callback<List<Market>>() {

            @Override
            public List<Market> parseNetworkResponse(Response response, int id) throws Exception {
                Gson gson = new Gson();
                return gson.fromJson(response.body().string(), new TypeToken<List<Market>>() {
                }.getType());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(List<Market> response, int id) {
                if (response == null) {
                    return;
                }
                markets = response;
                marketAdapter.setData(response, true);
            }
        });
    }

    //获取热点新闻的数据
    public void getNewData(String url) {
        OkHttpUtils.get().url(url)
                .addParams("keyword", "-1")
                .addParams("count", "3")
                .addParams("skip", "0")
                .build().execute(new Callback<List<HotNew>>() {

            @Override
            public List<HotNew> parseNetworkResponse(Response response, int id) throws Exception {
                Gson gson = new Gson();
                return gson.fromJson(response.body().string(), new TypeToken<List<HotNew>>() {
                }.getType());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onResponse(List<HotNew> response, int id) {
                swipeRefreshLayout.setRefreshing(false);
                if (response == null) {
                    return;
                }
                news = response;
                hotNewAdapter.setData(response, true);
            }
        });
    }

    @OnClick({R.id.rb_my_group, R.id.rb_report, R.id.rb_best_group, R.id.tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rb_my_group://我的组合
                MainActivity activity = (MainActivity) getActivity();
                FragmentManager fm = activity.getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.hide(activity.findFragment);
                if (activity.groupFragment == null) {
                    activity.groupFragment = new GroupFragment();
                    ft.add(R.id.fl_content, activity.groupFragment).commit();
                } else {
                    ft.show(activity.groupFragment).commit();
                }
                activity.rbGroup.setChecked(true);
                break;
            case R.id.rb_report://研究报告
                Intent reportIntent = new Intent(getActivity(), ReportActivity.class);
                startActivity(reportIntent);
                break;
            case R.id.rb_best_group://最佳组合
                Intent bestGroupIntent = new Intent(getActivity(), BestGroupActivity.class);
                startActivity(bestGroupIntent);
                break;
            case R.id.tv_search://搜索
                Intent intent = new Intent(getActivity(), ProductSearchActivity.class);
                intent.putExtra("jump_desc", true);
                intent.putExtra("type", "find");
                startActivity(intent);
                break;
        }
    }

    /**
     * 条目的点击事件
     *
     * @param parent   指哪个列表
     * @param view     当前item的view，通过它可以获得该项中的各个组件
     * @param position arg2是当前item的ID
     * @param id       arg3是当前的item在listView中的相对位置
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.lv_market:
                String articleID = markets.get(position).getArticleID();
                //埋点
                Map<String, String> marketMap = new HashMap<>();
                marketMap.put("type", "2");
                marketMap.put("newsID", articleID);
                Gson marketJson = new Gson();
                TAnalytics.onClick("articleRead", marketJson.toJson(marketMap));
                Intent marketIntent = new Intent(getActivity(), MarketDescActivity.class);
                marketIntent.putExtra("fluctuationID", articleID);
                startActivity(marketIntent);
                break;
            case R.id.lv_news:
                String newsID = news.get(position).getNewsID();
                //埋点
                Map<String, String> newsMap = new HashMap<>();
                newsMap.put("type", "1");
                newsMap.put("newsID", newsID);
                Gson newsJson = new Gson();
                TAnalytics.onClick("newsRead", newsJson.toJson(newsMap));
                //跳转详情
                Intent hotIntent = new Intent(getActivity(), HotNewsDescActivity.class);
                hotIntent.putExtra("newsID", newsID);
                startActivity(hotIntent);
                break;
        }
    }

    //点击轮播图
    @Override
    public void OnBannerClick(int position) {
        String articleID = bannerImages.get(position).getArticleID();
        //埋点
        Map<String, String> marketMap = new HashMap<>();
        marketMap.put("type", "2");
        marketMap.put("newsID", articleID);
        Gson marketJson = new Gson();
        TAnalytics.onClick("articleRead", marketJson.toJson(marketMap));
        //跳转
        Intent bannerIntent = new Intent(getActivity(), MarketDescActivity.class);
        bannerIntent.putExtra("fluctuationID", articleID);
        startActivity(bannerIntent);
    }

    // 刷新新闻列表
    @Override
    public void onRefresh() {
        getNewData(Constant_URL.NEWS);
    }

    // 开始轮播
    @Override
    public void onStart() {
        super.onStart();
        banner.start();
    }

    //停止轮播
    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    // 网络连接后自动加载数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void process(BooleanEvent event) {
        String type = event.getType();
        if (event.isFlag()) {
            if (type.equals("all")) {
                getBannerData(Constant_URL.BANNER);
                getMarketData(Constant_URL.MARKET);
                getNewData(Constant_URL.NEWS);
            }
        }
    }

    //注册事件总线
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    //解除事件总线
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //埋点
    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            TAnalytics.onPageStart("homePage");
        } else {
            TAnalytics.onPageLoad("homePage", "", "", "");
        }
    }
}