package com.xxfc.discovery.other;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
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.util.TransformationUtil;
import com.ruiwenliu.wrapper.util.glide.GlideApp;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.glide.GlideOptions;
import com.ruiwenliu.wrapper.util.um.CustomShareListener;
import com.ruiwenliu.wrapper.util.um.ShareManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.IsAppInstall;
import com.rv.component.utils.StorageUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.adapter.DiscoveryVideoCommentAdapter;
import com.xxfc.discovery.api.DiscoveryApi;
import com.xxfc.discovery.bean.DiscoveryCommentBean;
import com.xxfc.discovery.bean.DiscoveryIMTokenBean;
import com.xxfc.discovery.bean.DiscoveryRecommendBean;
import com.xxfc.discovery.dialog.TrillCommentInputDialog;
import com.xxfc.discovery.presenter.DiscoveryPresenter;
import com.yuyife.okgo.OkGoUtil;

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

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 短视频
 */
public class ShortVideoActivity extends BaseStatusActivity<DiscoveryPresenter> implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R2.id.iv_item_video_play)
    ImageView ivVideoPlay;
    @BindView(R2.id.rv_video_comment)
    RecyclerView rvVideoComment;
    @BindView(R2.id.ll_comment_show)
    LinearLayout llCommentShow;
    @BindView(R2.id.tv_video_comment_all)
    TextView tvVideoCommentAll;
    @BindView(R2.id.container)
    FrameLayout container;
    @BindView(R2.id.thumb)
    ImageView thumb;
    @BindView(R2.id.iv_video_avatar)
    ImageView ivVideoAvatar;
    @BindView(R2.id.iv_video_islike)
    ImageView ivVideoIslike;
    @BindView(R2.id.ll_item_video_islike)
    LinearLayout llItemVideoIslike;
    @BindView(R2.id.tv_video_islike_number)
    TextView tvVideoIslikeNumber;
    @BindView(R2.id.iv_video_comment)
    ImageView ivVideoComment;
    @BindView(R2.id.ll_item_video_comment)
    LinearLayout llItemVideoComment;
    @BindView(R2.id.tv_video_comment_number)
    TextView tvVideoCommentNumber;
    @BindView(R2.id.ll_item_video_share)
    LinearLayout llItemVideoShare;
    @BindView(R2.id.tv_video_share_number)
    TextView tvVideoShareNumber;
    @BindView(R2.id.tv_video_address_name)
    TextView tvVideoAddressName;
    @BindView(R2.id.tv_video_address)
    TextView tvVideoAddress;
//    @BindView(R2.id.video_play)
//    RotateVideoView mVideoView;



    private DiscoveryVideoCommentAdapter commentAdapter;

    private DiscoveryRecommendBean.DataBeanX.DataBean dataBean;
    private List<DiscoveryRecommendBean.DataBeanX.DataBean> dataBeanList;
    private int mPage;
    private int countPage;

    private String content;
    private String isPraise;
    private ShareManager shareManager;
    private ClipboardManager myClipboard;


    public static Intent getIntent(Context context, DiscoveryRecommendBean.DataBeanX.DataBean bean) {
        return new Intent(context, ShortVideoActivity.class)
                .putExtra("bean", bean);
    }

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


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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        showTitle(false);
        dataBean = (DiscoveryRecommendBean.DataBeanX.DataBean) intent.getSerializableExtra("bean");
        dataBeanList = new ArrayList();


        commentAdapter = new DiscoveryVideoCommentAdapter();
        rvVideoComment.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        rvVideoComment.setNestedScrollingEnabled(false);
        rvVideoComment.setAdapter(commentAdapter);

        initData();

        initShare(dataBean.getBody().getVideos().get(0).getOurl(), " ", " ", dataBean.getBody().getVideos().get(0).getOurl());
    }

    private void initData() {
        if (dataBean.getCount() != null) {
            tvVideoCommentAll.setText("全部评论" + dataBean.getCount().getComment() + "条");

            if (dataBean.getBody() != null && dataBean.getBody().getImages() != null && dataBean.getBody().getImages().size() > 0) {

                GlideOptions options = GlideOptions.placeholderOf(com.ruiwenliu.wrapper.R.drawable.glide_icon_placeholder).
                        error(com.ruiwenliu.wrapper.R.drawable.glide_icon_error);
                TransformationUtil utils = new TransformationUtil(thumb);
                GlideApp.with(mActivity)
                        .setDefaultRequestOptions(
                                new RequestOptions()
                                        .frame(1000000)
                                        .centerCrop()
                        )
                        .asBitmap()
                        .load(dataBean.getBody().getImages().get(0).getOurl())
                        .apply(options)
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(12)).override(thumb.getWidth(), thumb.getHeight()))
                        .placeholder(android.R.color.white)
                        .into(utils);
            }

            GlideManager.getInstance(mActivity).loadCircleImage(dataBean.getPicUrl(), ivVideoAvatar);
            if (!TextUtils.isEmpty(dataBean.getLocation())) {
                tvVideoAddress.setVisibility(View.VISIBLE);
                tvVideoAddress.setText(dataBean.getLocation());
            }

            if (dataBean.getCount() != null) {
                tvVideoIslikeNumber.setText(dataBean.getCount().getPraise());
                tvVideoCommentNumber.setText(dataBean.getCount().getComment());
                tvVideoShareNumber.setText(dataBean.getCount().getShare());
            }
