package com.hongyegroup.cpt_rewards.ui;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewStub;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.guadou.cs_cptservices.YYConstants;
import com.guadou.cs_cptservices.commonBean.LevelPoints;
import com.guadou.lib_baselib.base.activity.BaseVMActivity;
import com.guadou.lib_baselib.base.vm.BaseViewModel;
import com.guadou.lib_baselib.engine.ToastExtKt;
import com.guadou.lib_baselib.ext.DateTimeExtKt;
import com.guadou.lib_baselib.font_text_view.TextViewLight;
import com.guadou.lib_baselib.utils.CommUtils;
import com.guadou.lib_baselib.utils.DateAndTimeUtil;
import com.guadou.lib_baselib.utils.SPUtils;
import com.guadou.lib_baselib.view.titlebar.EasyTitleBar;
import com.hongyegroup.cpt_rewards.R;
import com.hongyegroup.cpt_rewards.utils.NumAnim;
import com.hongyegroup.cpt_rewards.utils.PointFormatUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.annotation.Nullable;

public class RewardsDailyLoginActivity extends BaseVMActivity<BaseViewModel> implements View.OnClickListener {

    private TextView mHistoryTv;
    private EasyTitleBar mEasyTitle;
    private TextView mCheckInTv;
    private RelativeLayout mRootRl;
    private TextView mContinuousDayTv;
    private TextView mNewsFeedPostTv;
    private TextView mPromotionApplyTv;

    private TextView mPointsTv;
    private TextView mData1Tv;
    private TextView mData2Tv;
    private TextView mData3Tv;
    private TextView mData4Tv;
    private TextView mData5Tv;
    private TextView mData6Tv;
    private TextView mData7Tv;
    private ImageView mChoose1Iv;
    private ImageView mChoose2Iv;
    private ImageView mChoose3Iv;
    private ImageView mChoose4Iv;
    private ImageView mChoose5Iv;
    private ImageView mChoose6Iv;
    private ImageView mChoose7Iv;
    private TextView mPoints1Tv;
    private TextView mPoints2Tv;
    private TextView mPoints3Tv;
    private TextView mPoints4Tv;
    private TextView mPoints5Tv;
    private TextView mPoints6Tv;
    private TextView mPoints7Tv;
    private ImageView mTeasurechest1Iv;
    private ImageView mTeasurechest2Iv;
    private ImageView mTeasurechest3Iv;
    private ImageView mTeasurechest4Iv;
    private ImageView mTeasurechest5Iv;
    private ImageView mTeasurechest6Iv;
    private ImageView mTeasurechest7Iv;

    //昨天是否签到
    private boolean isCheckInYesterday;
    //签到当天有宝箱，是否打开
    private boolean isBoxOpened = false;
    private LevelPoints mLevelPoints;
    //今天所在的位置
    private int mCurrentDayPosition;
    //当前是第几天
    private int mCurrentDay = 0;
    //总积分数
    private int mPoint = 0;
    //当前7天的连续签到天数
    private List<Integer> mDays = new ArrayList<>();
    //日期的数组
    private TextView[] mDateTvs = new TextView[7];
    //点卡图标的数组
    private ImageView[] mChoosesIvs = new ImageView[7];
    private ImageView[] mTeasurechesIvs = new ImageView[7];
    //签到加的积分
    private TextView[] mPointTvs = new TextView[7];
    // 贝塞尔曲线中间过程点坐标
    private float[] mCurrentPosition = new float[2];
    // 路径测量
    private PathMeasure mPathMeasure;
    private ViewStub mViewstub_sign;
    //    private View mRootView;
    private View mView_placeholder;
    private LinearLayout mLlHistory3itemRoot;
    private SmartRefreshLayout mRefreshLayout;
    private View mTvGotoRewards;
    private TextViewLight mTvDailyBrowseNews;
    private TextViewLight mTvDailyGiveLike;
    private TextViewLight mTvDailyPostVideo;
    private TextViewLight mTvDailyGetLikes;
    private boolean isFirstEnter = true;
    private boolean isInflateView = true;//每日签到布局只加载一次

