package com.xxrv.video.weight;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.danikula.videocache.HttpProxyCacheServer;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.BaseView;
import com.ruiwenliu.wrapper.presenter.WrapperPresenter;
import com.ruiwenliu.wrapper.util.glide.GlideApp;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.xxrv.video.R;
import com.xxrv.video.activity.TriListActivity;
import com.xxrv.video.adapter.CommentVideoAdapter;
import com.xxrv.video.api.VideoApi;
import com.xxrv.video.base.Proxy;
import com.xxrv.video.bean.circle.Comment;
import com.xxrv.video.bean.circle.DiscoveryDataBean;
import com.xxrv.video.bean.circle.VideoIMTokenBean;
import com.xxrv.video.dialog.TrillCommDialog;
import com.xxrv.video.presenter.VideoPresenter;
import com.yuyife.okgo.OkGoUtil;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoViewbyXuan;
import fm.jiecao.jcvideoplayer_lib.OnJcvdListener;

public class JcvTrillVideo extends FrameLayout implements BaseView, View.OnClickListener {
    TriListActivity mShareListener;
    int position;
    private Context mContext;
    private boolean isPause;
    private boolean isPraise;
    private int mCommCount;
    private int mLikeCount;
    private long mVideoSize;
    private String mToken;
    private String videoUserid;
    private String mMessageid;
    private String sVideoUrl;
    private String imageUrl;
    private String title;
    private TextView titleTextView;
    private TextView tvlikesCount;
    private TextView tvCommCount;
    private TextView tvShare;
    private TextView tvPlay;
    private TextView tvName;
    private ImageView ivAvatar;
    private ImageView startBtn;
    private ImageView thumbImageView;
    public Runnable HideThumbTask = new Runnable() {

        @Override
        public void run() {
            thumbImageView.setVisibility(GONE);
        }
    };
    private JCVideoViewbyXuan mVideoView;
    private Xpreprogressbar progressBar;
    //    private LikeRelativeLayout mLikeRelativeLayout;
    private ImageView btnLikes;
    private long mLastDoubleTapClickTime;
    private GestureDetector mGestureDetector;
    private Animation rotateAnim;
    private TrillCommDialog mCommDialog;
    private ProgressBar willPro;
    private VideoIMTokenBean ImTokenBean;
    private TextView tvConmmentHint1;
    private TextView tvConmmentHint2;
    private TextView tvConmmentHint3;
    private TextView tvAddress;
    private RecyclerView rvContent;
    private CommentVideoAdapter commentVideoAdapter;

    private OnJcvdListener mVideoListener = new OnJcvdListener() {
        @Override
        public void onPrepared() {
            isPause = false;
//             thumbImageView.setVisibility(GONE);
            thumbImageView.postDelayed(HideThumbTask, 300);

            startBtn.setVisibility(GONE);

            if (mVideoView.mCurrState == JCVideoPlayer.CURRENT_STATE_PAUSE) {
                progressBar.play(mVideoView.getDuration());
            } else {
                progressBar.play(0, mVideoView.getDuration());

            }
            willPro.setVisibility(GONE);
            Log.e("xuan", "onPrepared: " + mVideoView.mCurrState);
        }

        @Override
        public void onCompletion() {
            progressBar.clear();
            willPro.setVisibility(GONE);
        }

        @Override
        public void onError() {
            willPro.setVisibility(GONE);
            startBtn.setVisibility(VISIBLE);
            startBtn.setImageResource(R.drawable.jc_click_error_selector);
        }

        @Override
        public void onPause() {
            isPause = true;
            startBtn.setVisibility(VISIBLE);
            willPro.setVisibility(GONE);
            startBtn.setImageResource(R.drawable.ic_play_inco);
            progressBar.cancelProgressTimer();
        }

        @Override
        public void onReset() {
            thumbImageView.setVisibility(VISIBLE);
            startBtn.setVisibility(GONE);
            willPro.setVisibility(VISIBLE);
            progressBar.clear();
            progressBar.cancelProgressTimer();
        }
    };
    private VideoPresenter mPresenter;

    public JcvTrillVideo(Context context) {
        this(context, null);
    }

