package com.edufound.reader.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.duer.bot.directive.payload.AmountInfo;
import com.baidu.duer.botsdk.BotIntent;
import com.edufound.reader.R;
import com.edufound.reader.activity.CommentActivity;
import com.edufound.reader.activity.OthersRecordActivity;
import com.edufound.reader.activity.RecordActivity;
import com.edufound.reader.base.BaseActivity;
import com.edufound.reader.base.BaseMvpFragment;
import com.edufound.reader.bean.ChannelCodeEnum;
import com.edufound.reader.bean.UserEventEnum;
import com.edufound.reader.bean.UserRecordBean;
import com.edufound.reader.contract.RecommendFragmentContract;
import com.edufound.reader.presenter.RecommendFragmentPresenter;
import com.edufound.reader.util.Consts;
import com.edufound.reader.util.EfunboxUtil;
import com.edufound.reader.util.GlideUtils;
import com.edufound.reader.util.MMKVUtil;
import com.orhanobut.logger.Logger;

import java.util.HashMap;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import io.reactivex.rxjava3.annotations.Nullable;

public class RecommendFragment extends BaseMvpFragment<RecommendFragmentPresenter> implements RecommendFragmentContract.View {


    View mRootView;
    RecyclerView mRecyclerView;
    FrameLayout mUserHeadLayout;
    FrameLayout mCommentLayout;
    FrameLayout mCollectionLayout;
    FrameLayout mThumbsLayout;
    LinearLayout mToRecordLayout;
    ImageView mVideoUp;
    ImageView mVideoNext;
    ObjectAnimator mRotationImgAnim;
    ImageView mToRecordRotationbg;
    ObjectAnimator mToRecordScaleXAnim;
    ObjectAnimator mToRecordScaleYAnim;
    ImageView mToRecordScaleIcon;
    ImageView mUserHead;
    TextView mUserPhone;
    TextView mCommentCount;
    TextView mCollentStatus;
    TextView mThumbCount;
    ImageView isFollow;
    ImageView isUserVip;

    //默认是推荐 mFragmentType=0
    //关注 mFragmentType=1
    //官方的 mFragmentType=2
    //关注的人的mFragmentType=3
    int mFragmentType = 0;

    boolean hideBottom = false;

    int startPosition = 0;


    String mDataJson = null;

    String intoPage;

    public RecommendFragment(int type) {
        mFragmentType = type;
    }

    public RecommendFragment() {
    }