//            isPraise = dataBean.getIsPraise();
//            if ("1".equals(dataBean.getIsPraise())) { //0：未点赞 1：已点赞
//                ivVideoIslike.setImageResource(R.drawable.icon_discover_video_like);
//            } else {
//                ivVideoIslike.setImageResource(R.drawable.icon_discover_video_likeun);
//            }
        }


    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
    }

    /**
     * IM token
     */
    private void getImToken(int position) {
        if (OkGoUtil.getToken() != null) {
            Map<String, Object> headMap = new LinkedHashMap<>();
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(RvFrameConfig.HOST, position, DiscoveryApi.DISCOVERY_IM_LOGIN, DiscoveryIMTokenBean.class, headMap, headMap, false);
        }
    }


    /**
     * 获取评论
     */
    private void commentData(String token) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("access_token", token);
        map.put("messageId", dataBean.getMsgId());
        map.put("pageIndex", mPage);
        mPresenter.postData(1, DiscoveryApi.DISCOVERY_COMMENT_LIST, DiscoveryCommentBean.class, map, mPage == 1 ? false : false);
    }


    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                DiscoveryIMTokenBean intokenBean = (DiscoveryIMTokenBean) result;
                commentData(intokenBean.getData());
                break;
            case 1:
                DiscoveryCommentBean commentBean = (DiscoveryCommentBean) result;
                setCommentData(commentBean);
                break;
            case 2:
                DiscoveryIMTokenBean intokenBean2 = (DiscoveryIMTokenBean) result;
                upCommentData(intokenBean2.getData());
                break;
            case 3:
                getImToken(0);
                break;
            case 4:
                DiscoveryIMTokenBean intokenBean3 = (DiscoveryIMTokenBean) result;
                upLikeData(intokenBean3.getData());
                break;
            case 5:
                isPraise = "1";
                ivVideoIslike.setImageResource(R.drawable.icon_discover_video_like);
                break;
            case 6:
                isPraise = "0";
                ivVideoIslike.setImageResource(R.drawable.icon_discover_video_likeun);
                break;
        }
    }

    private void upLikeData(String data) {
        if ("0".equals(isPraise)) {//0：未点赞 1：已点赞
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("access_token", data);
            map.put("messageId", dataBean.getMsgId());
            mPresenter.postData(5, DiscoveryApi.DISCOVERY_PRAISE_ADD, BaseBean.class, map, false);
        } else {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("access_token", data);
            map.put("messageId", dataBean.getMsgId());
            mPresenter.postData(6, DiscoveryApi.DISCOVERY_PRAISE_DELETE, BaseBean.class, map, false);
        }
    }

    /**
     * 评论列表
     *
     * @param commentBean
     */
    private void setCommentData(DiscoveryCommentBean commentBean) {
        commentAdapter.setNewData(commentBean.getData());
    }


    /**
     * 更新评论
     */
    private void upCommentData(String token) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("access_token", token);
        map.put("messageId", dataBean.getMsgId());
        map.put("body", content);
        mPresenter.postData(3, DiscoveryApi.DISCOVERY_COMMENT_ADD, BaseBean.class, map, true);
    }



    @OnClick({R2.id.iv_item_video_play, R2.id.iv_item_video_close, R2.id.v_comment_show_bg, R2.id.ll_item_comment
            , R2.id.ll_item_video_islike, R2.id.ll_item_video_comment, R2.id.ll_item_video_share, R2.id.rl_item_video})
    public void onViewClicked(View v) {
        int id = v.getId();
        if (id == R.id.rl_item_video || id == R.id.iv_item_video_play) {

        } else if (id == R.id.ll_item_video_islike) {
            //点赞
            getImToken(4);
        } else if (id == R.id.ll_item_video_comment) {
            //评论
            getImToken(0);
            llCommentShow.setVisibility(View.VISIBLE);

        } else if (id == R.id.ll_item_video_share) {
            //分享
            if (shareManager != null) {
                shareManager.open();
            }

        } else if (id == R.id.iv_item_video_close || id == R.id.v_comment_show_bg) {
            llCommentShow.setVisibility(View.GONE);

        } else if (id == R.id.ll_item_comment) {
            TrillCommentInputDialog trillCommentInputDialog = new TrillCommentInputDialog(mActivity, new TrillCommentInputDialog.OnSendCommentListener() {
                @Override
                public void sendComment(String str) {
                    content = str;
                    getImToken(2);
                }
            });
            Window window = trillCommentInputDialog.getWindow();
            if (window != null) {
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);// 软键盘弹起
                trillCommentInputDialog.show();
            }

        }
    }

    @Override
    public void onLoadMoreRequested() {

//        if (mPage >= countPage) {
//            commentAdapter.loadMoreEnd();
//        } else {
//            mPage++;
//            getImToken(0);
//        }
    }


    /**
     * 刷新数据
     */
    private void onRefresh() {
//        mPage = 1;
//        getImToken(0);
    }


    /**
     * 初始化分享
     */
    private void initShare(final String videoUrl, final String name, final String content, final String logo) {

        shareManager = new ShareManager(this, new ShareBoardlistener() {
            @Override
            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                if (snsPlatform.mShowWord.equals("下载视频")) {
                    downMp4(videoUrl);
                } else if (snsPlatform.mShowWord.equals("复制链接")) {
                    copyText();
                } else if (snsPlatform.mShowWord.contains("微信")) {
                    if (!IsAppInstall.isWeixinAvilible(mActivity)) {
                        showToast("亲，您微信还没有安装呢");
                        return;
                    }
                } else if (snsPlatform.mShowWord.contains("QQ")) {
                    if (!IsAppInstall.isQQClientAvailable(mActivity)) {
                        showToast("亲，您QQ还没有安装呢");
                        return;
                    }
                }

                shareManager.showShareVideo(share_media, videoUrl, name, content, logo, 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(platform + "分享成功啦");
                        }
                    }
                });
            }
        }, "rv_um_share_bill", "rv_share_download_video", "");
    }


    /**
     * 复制
     */
    private void copyText() {
        if (myClipboard == null) {
            myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        }
        ClipData myClip = ClipData.newPlainText("text", dataBean.getBody().getVideos().get(0).getOurl());
        myClipboard.setPrimaryClip(myClip);
        showToast("复制成功！");
    }


    private DownloadManager downloadManager;
    private long reference;
    private CompleteReceiver completeReceiver;

    private void downMp4(String urlVideo) {
        //下载任务
        String serviceString = Context.DOWNLOAD_SERVICE;
        //直接使用系统的下载管理器。是不是非常方便
        downloadManager = (DownloadManager) getBaseContext().getSystemService(serviceString);

        //可以是视频也可以是图片，分享时要填写正确的type类型，在下面我会列出各种类型
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlVideo));
        request.setShowRunningNotification(false);//不显示通知栏（若不显示就不需要写上面的内容）
        request.setVisibleInDownloadsUi(true);
        //下载到那个文件夹下，以及命名
        request.setDestinationInExternalPublicDir(StorageUtils.getPhotoSavePath(mActivity), System.currentTimeMillis() + ".mp4");
        //下载的唯一标识，可以用这个标识来控制这个下载的任务enqueue（）开始执行这个任务
        reference = downloadManager.enqueue(request);


        /** 注册下载监听的广播 **/
        completeReceiver = new CompleteReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(completeReceiver, filter);
    }

    //下载监听
    class CompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //下载完成之后监听
            String action = intent.getAction();
            //下载完成的监听
            if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                showToast("下载完成");
//                AlbumNotifyHelper.insertVideoToMediaStore(mActivity, StorageUtils.getPhotoSavePath(mActivity), System.currentTimeMillis(), 0);
            }
            //点击通知栏，取消下载任务
            if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
                downloadManager.remove((Long) reference);
            }
        }
    }
}