    public static void startInstance() {

        Context context = CommUtils.getContext();
        Intent intent = new Intent(context, RewardsDailyLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

    }

    @Override
    public void init(@Nullable Bundle savedInstanceState) {

        initView();
        initListener();

    }

    private void initListener() {

        mCheckInTv.setOnClickListener(this);
        mTvGotoRewards.setOnClickListener(this);
        mEasyTitle.addRightImg(R.drawable.help_blue, new EasyTitleBar.MenuBuilder.OnMenuClickListener() {
            @Override
            public void OnMenuEvent() {

                ToastExtKt.toast(this, "Rules");

            }
        });

    }

    private void initView() {

//        mLevelPoints = (LevelPoints) getArguments().getSerializable("level_points");
//        isCheckInYesterday = getArguments().getBoolean("is_check_in_yesterday");

        /**
         * total : 0
         * level : 1
         * level_alias : Bronze
         * "daily_check_in": false,
         * "promotion_apply": false,
         * "news_feed_post": false
         * continuous_days : 0
         */
        mLevelPoints = new LevelPoints();
        mLevelPoints.points = 200;
        mLevelPoints.level = "1";
        mLevelPoints.daily_check_in = false;
        mLevelPoints.continuous_days = 3;

        isCheckInYesterday = true;

//        if (mLevelPoints.daily_check_in) {
//            mCurrentDay = mLevelPoints.continuous_days;
//        } else {
//            mCurrentDay = mLevelPoints.continuous_days + 1;
//        }

        mTvGotoRewards = findViewById(R.id.tv_goto_rewards);
        mRefreshLayout = findViewById(R.id.refresh_layout);
        mViewstub_sign = findViewById(R.id.viewstub_sign);
        mView_placeholder = findViewById(R.id.view_placeholder);
        mEasyTitle = findViewById(R.id.easy_title);
        mHistoryTv = findViewById(R.id.tv_daily_login_history);
        mPointsTv = findViewById(R.id.tv_daily_login_points);
        mCheckInTv = findViewById(R.id.tv_daily_login_check_in);
        mRootRl = findViewById(R.id.rl_daily_login_root);
        mLlHistory3itemRoot = findViewById(R.id.ll_history_3item_root);

        mLlHistory3itemRoot.removeAllViews();

        View inflate = CommUtils.inflate(R.layout.item_points_history);

        mLlHistory3itemRoot.addView(inflate);
//        mLlHistory3itemRoot.addView(inflate);
//        mLlHistory3itemRoot.addView(inflate);

        //设置其他的数据
//        setupDailyStatus();

    }

    //其他的按钮状态设置
    @SuppressLint("SetTextI18n")
    private void setupDailyStatus() {
        if (mLevelPoints != null) {

            if (mLevelPoints.news_feed_post) {
                mNewsFeedPostTv.setEnabled(false);
                mNewsFeedPostTv.setBackgroundColor(CommUtils.getColor(R.color.gray));
            }

            if (mLevelPoints.promotion_apply) {
                mPromotionApplyTv.setEnabled(false);
                mPromotionApplyTv.setBackgroundColor(CommUtils.getColor(R.color.gray));
            }

            if (mLevelPoints.browse_news_feed) {
                mTvDailyBrowseNews.setEnabled(false);
                mTvDailyBrowseNews.setBackgroundColor(CommUtils.getColor(R.color.gray));
            }

            if (mLevelPoints.give_likes >= 10) {
                mTvDailyGiveLike.setEnabled(false);
                mTvDailyGiveLike.setBackgroundColor(CommUtils.getColor(R.color.gray));
            } else {
                mTvDailyGiveLike.setEnabled(true);
                mTvDailyGiveLike.setBackgroundColor(CommUtils.getColor(R.color.profile_red));
            }
            mTvDailyGiveLike.setText(mLevelPoints.give_likes + " / 10");


            if (mLevelPoints.post_video) {
                mTvDailyPostVideo.setEnabled(false);
                mTvDailyPostVideo.setBackgroundColor(CommUtils.getColor(R.color.gray));
            }

            if (mLevelPoints.get_likes >= 50) {
                mTvDailyGetLikes.setEnabled(false);
                mTvDailyGetLikes.setBackgroundColor(CommUtils.getColor(R.color.gray));
            } else {
                mTvDailyGetLikes.setEnabled(true);
                mTvDailyGetLikes.setBackgroundColor(CommUtils.getColor(R.color.profile_red));
            }
            mTvDailyGetLikes.setText(mLevelPoints.get_likes + " / 50");

        }
    }

    @Override
    public int getLayoutIdRes() {
        return R.layout.activity_rewards_daily_login;
    }

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

        //每日签到界面只填充一次
        if (isInflateView) {

            isInflateView = false;

            //展示顶部point和动画
//        mPoint = SPUtils.getInstance(CommUtils.getContext()).getInt(YYConstants.CACHE_REWARDS_POINTS, 0);
            mPoint = 200;
            NumAnim.startAnim(mPointsTv, mPoint);

            //加载布局
            mView_placeholder.setVisibility(View.GONE);
            mViewstub_sign.inflate();

            mContinuousDayTv = findViewById(R.id.tv_daily_login_continuous_day);
            mData1Tv = findViewById(R.id.tv_date1);
            mData2Tv = findViewById(R.id.tv_date2);
            mData3Tv = findViewById(R.id.tv_date3);
            mData4Tv = findViewById(R.id.tv_date4);
            mData5Tv = findViewById(R.id.tv_date5);
            mData6Tv = findViewById(R.id.tv_date6);
            mData7Tv = findViewById(R.id.tv_date7);

            mDateTvs[0] = mData1Tv;
            mDateTvs[1] = mData2Tv;
            mDateTvs[2] = mData3Tv;
            mDateTvs[3] = mData4Tv;
            mDateTvs[4] = mData5Tv;
            mDateTvs[5] = mData6Tv;
            mDateTvs[6] = mData7Tv;

            mChoose1Iv = findViewById(R.id.iv_daily_choose1);
            mChoose2Iv = findViewById(R.id.iv_daily_choose2);
            mChoose3Iv = findViewById(R.id.iv_daily_choose3);
            mChoose4Iv = findViewById(R.id.iv_daily_choose4);
            mChoose5Iv = findViewById(R.id.iv_daily_choose5);
            mChoose6Iv = findViewById(R.id.iv_daily_choose6);
            mChoose7Iv = findViewById(R.id.iv_daily_choose7);

            mChoosesIvs[0] = mChoose1Iv;
            mChoosesIvs[1] = mChoose2Iv;
            mChoosesIvs[2] = mChoose3Iv;
            mChoosesIvs[3] = mChoose4Iv;
            mChoosesIvs[4] = mChoose5Iv;
            mChoosesIvs[5] = mChoose6Iv;
            mChoosesIvs[6] = mChoose7Iv;

            mPoints1Tv = findViewById(R.id.tv_points1);
            mPoints2Tv = findViewById(R.id.tv_points2);
            mPoints3Tv = findViewById(R.id.tv_points3);
            mPoints4Tv = findViewById(R.id.tv_points4);
            mPoints5Tv = findViewById(R.id.tv_points5);
            mPoints6Tv = findViewById(R.id.tv_points6);
            mPoints7Tv = findViewById(R.id.tv_points7);

            mPointTvs[0] = mPoints1Tv;
            mPointTvs[1] = mPoints2Tv;
            mPointTvs[2] = mPoints3Tv;
            mPointTvs[3] = mPoints4Tv;
            mPointTvs[4] = mPoints5Tv;
            mPointTvs[5] = mPoints6Tv;
            mPointTvs[6] = mPoints7Tv;

            mTeasurechest1Iv = findViewById(R.id.iv_teasurechest1);
            mTeasurechest2Iv = findViewById(R.id.iv_teasurechest2);
            mTeasurechest3Iv = findViewById(R.id.iv_teasurechest3);
            mTeasurechest4Iv = findViewById(R.id.iv_teasurechest4);
            mTeasurechest5Iv = findViewById(R.id.iv_teasurechest5);
            mTeasurechest6Iv = findViewById(R.id.iv_teasurechest6);
            mTeasurechest7Iv = findViewById(R.id.iv_teasurechest7);

            mTeasurechesIvs[0] = mTeasurechest1Iv;
            mTeasurechesIvs[1] = mTeasurechest2Iv;
            mTeasurechesIvs[2] = mTeasurechest3Iv;
            mTeasurechesIvs[3] = mTeasurechest4Iv;
            mTeasurechesIvs[4] = mTeasurechest5Iv;
            mTeasurechesIvs[5] = mTeasurechest6Iv;
            mTeasurechesIvs[6] = mTeasurechest7Iv;

            //初始化签到控件的展示
//        initCheckInView();
//        mContinuousDayTv.setText(String.valueOf(mLevelPoints.continuous_days));


            if (isCheckInYesterday) {

                //昨天有签到
                mContinuousDayTv.setText(String.valueOf(mLevelPoints.continuous_days));

                if (mLevelPoints.daily_check_in) {
                    mCurrentDay = mLevelPoints.continuous_days;
                } else {
                    mCurrentDay = mLevelPoints.continuous_days + 1;
                }

            } else {

                //昨天没有签到
                mCurrentDay = 1;
                if (mLevelPoints.daily_check_in) {
                    mContinuousDayTv.setText(String.valueOf(mLevelPoints.continuous_days));
                } else {
                    mContinuousDayTv.setText("0");
                }

            }

            initCheckInView();

            //如果今天签到了，并且有宝箱，则打开宝箱
            if (mLevelPoints.daily_check_in) {

                mCheckInTv.setEnabled(false);
                mCheckInTv.setBackgroundColor(CommUtils.getColor(R.color.gray));

                Integer day = mDays.get(mCurrentDayPosition);

                if (day == 7 || day == 14 || day == 30) {

                    mTeasurechesIvs[mCurrentDayPosition].setImageResource(R.drawable.iv_daily_login_open_teasurechest);
                } else {

                    mPointTvs[mCurrentDayPosition].setVisibility(View.GONE);
                    mChoosesIvs[mCurrentDayPosition].setVisibility(View.VISIBLE);
                }
            }

        }

    }