    @Override
    protected void initView(View view) {
        mRootView = view;
        mRootView.setVisibility(View.INVISIBLE);
        mPresenter = new RecommendFragmentPresenter(getContext());
        mPresenter.attachView(this);
        mRecyclerView = view.findViewById(R.id.fragment_recommend_recyclerview);
        mUserHeadLayout = view.findViewById(R.id.fragment_recommend_user_head_layout);
        mCommentLayout = view.findViewById(R.id.fragment_recommend_comment_layout);
        mCollectionLayout = view.findViewById(R.id.fragment_recommend_collection_layout);
        mThumbsLayout = view.findViewById(R.id.fragment_recommend_thumbs_layout);
        mVideoUp = view.findViewById(R.id.fragment_recommend_video_up);
        mVideoNext = view.findViewById(R.id.fragment_recommend_video_next);
        mToRecordLayout = view.findViewById(R.id.fragment_recommend_to_record_layout);
        mUserHead = view.findViewById(R.id.fragment_recommend_user_head);
        mUserPhone = view.findViewById(R.id.fragment_recommend_user_phone);
        mCommentCount = view.findViewById(R.id.fragment_recommend_comment_num);
        mCollentStatus = view.findViewById(R.id.fragment_recommend_collection_status);
        mThumbCount = view.findViewById(R.id.fragment_recommend_thumbs_num);
        isFollow = view.findViewById(R.id.fragment_main_recommend_isfollow);
        isUserVip = view.findViewById(R.id.fragment_recommend_app_user_isvip);
        //录音按钮背景旋转
        mToRecordRotationbg = mToRecordLayout.findViewById(R.id.fragment_recommend_to_record_bg);
        mRotationImgAnim = ObjectAnimator.ofFloat(mToRecordRotationbg, "rotation", 0.0F, 359.0F);
        mRotationImgAnim.setRepeatCount(-1);
        mRotationImgAnim.setDuration(1500);
        LinearInterpolator interpolator = new LinearInterpolator();
        mRotationImgAnim.setInterpolator(interpolator); //设置匀速旋转,不卡顿 icon_anim.start();
        mRotationImgAnim.start();
        //录音按钮缩小放大
        mToRecordScaleIcon = mToRecordLayout.findViewById(R.id.fragment_recommend_to_record_icon);
        mToRecordScaleXAnim = ObjectAnimator.ofFloat(mToRecordScaleIcon, "scaleX", 1F, 1.2F);//设置Y轴的立体旋转动画
        mToRecordScaleXAnim.setRepeatCount(-1);
        mToRecordScaleXAnim.setRepeatMode(ObjectAnimator.REVERSE);
        mToRecordScaleXAnim.setDuration(1000);
        LinearInterpolator interpolator2 = new LinearInterpolator();
        mToRecordScaleXAnim.setInterpolator(interpolator2); //设置匀速旋转,不卡顿 icon_anim.start();
        mToRecordScaleYAnim = ObjectAnimator.ofFloat(mToRecordScaleIcon, "scaleY", 1F, 1.2F);//设置Y轴的立体旋转动画
        mToRecordScaleYAnim.setRepeatCount(-1);
        mToRecordScaleYAnim.setRepeatMode(ObjectAnimator.REVERSE);
        mToRecordScaleYAnim.setDuration(1000);
        mToRecordScaleYAnim.setInterpolator(interpolator2); //设置匀速旋转,不卡顿 icon_anim.start();
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(mToRecordScaleXAnim).with(mToRecordScaleYAnim);
        animatorSet.start();

    }

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


