package com.efounder.chat.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Interpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.activity.LuckMoneyDetailActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.item.RedPackageItem;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.utilcode.util.ScreenUtils;

import net.sf.json.JSONObject;

import org.greenrobot.eventbus.EventBus;

import static com.efounder.chat.item.RedPackageItem.PACKAGE_RECEIVED;

/**
 * 抢红包dialog
 *
 * @author YQS 2018/08/06
 */
public class ScrambleRedPackageDialogFragment extends DialogFragment implements View.OnClickListener {

    private static final String TAG = "RedPackageDFragment";
    private View rootView;
    private ImageView ivAvatar;
    private TextView tvNickname;
    private TextView tvTip1;
    private TextView tvMessage;
    private ImageButton butOpen;
    private ImageView ivClose;
    private TextView tvLookLuck;
    private ImageView ivBottom;
    private byte chatType;//聊天类型 群聊单聊
    IMStruct002 imStruct002 ;

    public static ScrambleRedPackageDialogFragment newInstance() {

        Bundle args = new Bundle();
       // args.putSerializable("imStruct002", imStruct002);
        ScrambleRedPackageDialogFragment fragment = new ScrambleRedPackageDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }
    public  void setMessage(IMStruct002 imStruct002){
        this.imStruct002 = imStruct002;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //隐藏标题栏
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (savedInstanceState!=null && savedInstanceState.containsKey("imStruct002")){
            imStruct002= (IMStruct002) savedInstanceState.getSerializable("imStruct002");
        }
        rootView = inflater.inflate(R.layout.wechatview_dialog_scramble_red_package, container, false);
        initView(rootView);
        initData();
        return rootView;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("imStruct002",imStruct002);
    }

    @Override
    public void onStart() {
        super.onStart();
        getDialog().getWindow().setBackgroundDrawableResource(R.color.transparent);
        getDialog().getWindow()
                .setLayout(ScreenUtils.getScreenWidth() * 4 / 5, WindowManager.LayoutParams.WRAP_CONTENT);
        getDialog().setCanceledOnTouchOutside(true);
        getDialog().setCancelable(true);

        setViewScaleAnimtor(rootView, 800, 0.7F, 1f);
    }

    private void initView(View rootView) {
        ivAvatar = (ImageView) rootView.findViewById(R.id.iv_avatar);
        tvNickname = (TextView) rootView.findViewById(R.id.tv_nickname);
        tvTip1 = (TextView) rootView.findViewById(R.id.tv_tip1);
        tvMessage = (TextView) rootView.findViewById(R.id.tv_message);
        butOpen = (ImageButton) rootView.findViewById(R.id.but_open);
        ivClose = (ImageView) rootView.findViewById(R.id.iv_close);
        tvLookLuck = (TextView) rootView.findViewById(R.id.tv_lookluck);
        ivBottom = (ImageView) rootView.findViewById(R.id.iv_bottom);
        ivClose.setOnClickListener(this);
        butOpen.setOnClickListener(this);
        tvLookLuck.setOnClickListener(this);

    }