    public JcvTrillVideo(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public JcvTrillVideo(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(@NonNull Context context) {
        ParameterizedType type = (ParameterizedType) context.getClass().getGenericSuperclass();
        Class<? extends WrapperPresenter> presenterClass = (Class<? extends WrapperPresenter>) type.getActualTypeArguments()[0];
        try {
            this.mPresenter = (VideoPresenter) presenterClass.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        mPresenter.attachView(this);

        View.inflate(context, R.layout.layout_jcv_trill, this);
        mContext = context;

//        mLikeRelativeLayout = findViewById(R.id.like_relativeLayout);
        mVideoView = findViewById(R.id.xuan_video);
        thumbImageView = findViewById(R.id.thumb);
        startBtn = findViewById(R.id.start);
        willPro = findViewById(R.id.progress);


        tvName = findViewById(R.id.tv_name); // 用户名称
        titleTextView = findViewById(R.id.tv_title);
        progressBar = findViewById(R.id.bottom_progress);

        ivAvatar = findViewById(R.id.iv_avatar);
        btnLikes = findViewById(R.id.iv_likes);
        tvlikesCount = findViewById(R.id.tv_likes);// 点赞数
        tvCommCount = findViewById(R.id.tv_comm);  // 评论数
        tvShare = findViewById(R.id.tv_share);  // 转发数
        tvPlay = findViewById(R.id.tv_play);  // 播放数
        tvConmmentHint1 = findViewById(R.id.tv_conmment_hint1);
        tvConmmentHint2 = findViewById(R.id.tv_conmment_hint2);
        tvConmmentHint3 = findViewById(R.id.tv_conmment_hint3);
        tvAddress = findViewById(R.id.tv_address);
        rvContent = findViewById(R.id.rv_content);

        ivAvatar.setOnClickListener(this);
        findViewById(R.id.iv_follow).setOnClickListener(this);// 关注
        findViewById(R.id.ll_item_video_islike).setOnClickListener(this);
        findViewById(R.id.ll_item_video_comment).setOnClickListener(this);
        findViewById(R.id.ll_item_video_share).setOnClickListener(this);

        mVideoView.addOnJcvdListener(mVideoListener);
        initGestureAndAnimation(context);

//        AutoScrollLayoutManager autoScrollLayoutManager = new AutoScrollLayoutManager(context);
//        rvContent.setLayoutManager(autoScrollLayoutManager);
//        commentVideoAdapter = new CommentVideoAdapter();
//        rvContent.setAdapter(commentVideoAdapter);
//
//
//        rvContent.setOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    // 如果自动滑动到最后一个位置，则此处状态为SCROLL_STATE_IDLE
//                    AutoScrollLayoutManager lm = (AutoScrollLayoutManager) recyclerView
//                            .getLayoutManager();
//
//                    int position = lm.findLastCompletelyVisibleItemPosition();
//                    int count = lm.getItemCount();
//                    if (position == count - 1) {
//                        lm.scrollToPosition(0);
//                        rvContent.smoothScrollToPosition(commentVideoAdapter.getItemCount());
//                    }
//                }
//            }
//        });
    }


    private void initGestureAndAnimation(Context context) {
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                if (System.currentTimeMillis() - mLastDoubleTapClickTime <= 600) {
                    /*
                    之前有一个bug，即当用户在双击点赞时，如点击屏幕的次数为单数，最后都会触发onSingleTapConfirmed事件
                    现加一个时间判断，如当前时间减去最后一次双击时间小于600ms，认定当前用户正在进行双击操作 做弹爱心处理
                     */
//                    mLikeRelativeLayout.start(e);
                    return true;
                }
                if (isPause) {
                    mVideoView.play("");
                } else {
                    mVideoView.pause();
                }
                return true;
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                // 记录触发双击的时间
                mLastDoubleTapClickTime = System.currentTimeMillis();
                if (!isPraise) {// 非like状态，需要调用赞接口
                    loadImToken();
                }
//                mLikeRelativeLayout.start(e);
                return true;
            }
        });

        rotateAnim = AnimationUtils.loadAnimation(context, R.anim.rotate_anim_disc);
        LinearInterpolator lin = new LinearInterpolator();
        rotateAnim.setInterpolator(lin);
        rotateAnim.setFillAfter(true);
    }

    public int getCurrState() {
        return mVideoView.mCurrState;
    }

    public void startVideo() {
        // 增加缓存
        HttpProxyCacheServer proxy = Proxy.getInstance().getProxy(mContext);
        mVideoView.play(proxy.getProxyUrl(sVideoUrl));
    }

    private String formatCount(int count) {
        if (count < 10000) {
            return String.valueOf(count);
        }
        return String.format(Locale.getDefault(), "%.1fw", count / 1000 / 10.0);
    }