    public RecommendFragmentPresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected void initViewListener() {


        if (hideBottom) {
            mVideoUp.setVisibility(View.GONE);
            mVideoNext.setVisibility(View.GONE);
        } else {
            addUiClickListener(mVideoUp, o -> {
                Logger.e("上一个视频");
                mPresenter.scrollToUpFunction(mRecyclerView);
            });
            addUiClickListener(mVideoNext, o -> {
                mPresenter.checkIsOver();
                mPresenter.scrollToNextFunction(mRecyclerView, true);
//                mPresenter.toNext(mRecyclerView);
                Logger.e("下一个视频");
            });
        }

        addUiClickListener(mToRecordLayout, o -> {
            mPresenter.getUserApi().postUserEvent(getActivity(), UserEventEnum.EVENT_RECREAD.getEvent());
            if (EfunboxUtil.checkLogin(getActivity())) {
                //登陆了,判断是否是VIP
                if (EfunboxUtil.checkIsVip()) {
                    //如果是VIP
                    Bundle bundle = new Bundle();
                    bundle.putString("exampleId", mPresenter.getCurVideoExampleId().toString());
                    toNextActivity(RecordActivity.class, bundle);
                } else {
                    EfunboxUtil.userPay(getActivity());
                }

            }
        });
        mPresenter.initVideoList(mRecyclerView, mFragmentType, startPosition);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(String errMessage) {

    }


    @Override
    public void onPause() {
        mPresenter.fragmentPause(mRecyclerView);
        super.onPause();
    }

    @Override
    public void onResume() {
        mPresenter.fragmentResume(mRecyclerView);
        if (Consts.getUmengChannel().equals(ChannelCodeEnum.BAIDU.getChannelCode())) {
            if (Consts.getmConstsBaiDuUserBean() != null) {
                isUserVip.setVisibility(View.INVISIBLE);
            }
        } else if (Consts.getUmengChannel().equals(ChannelCodeEnum.YIFANG.getChannelCode()) || Consts.getUmengChannel().equals(ChannelCodeEnum.TMAIL.getChannelCode())) {
            isUserVip.setEnabled(false);
            isUserVip.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (Consts.isIsYFVip()) {
                        isUserVip.setVisibility(View.INVISIBLE);
                    }
                    isUserVip.setEnabled(true);
                }
            }, 500);
        }
        super.onResume();

    }

    @Override
    public ViewGroup getRootView() {
        return (ViewGroup) mRootView;
    }


    public void hiddenBottomView() {
        hideBottom = true;
    }


    public void scrollPosition(int position) {
        startPosition = position;
    }


    public void setDataJson(String json) {
        mDataJson = json;
    }

    public void setInToPage(String page) {
        intoPage = page;
    }


    @Override
    public void setTopStatus(UserRecordBean bean) {

        //设置信息和点赞数等
        if (bean.getUser().getAvatar() == null || bean.getUser().getAvatar().equals("")) {
            if (bean.getUser().getGender().equals("1")) {
                //男
                GlideUtils.loadImage(getActivity(), R.drawable.activity_userinfo_setting_boy, mUserHead);
            } else {
                GlideUtils.loadImage(getActivity(), R.drawable.activity_userinfo_setting_girl, mUserHead);
            }
        } else {
            GlideUtils.loadCircleImage(getActivity(), bean.getUser().getAvatar(), mUserHead);
        }
        if (bean.getUser().getNickName().length() > 6) {
            mUserPhone.setText(bean.getUser().getNickName().substring(0, 6) + "...");
        } else {
            mUserPhone.setText(bean.getUser().getNickName());
        }
        mCommentCount.setText(bean.getUserRead().getCommentAmount());
        if (bean.getUser().getUid().equals(Consts.getUID()) || bean.getUser().getProfession().equals("官方")) {
            //是自己
            isFollow.setVisibility(View.INVISIBLE);
        } else {
            if (bean.getIsFans()) {
                isFollow.setVisibility(View.INVISIBLE);
            } else {
                isFollow.setVisibility(View.VISIBLE);
            }
        }
        if (bean.getIsFavorites() || bean.getFavoritesBean() != null) {
            mCollentStatus.setText("已收藏");
            ((ImageView) mCollectionLayout.findViewById(R.id.fragment_recommend_collection_icon)).setImageResource(R.drawable.fragment_recommend_collection_icon_s);
        } else {
            mCollentStatus.setText("未收藏");
            ((ImageView) mCollectionLayout.findViewById(R.id.fragment_recommend_collection_icon)).setImageResource(R.drawable.fragment_recommend_collection_icon);
        }
        if (bean.getIsLike()) {
            ((ImageView) mThumbsLayout.findViewById(R.id.fragment_recommend_thumbs_icon)).setImageResource(R.drawable.fragment_recommend_thumbs_up_s);
        } else {
            ((ImageView) mThumbsLayout.findViewById(R.id.fragment_recommend_thumbs_icon)).setImageResource(R.drawable.fragment_recommend_thumbs_up);
        }


        addUiClickListener(mUserHeadLayout, o -> {
            if (EfunboxUtil.checkLogin(getActivity())) {
                Bundle bundle = new Bundle();
                bundle.putString("other_uid", bean.getUser().getUid());
                bundle.putString("record_id", bean.getUserRead().getId());
                bundle.putString("intoPage", "RecommendFragment");
                toNextActivity(OthersRecordActivity.class, bundle);
            }
        });

        addUiClickListener(mCollectionLayout, o -> {
            if (EfunboxUtil.checkLogin(getActivity())) {
                mPresenter.doFavorites(bean.getUserRead());
            }
        });
        addUiClickListener(mThumbsLayout, o -> {
            if (EfunboxUtil.checkLogin(getActivity())) {
                mPresenter.doLike(bean.getUserRead());
            }
        });
        mThumbCount.setText(bean.getUserRead().getLikeAmount());
        addUiClickListener(mCommentLayout, o -> {
            if (EfunboxUtil.checkLogin(getActivity())) {
                Logger.e("点击了评论");
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getUserRead().getId());
                toNextActivity(CommentActivity.class, bundle);
            }
        });


    }

    @Override
    public void setFavorites(boolean isfavorites) {
        if (isfavorites) {
            mCollentStatus.setText("已收藏");
            ((ImageView) mCollectionLayout.findViewById(R.id.fragment_recommend_collection_icon)).setImageResource(R.drawable.fragment_recommend_collection_icon_s);
        } else {
            mCollentStatus.setText("未收藏");
            ((ImageView) mCollectionLayout.findViewById(R.id.fragment_recommend_collection_icon)).setImageResource(R.drawable.fragment_recommend_collection_icon);
        }
    }

    @Override
    public void setLikes(String count) {
        if (!count.equals(mThumbCount.getText().toString())) {
            ((ImageView) mThumbsLayout.findViewById(R.id.fragment_recommend_thumbs_icon)).setImageResource(R.drawable.fragment_recommend_thumbs_up_s);
        }
        mThumbCount.setText(count);
    }

    @Override
    public String getDataJson() {
        return mDataJson;
    }

    @Override
    public void showFirstIntoView() {
        boolean isFirst = (boolean) MMKVUtil.getInstance().decode("first_into", true);
        if (isFirst) {
            //是第一次进入
            ((BaseActivity) getActivity()).showFirstTouchView();
            MMKVUtil.getInstance().encode("first_into", false);
        } else {
            //不是第一次进入了
        }
    }


    @Override
    public void onDestroy() {

        mPresenter.activityDestory();
        mPresenter.detachView();
        super.onDestroy();
    }

    @Override
    public void onGetDisconnect() {

    }

    @Override
    public void onGetMobileConnect() {

    }

    @Override
    public void onGetWifiConnect() {

    }


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

    }

    @Override
    protected void botHandleIntent(BotIntent intent, String customData) {
        super.botHandleIntent(intent, customData);
        Logger.e("botHandleIntent:" + customData);
        if (EfunboxUtil.checkIsVip()) {
            isUserVip.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void botOnClickLink(String url, HashMap<String, String> paramMap) {
        super.botOnClickLink(url, paramMap);
        Logger.e("botOnClickLink:" + url);
    }

    @Override
    protected void botOnHandleScreenNavigatorEvent(int event) {
        super.botOnHandleScreenNavigatorEvent(event);
        Logger.e("botOnHandleScreenNavigatorEvent:");
    }

    @Override
    protected void botOnLinkAccountSucceed(String s, String s1) {
        super.botOnLinkAccountSucceed(s, s1);
        Logger.e("botOnHandleScreenNavigatorEvent:");
    }

    @Override
    protected void botOnChargeStatusUpdated(String purchaseResult, AmountInfo authorizationAmount, AmountInfo capturedAmount, long creationTimestamp, String baiduOrderReferenceId, String sellerOrderId, String msg) {
        super.botOnChargeStatusUpdated(purchaseResult, authorizationAmount, capturedAmount, creationTimestamp, baiduOrderReferenceId, sellerOrderId, msg);
        Logger.e("botOnHandleScreenNavigatorEvent:");
    }

    @Override
    protected void botOnBuyStatusUpdated(@NonNull String purchaseResult, @NonNull String productId, @NonNull String baiduOrderId, @NonNull String sellerOrderId, @Nullable String msg, String token) {
        super.botOnBuyStatusUpdated(purchaseResult, productId, baiduOrderId, sellerOrderId, msg, token);
        Logger.e("botOnBuyStatusUpdated:");
    }


}