    private void initData() {
//        IMStruct002 imStruct002 = imStruct002;
        chatType = imStruct002.getToUserType();
        User user = WeChatDBManager.getInstance().getOneUserById(imStruct002.getFromUserId());
        tvNickname.setText(user.getReMark());
        LXGlideImageLoader.getInstance().showRoundUserAvatar(ivAvatar.getContext(), ivAvatar,
                user.getAvatar(), LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);
        try {
            JSONObject jsonObject = JSONObject.fromObject(imStruct002.getMessage());
            if (imStruct002.getToUserType() == StructFactory.TO_USER_TYPE_PERSONAL) {
                tvTip1.setText(R.string.wechatview_give_you_red);
            } else {


                if (jsonObject.optInt("luckMode", 0) == 0) {
                    tvTip1.setText(R.string.wechatview_red_random_amount);
                } else {
                    tvTip1.setText(R.string.wechatview_send_a_red);
                }

            }
            tvMessage.setText(jsonObject.optString("leaveMessage"));
            //查看红包状态
            int packageState = jsonObject.optInt("packageState", 0);
            if (packageState == RedPackageItem.PACKAGE_WITHOUT) {
                redPackageRunOut();
            } else if (packageState == RedPackageItem.PACKAGE_TIME_OUT) {
                if (packageState == RedPackageItem.PACKAGE_WITHOUT) {
                    redPackageTimeOut();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //红包已抢光
    private void redPackageRunOut() {
        tvTip1.setVisibility(View.INVISIBLE);
        ivBottom.setVisibility(View.INVISIBLE);
        butOpen.setVisibility(View.INVISIBLE);
        tvMessage.setText(R.string.wechatview_slow_hand);
        tvLookLuck.setVisibility(View.VISIBLE);
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            tvLookLuck.setText(R.string.wechatview_view_picking_details);
        } else {
            tvLookLuck.setText(R.string.wechatview_look_luck);
        }
    }

    //红包已过期
    private void redPackageTimeOut() {
        tvTip1.setVisibility(View.INVISIBLE);
        ivBottom.setVisibility(View.INVISIBLE);
        butOpen.setVisibility(View.INVISIBLE);
        tvMessage.setText(R.string.wechatview_red_expired);
        tvLookLuck.setVisibility(View.VISIBLE);
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            tvLookLuck.setText(R.string.wechatview_view_picking_details);
        } else {
            tvLookLuck.setText(R.string.wechatview_look_luck);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_close) {
            dismiss();
        } else if (v.getId() == R.id.tv_lookluck) {
            LuckMoneyDetailActivity.start(getActivity(), imStruct002);
            dismiss();
        } else if (v.getId() == R.id.but_open) {
            //来点动画在打开红包
            ObjectAnimator animator = ObjectAnimator.ofFloat(butOpen, "rotationY", 0f, 90f);
            animator.setDuration(120);


            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    butOpen.setImageDrawable(getResources().getDrawable(R.drawable.wecahtview_red_package_back));
                    ObjectAnimator animator1 = ObjectAnimator.ofFloat(butOpen, "rotationY", 90f, 180f);
                    animator1.setDuration(120);
                    animator1.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            dismiss();
                            //标记红包为已打开（更新数据库的消息）
                            JSONObject jsonObject = JSONObject.fromObject(imStruct002.getMessage());
                            jsonObject.put("packageState",PACKAGE_RECEIVED);
                            imStruct002.setMessage(jsonObject.toString());
                            JFMessageManager.dbManager.update(imStruct002);

                            //通知界面刷新
                            EventBus.getDefault().post(new NotifyChatUIRefreshEvent());
                            //动画完成，抢红包
                            LuckMoneyDetailActivity.startRob(getActivity(),
                                    imStruct002,true);
                        }
                    });
                    animator1.start();

                }
            });
            animator.start();
        }

    }

    /**
     * 设置view缩放动画
     *
     * @param view     view
     * @param duration 持续时间
     */
    private void setViewScaleAnimtor(View view, long duration, float... values) {
        //https://www.jianshu.com/p/649bace2e164 属性动画的使用
        AnimatorSet animatorSet1 = new AnimatorSet();//组合动画
        ObjectAnimator scaleX1 = ObjectAnimator.ofFloat(view, "scaleX", values);
        ObjectAnimator scaleY1 = ObjectAnimator.ofFloat(view, "scaleY", values);

        animatorSet1.setDuration(duration);
//        animatorSet1.setInterpolator(new DecelerateInterpolator());
        animatorSet1.setInterpolator(new SpringScaleInterpolator(0.4f));

        animatorSet1.play(scaleX1).with(scaleY1);//两个动画同时开始
        animatorSet1.start();
    }

    public class SpringScaleInterpolator implements Interpolator {
        //弹性因数
        private float factor;

        public SpringScaleInterpolator(float factor) {
            this.factor = factor;
        }

        @Override
        public float getInterpolation(float input) {

            return (float) (Math.pow(2, -10 * input) * Math.sin((input - factor / 4) * (2 * Math.PI) / factor) + 1);
        }
    }
}