    public void updateDatas(DiscoveryDataBean bean, String token) {
        mToken = token;
        mMessageid = bean.getMsgId();

        sVideoUrl = bean.getFirstVideo();
        imageUrl = bean.getFirstImageOriginal();
        String text = bean.getBody().getText();

        GlideApp.with(mContext).load(imageUrl).into(thumbImageView);

        videoUserid = bean.getUserId();
        GlideManager.getInstance(mContext).loadCircleImage(bean.getPicUrl(), ivAvatar);

        mVideoSize = bean.getFirstVideoSize();
        mCommCount = bean.getComments().size();
        mLikeCount = bean.getPraiseCount();
        tvCommCount.setText(formatCount(mCommCount));
        tvlikesCount.setText(formatCount(mLikeCount));
//        tvShare.setText(formatCount(bean.getCount().getForward()));
        tvPlay.setText(formatCount(bean.getCount().getPlay()));

        mCommDialog = TrillCommDialog.getInstance();// 创建评论窗口
        mCommDialog.setOnUpdateCommListener(mContext, bean.getComments(), bean.getMsgId(), new TrillCommDialog.OnUpdateCommListener() {
            @Override
            public void updateCommCount() {
                mCommCount++;
                tvCommCount.setText(String.valueOf(mCommCount));
            }
        });

        isPraise = bean.getIsPraise() == 1;
        if (isPraise) {
            btnLikes.setSelected(true);
        } else {
            btnLikes.setSelected(false);
        }

        title = bean.getBody().getText();
        if (TextUtils.isEmpty(bean.getBody().getText())) {
            titleTextView.setVisibility(GONE);
        } else {
            titleTextView.setVisibility(VISIBLE);
            titleTextView.setText(bean.getBody().getText());
        }

        tvName.setText("@" + String.valueOf(bean.getNickname()));

        if (TextUtils.isEmpty(bean.getLocation())) {
            tvAddress.setVisibility(GONE);
        } else {
            tvAddress.setVisibility(VISIBLE);
            tvAddress.setText(bean.getLocation());
        }

//        commentVideoAdapter.addData(bean.getComments());

        List<Comment> comments = bean.getComments();
        if (comments != null && comments.size() > 0) {
            tvConmmentHint1.setVisibility(VISIBLE);
            tvConmmentHint1.setText(comments.get(0).getBody());
        } else {
            tvConmmentHint1.setVisibility(GONE);
        }

        if (comments != null && comments.size() > 1) {
            tvConmmentHint2.setVisibility(VISIBLE);
            tvConmmentHint2.setText(comments.get(1).getBody());
        } else {
            tvConmmentHint2.setVisibility(GONE);
        }

        if (comments != null && comments.size() > 2) {
            tvConmmentHint3.setVisibility(VISIBLE);
            tvConmmentHint3.setText(comments.get(2).getBody());
        } else {
            tvConmmentHint3.setVisibility(GONE);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mGestureDetector.onTouchEvent(event);
        return true;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();// 关注
        if (id == R.id.iv_avatar) {
            // 点击头像

        } else if (id == R.id.iv_follow) {
        } else if (id == R.id.ll_item_video_islike) {
            // 点赞按钮
            loadImToken();
        } else if (id == R.id.ll_item_video_comment) {
            // 评论按钮
            if (mContext instanceof BaseStatusActivity) {
                mCommDialog.show(((BaseStatusActivity) mContext).getSupportFragmentManager(), "TilTok");
            }
        } else if (id == R.id.ll_item_video_share) {
            // 分享按钮
            shareMessage();
        } else if (id == R.id.xuan_video) {
            // 暂停视频
            mVideoView.pause();
        }

    }

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

    private void praiseOrCancel() {
        if (TextUtil.isEmpty(ImTokenBean.getData())) {
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("access_token", ImTokenBean.getData());
        params.put("messageId", mMessageid);
        if (isPraise) {
            mPresenter.postData(2, VideoApi.DISCOVERY_PRAISE_DELETE, BaseBean.class, params, false);
        } else {
            mPresenter.postData(2, VideoApi.DISCOVERY_PRAISE_ADD, BaseBean.class, params, false);
        }
    }

    private void shareMessage() {

        if (mShareListener != null) {
            String url = VideoApi.DISCOVERY_SHORT_VIDEO + "?id=" + mMessageid + "&shareType=app";
            mShareListener.onShare(imageUrl, sVideoUrl, url, title, position);
        }
    }

    public void onShareListener(TriListActivity triListActivity) {
        mShareListener = triListActivity;
    }

    public void setPosiont(int position) {
        this.position = position;
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 1:
                ImTokenBean = (VideoIMTokenBean) result;
                praiseOrCancel();
                break;
            case 2:
                if (isPraise) {
                    btnLikes.setSelected(false);
                } else {
                    btnLikes.setSelected(true);
                }
                isPraise = !isPraise;
                if (isPraise) {
                    mLikeCount++;
                } else {
                    mLikeCount--;
                }
                tvlikesCount.setText(String.valueOf(mLikeCount));
                break;
        }
    }

    @Override
    public void onBeforeSuccess() {

    }

    @Override
    public void onShowLoading() {

    }

    @Override
    public void onHideLoading() {

    }

    @Override
    public void onShowError(String errorMsg, int errorType) {

    }

    @Override
    public void onErrorToken() {

    }
}