    //签到的控件展示
    @SuppressLint("SetTextI18n")
    private void initCheckInView() {

        mCurrentDayPosition = mCurrentDay % 7;
        if (mCurrentDayPosition == 0) {

            mCurrentDayPosition = 6;
        } else {

            mCurrentDayPosition = mCurrentDayPosition - 1;
        }

        //以30天为周期，当前是第几天
        int currentDay = mCurrentDay % 30;

        for (int i = 0; i < mDateTvs.length; i++) {

            //确定日期
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, i - mCurrentDayPosition);

            if (i == mCurrentDayPosition) {

                mDateTvs[i].setText("今天");
            } else {

                mDateTvs[i].setText(DateAndTimeUtil.stampToDate21(String.valueOf(calendar.getTime().getTime())));

            }


            //计算当前7天是哪几天
            if (currentDay + i - mCurrentDayPosition > 0) {

                mDays.add(currentDay + i - mCurrentDayPosition);
            } else {

                mDays.add(30 + currentDay + i - mCurrentDayPosition);

            }

            if (i < mCurrentDayPosition) {

                mChoosesIvs[i].setVisibility(View.VISIBLE);
                mPointTvs[i].setVisibility(View.GONE);

            }

        }

        if (mDays.contains(7)) {

            int index = mDays.indexOf(7);
            boolean isOpen = index < mCurrentDayPosition;
            setTeasureches(index, isOpen);
            return;

        }

