package com.xxrv.video.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
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.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.danikula.videocache.HttpProxyCacheServer;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.http.ProgressRequestBody;
import com.ruiwenliu.wrapper.statusbar.StatusBarUtil;
import com.ruiwenliu.wrapper.util.um.CustomShareListener;
import com.ruiwenliu.wrapper.util.um.ShareManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.dialog.DownloadLoadingDialog;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.IsAppInstall;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.xxrv.video.R;
import com.xxrv.video.R2;
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.DiscoveryDataBean;
import com.xxrv.video.bean.circle.DiscoveryVideoBean;
import com.xxrv.video.bean.circle.VideoIMTokenBean;
import com.xxrv.video.presenter.VideoPresenter;
import com.xxrv.video.util.DownloadVideo;
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<DiscoveryDataBean> urlList;
    private int position = -1;
    private boolean isLoad;
    private int pagerIndex;
    boolean shareBack;
    private VideoIMTokenBean ImTokenBean;
    private ShareManager shareManager;

    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<DiscoveryDataBean> data, boolean isMore) {
        return new Intent(context, TriListActivity.class)
                .putExtra("position", position)
                .putExtra("page", page)
                .putExtra("data", JSON.toJSONString(data))
                .putExtra("more", isMore);
    }


    @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");
        boolean more = intent.getBooleanExtra("more", false);
        urlList = JSON.parseArray(data, DiscoveryDataBean.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();
                }
            }
        });
        if (more) {
            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();
        UMShareAPI.get(this).release();
    }

    String titles = "";

    public void onShare(String imageUrl, String videoUrl, String url, String title, int position) {
        /**
         * 初始化分享
         */
        String code = Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_CODE, "");
        String sVideoUrl = url + "&code=" + code;

        if (TextUtils.isEmpty(title)) {
            titles = "#短视频#记录您和房车的精彩瞬间";
        } else {
            titles = title;
        }
        shareManager = new ShareManager(this, new ShareBoardlistener() {
            @Override
            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                if (snsPlatform.mShowWord.equals("下载视频")) {

                    DownloadVideo.getInstance().downMp4(videoUrl, mActivity);

                } else if (snsPlatform.mShowWord.equals("复制链接")) {
                    ClipboardManager myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    ClipData myClip = ClipData.newPlainText("text", sVideoUrl);
                    myClipboard.setPrimaryClip(myClip);
                    showToast("链接已复制快去分享吧！");
                } else if (snsPlatform.mShowWord.contains("微信")) {
                    if (!IsAppInstall.isWeixinAvilible(mActivity)) {
                        showToast("亲，您微信还没有安装呢");
                        return;
                    }
                }

                shareManager.showShareVideo(share_media, sVideoUrl, titles, "[滴房车app]房车,让生活更美好", imageUrl

                        , new CustomShareListener(mActivity) {
                            @Override
                            public void onResult(SHARE_MEDIA platform) {
                                super.onResult(platform);

                                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                                        && platform != SHARE_MEDIA.EMAIL
                                        && platform != SHARE_MEDIA.FLICKR
                                        && platform != SHARE_MEDIA.FOURSQUARE
                                        && platform != SHARE_MEDIA.TUMBLR
                                        && platform != SHARE_MEDIA.POCKET
                                        && platform != SHARE_MEDIA.PINTEREST

                                        && platform != SHARE_MEDIA.INSTAGRAM
                                        && platform != SHARE_MEDIA.GOOGLEPLUS
                                        && platform != SHARE_MEDIA.YNOTE
                                        && platform != SHARE_MEDIA.EVERNOTE) {
                                    showToast("分享成功啦");
//                                            sharingSuccess();
                                }
                            }
                        });
            }
        }, "rv_um_share_copy", "rv_share_download_video", "1");


        if (shareManager != null) {
            shareManager.open();
        }

    }

    class ListVideoAdapter extends BaseRecAdapter<DiscoveryDataBean, VideoViewHolder> {
        public ListVideoAdapter(List<DiscoveryDataBean> list) {
            super(list);
        }

        @Override
        public void onHolder(VideoViewHolder holder, DiscoveryDataBean 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);

            holder.back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });

            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 LinearLayout back;

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

    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) {
            DiscoveryDataBean 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);
        }
    }
}
