package com.xxrv.video.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.danikula.videocache.HttpProxyCacheServer;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.statusbar.StatusBarUtil;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.xxrv.video.R;
import com.xxrv.video.R2;
import com.xxrv.video.adapter.ListVideoAdapter;
import com.xxrv.video.api.VideoApi;
import com.xxrv.video.base.BaseRecAdapter;
import com.xxrv.video.base.BaseRecViewHolder;
import com.xxrv.video.base.Proxy;
import com.xxrv.video.bean.circle.DiscoveryVideoBean;
import com.xxrv.video.bean.circle.VideoIMTokenBean;
import com.xxrv.video.presenter.VideoPresenter;
import com.xxrv.video.weight.JcvTrillVideo;
import com.yuyife.okgo.OkGoUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import fm.jiecao.jcvideoplayer_lib.JCMediaManager;
import fm.jiecao.jcvideoplayer_lib.VideotillManager;

public class TriListActivity extends BaseStatusActivity<VideoPresenter> {

    @BindView(R2.id.rv_pager)
    RecyclerView mPager;

    private PagerSnapHelper snapHelper;
    private LinearLayoutManager layoutManager;
    private ListVideoAdapter videoAdapter;
    private List<DiscoveryVideoBean.DataBeanX.DataBean> urlList;
    private int position = -1;
    private boolean isLoad;
    private int pagerIndex;
    boolean shareBack;
    private VideoIMTokenBean ImTokenBean;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            videoAdapter.notifyDataSetChanged();
            layoutManager.scrollToPosition(position);
            return true;
        }
    });

    public static Intent getIntent(Context context, int position, int page, List<DiscoveryVideoBean.DataBeanX.DataBean> data) {
        return new Intent(context, TriListActivity.class)
                .putExtra("position", position)
                .putExtra("page", page)
                .putExtra("data", JSON.toJSONString(data));
    }


    @Override
    protected int setLayout() {
        return R.layout.activity_tri_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setRootViewFitsSystemWindows(mActivity, false);
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        showTitle(false);

        position = intent.getIntExtra("position", 0);
        pagerIndex = intent.getIntExtra("page", 0);
        String data = intent.getStringExtra("data");
        urlList = JSON.parseArray(data, DiscoveryVideoBean.DataBeanX.DataBean.class);

        snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(mPager);
        videoAdapter = new ListVideoAdapter(urlList);
        layoutManager = new LinearLayoutManager(this);
        mPager.setLayoutManager(layoutManager);

        mPager.setAdapter(videoAdapter);

        layoutManager.scrollToPosition(position);

        mPager.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int position = -1;

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                int cur = layoutManager.findFirstVisibleItemPosition();
                if (cur != position) {
                    position = cur;
//                    TrillStatisticsHelper.play(mContext, coreManager, urlList.get(cur));      //观看数量统计

                    loadImToken();
                }
            }
        });
        addListener();

    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 1:
                processData((DiscoveryVideoBean) result);
                break;
            case 2:
                ImTokenBean = (VideoIMTokenBean) result;
                playAmount();
                break;
        }
    }

    private void processData(DiscoveryVideoBean bean) {
        isLoad = false;
        if (bean.getData() != null && bean.getData().getList() != null && bean.getData().getList().size() > 0) {
            urlList.addAll(bean.getData().getList());
            Log.e("xuan", "onResponse: " + urlList.size());
            videoAdapter.notifyDataSetChanged();
            layoutManager.scrollToPosition(position);
        }
    }

    private void addListener() {
        mPager.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动

                        if (urlList == null || urlList.size() == 0) {
                            return;
                        }

                        View view = snapHelper.findSnapView(layoutManager);
                        RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);
                        position = recyclerView.getChildLayoutPosition(view);

                        if (viewHolder != null && viewHolder instanceof VideoViewHolder) {
                            JcvTrillVideo video = ((VideoViewHolder) viewHolder).mp_video;
                            //                            Log.e("xuan", position + " : 滚动到: " + video.getCurrState());
                            video.startVideo();
                        }

                        if (urlList.size() > position + 1) {
                            Log.e("xuan", "onScrollStateChanged: " + (position + 1) + ",  size " + urlList.size());
                            HttpProxyCacheServer proxy = Proxy.getInstance().getProxy(TriListActivity.this);
                            proxy.getProxyUrl(urlList.get(position + 1).getFirstVideo());
                        }

                        if (!isLoad && position > urlList.size() - 4) {
                            pagerIndex++;
                            loadData();
                        }

                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING://拖动
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
                        break;
                }

            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        VideotillManager.instance().pause();
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.e("xuan", "onResume: " + shareBack);
        if (!shareBack) {
            VideotillManager.instance().play();
        } else {
            VideotillManager.instance().releaseVideo();
            JCMediaManager.instance().releaseMediaPlayer();
            handler.sendEmptyMessageDelayed(1, 500);

        }
        shareBack = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        JCMediaManager.addOnJcvdListener(null);
        VideotillManager.instance().releaseVideo();
    }


    class ListVideoAdapter extends BaseRecAdapter<DiscoveryVideoBean.DataBeanX.DataBean, VideoViewHolder> {
        public ListVideoAdapter(List<DiscoveryVideoBean.DataBeanX.DataBean> list) {
            super(list);
        }

        @Override
        public void onHolder(VideoViewHolder holder, DiscoveryVideoBean.DataBeanX.DataBean bean, int position) {
            ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            holder.mp_video.updateDatas(bean, "");
            holder.mp_video.onShareListener(TriListActivity.this);
            holder.mp_video.setPosiont(position);

            Log.e("xuan", "onHolder: " + position + " ,,  " + TriListActivity.this.position);
            if (position == TriListActivity.this.position) {
                holder.mp_video.startVideo();
            }
        }

        @Override
        public VideoViewHolder onCreateHolder() {
            return new VideoViewHolder(getViewByRes(R.layout.item_trill));
        }
    }

    public class VideoViewHolder extends BaseRecViewHolder {
        public View rootView;
        public JcvTrillVideo mp_video;

        public VideoViewHolder(View rootView) {
            super(rootView);
            this.rootView = rootView;
            this.mp_video = rootView.findViewById(R.id.mp_video);
        }
    }

    private void loadData() {
        isLoad = true;
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", pagerIndex + "");
        map.put("type", 4);
        mPresenter.postData(1, VideoApi.DISCOVERY_UNAUTH_LIST, DiscoveryVideoBean.class, map, false);

    }


    private void loadImToken() {
        if (OkGoUtil.getToken() != null) {
            Map<String, Object> headMap = new LinkedHashMap<>();
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(RvFrameConfig.HOST, 2, VideoApi.DISCOVERY_IM_LOGIN, VideoIMTokenBean.class, headMap, headMap, false);
        }
    }

    private void playAmount() {
        if (urlList != null && urlList.size() >= position) {
            DiscoveryVideoBean.DataBeanX.DataBean dataBean = urlList.get(position);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("access_token", ImTokenBean.getData());
            map.put("messageId", dataBean.getMsgId());
            mPresenter.getData(3, VideoApi.DISCOVERY_PLAYAMOUNT_ADD, VideoIMTokenBean.class, map, false);
        }
    }
}