        if (mDays.contains(14)) {

            int index = mDays.indexOf(14);
            boolean isOpen = index < mCurrentDayPosition;
            setTeasureches(index, isOpen);
            return;

        }

        if (mDays.contains(30)) {

            int index = mDays.indexOf(30);
            boolean isOpen = index < mCurrentDayPosition;
            setTeasureches(index, isOpen);
            return;

        }

    }

    //设置宝箱
    private void setTeasureches(int position, boolean isOpen) {

        mTeasurechesIvs[position].setVisibility(View.VISIBLE);
        mChoosesIvs[position].setVisibility(View.INVISIBLE);
        mPointTvs[position].setVisibility(View.INVISIBLE);

        if (isOpen) {

            mTeasurechesIvs[position].setImageResource(R.drawable.iv_daily_login_open_teasurechest);

        } else {

            mTeasurechesIvs[position].setImageResource(R.drawable.iv_daily_login_teasurechest);
        }

    }

    @Override
    public void startObserve() {

    }

    @Override
    public void onClick(View view) {

        int viewId = view.getId();
        if (viewId == R.id.tv_daily_login_check_in) {

            //积分+2移动动画
            mPointTvs[mCurrentDayPosition].setText("+2");
            addPointsToTotal(mPointTvs[mCurrentDayPosition]);

        } else if (viewId == R.id.tv_goto_rewards) {

            RewardsActivity.Companion.startInstance();

        }

    }

    //增加积分的动画
    private void addPointsToTotal(TextView pointsTv) {

        // 创造出执行动画的主题goodsImg（这个图片就是执行动画的图片,从开始位置出发,经过一个抛物线（贝塞尔曲线）,移动到购物车里）
        TextView pointTv = new TextView(mActivity);
//        goods.setImageDrawable(goodsImg.getDrawable());
        pointTv.setBackgroundResource(R.drawable.iv_daily_login_unchoice);
        pointTv.setText(pointsTv.getText().toString().trim());

        pointTv.setTextColor(CommUtils.getColor(R.color.white));
        pointTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 8);
        pointTv.setGravity(Gravity.CENTER);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(CommUtils.dip2px(20), CommUtils.dip2px(20));
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
//        mShoppingCartRly.addView(goods, params);
        mRootRl.addView(pointTv, params);

        // 得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
        int[] parentLocation = new int[2];
//        mShoppingCartRly.getLocationInWindow(parentLocation);
        mRootRl.getLocationInWindow(parentLocation);

        // 得到商品图片的坐标（用于计算动画开始的坐标）
        int startLoc[] = new int[2];
        pointsTv.getLocationInWindow(startLoc);

        // 得到购物车图片的坐标(用于计算动画结束后的坐标)
        int endLoc[] = new int[2];
//        mShoppingCartIv.getLocationInWindow(endLoc);
        mPointsTv.getLocationInWindow(endLoc);

        // 开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
        float startX = startLoc[0] - parentLocation[0] + pointsTv.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + pointsTv.getHeight() / 2;

        // 商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
//        float toX = endLoc[0] - parentLocation[0] + mShoppingCartIv.getWidth() / 5;
        float toX = endLoc[0] - parentLocation[0] + mPointsTv.getWidth() / 5;
        float toY = endLoc[1] - parentLocation[1];

        // 开始绘制贝塞尔曲线
        Path path = new Path();
        // 移动到起始点（贝塞尔曲线的起点）
        path.moveTo(startX, startY);
        // 使用二阶贝塞尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
//        path.quadTo((startX + toX) / 2, startY, toX, toY);
        path.quadTo(startX, (startY + toY) / 2, toX, toY);
        // mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，如果是true，path会形成一个闭环
        mPathMeasure = new PathMeasure(path, false);

        // 属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);

        // 匀速线性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // 获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                // mCurrentPosition此时就是中间距离点的坐标值
                mPathMeasure.getPosTan(value, mCurrentPosition, null);
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                pointTv.setTranslationX(mCurrentPosition[0]);
                pointTv.setTranslationY(mCurrentPosition[1]);
            }
        });

        // 开始执行动画
        valueAnimator.start();

        // 动画结束后的处理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                // 购物车商品数量加1
//                goodsCount ++;
//                isShowCartGoodsCount();
//                mShoppingCartCountTv.setText(String.valueOf(goodsCount));
                // 把执行动画的商品图片从父布局中移除
//                mShoppingCartRly.removeView(goods);
                mRootRl.removeView(pointTv);

                mPoint = mPoint + Integer.valueOf(pointsTv.getText().toString());

                mPointsTv.setText(PointFormatUtils.formatPoints(String.valueOf(mPoint)));

                if (mDays.get(mCurrentDayPosition) == 7 && !isBoxOpened) {

                    isBoxOpened = true;
                    //设置宝箱金额
                    mPointTvs[mCurrentDayPosition].setText("+10");
                    //添加开启宝箱的第二次动画
                    addPointsToTotal(mPointTvs[mCurrentDayPosition]);
                    //打卡宝箱
                    mTeasurechesIvs[mCurrentDayPosition].setImageResource(R.drawable.iv_daily_login_open_teasurechest);

                } else if (mDays.get(mCurrentDayPosition) == 14 && !isBoxOpened) {

                    isBoxOpened = true;
                    mPointTvs[mCurrentDayPosition].setText("+20");
                    addPointsToTotal(mPointTvs[mCurrentDayPosition]);
                    mTeasurechesIvs[mCurrentDayPosition].setImageResource(R.drawable.iv_daily_login_open_teasurechest);

                } else if (mDays.get(mCurrentDayPosition) == 30 && !isBoxOpened) {

                    isBoxOpened = true;
                    mPointTvs[mCurrentDayPosition].setText("+50");
                    addPointsToTotal(mPointTvs[mCurrentDayPosition]);
                    mTeasurechesIvs[mCurrentDayPosition].setImageResource(R.drawable.iv_daily_login_open_teasurechest);

                } else {

                    if (!isBoxOpened) {

                        mPointTvs[mCurrentDayPosition].setVisibility(View.GONE);
                        mChoosesIvs[mCurrentDayPosition].setVisibility(View.VISIBLE);
                    }

                }

            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
    }

}
