package com.cooleshow.student.ui.live.floatPop;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;


import com.cooleshow.base.common.AppManager;
import com.cooleshow.base.utils.AppUtils;
import com.cooleshow.base.utils.UiUtils;
import com.cooleshow.base.utils.helper.QMUIDisplayHelper;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.student.R;

import java.util.List;

import cn.rongcloud.rtc.api.stream.RCRTCVideoView;
import cn.rongcloud.rtc.core.RendererCommon;

/**
 * Author by pq, Date on 2022/5/13.
 * 悬浮窗
 */
public class FloatWindowHelper implements View.OnTouchListener {
    public static final int REQUEST_OVERLAY_CODE = 5000;
    private Context mContext;
    private View mContentView;
    private WindowManager.LayoutParams mFloatParams;
    private WindowManager mWindowManager;
    private RelativeLayout mLiveContainer;
    private int maxWidth;
    private int maxHeight;
    private int maxDragX = 0;//控制最大拖拽的坐标
    private int maxDragY = 0;//控制最大拖拽的坐标
    private int initX = 0;//初始位置坐标
    private int initY = 0;//初始位置坐标
    private OnEventListener mEventListener;
    private boolean isLiveFromPc = true;

    public FloatWindowHelper(Context context, OnEventListener eventListener) {
        mContext = context;
        this.mEventListener = eventListener;
        initView();
    }

    private void setDefaultParams() {
        int deviceWidth = QMUIDisplayHelper.getScreenWidth(mContext);
        int deviceHeight = QMUIDisplayHelper.getScreenHeight(mContext);
        int orientation = mContext.getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            maxWidth = deviceHeight / 2;
            maxDragX = deviceHeight - maxWidth;
            maxHeight = UiUtils.getHeightAtRatio16_9(mContext, maxWidth);
            int actionBarHeight = QMUIDisplayHelper.getActionBarHeight(mContext);
            int statusBarHeight = QMUIStatusBarHelper.getStatusbarHeight(mContext);
            maxDragY = deviceWidth - actionBarHeight - statusBarHeight - maxHeight;
        } else {
            if (isLiveFromPc) {
                //PC端是16:9的比例尺寸
                maxWidth = deviceWidth / 2;
                maxHeight = UiUtils.getHeightAtRatio16_9(mContext, maxWidth);
            } else {
                maxWidth = deviceWidth / 4;
                float ratio = (float) deviceWidth / (float) deviceHeight;
                maxHeight = (int) (maxWidth / ratio);
            }
            maxDragX = deviceWidth - maxWidth;
            maxDragY = deviceHeight - maxHeight;
        }
        initX = deviceWidth - maxWidth - 50;
        initY = maxDragY - 300;
    }

    /**
     * 判断是否有悬浮窗权限
     *
     * @param activity
     * @return
     */
    public static boolean requestOverlayPermission(Activity activity, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(activity)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + activity.getPackageName()));
                activity.startActivityForResult(intent, requestCode);
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public boolean isLiveFromPc() {
        return isLiveFromPc;
    }

    public void setLiveFromPc(boolean liveFromPc) {
        isLiveFromPc = liveFromPc;
        //设置默认参数
        setDefaultParams();
    }

    /**
     * 判断是否有悬浮窗权限
     *
     * @param activity
     * @return
     */
    public static boolean requestOverlayPermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(activity)) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    private void initView() {
        mContentView = LayoutInflater.from(mContext).inflate(R.layout.view_live_float_window_layout, null);
        mLiveContainer = mContentView.findViewById(R.id.fl_live_container);
        ImageView iv_close = mContentView.findViewById(R.id.iv_close);
        mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTopApp(mContext);
            }
        });
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEventListener != null) {
                    mEventListener.onClose();
                }
            }
        });
    }

    public void showFloatingWindowView(Context context) {
        // 获取系统窗口管理服务
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        // 悬浮窗口参数设置及返回
        mFloatParams = getParams();
        // 设置窗口触摸移动事件
        mContentView.setOnTouchListener(this);
        // 悬浮窗生成
        mWindowManager.addView(mContentView, mFloatParams);
    }

    private WindowManager.LayoutParams getParams() {
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        //设置悬浮窗口类型
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        //设置悬浮窗口属性
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        //设置悬浮窗口透明
        layoutParams.format = PixelFormat.TRANSLUCENT;
        //设置悬浮窗口长宽数据
        layoutParams.width = maxWidth;
        layoutParams.height = maxHeight;
        //设置悬浮窗显示位置
        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        layoutParams.x = initX;
        layoutParams.y = initY;
        return layoutParams;
    }

    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    int mTouchStartX = 0;
    int mTouchStartY = 0;
    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    int mStartX = 0;
    int mStartY = 0;
    //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    boolean isMove = false;

    @Override
    public boolean onTouch(View v, MotionEvent motionEvent) {
        int action = motionEvent.getAction();
        int x = (int) motionEvent.getX();
        int y = (int) motionEvent.getY();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isMove = false;
                mTouchStartX = (int) motionEvent.getRawX();
                mTouchStartY = (int) motionEvent.getRawY();
                mStartX = x;
                mStartY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                int nowX = (int) motionEvent.getRawX();
                int nowY = (int) motionEvent.getRawY();
                Log.i("pq", "now:x=" + nowX + "y=" + nowX);
                int offsetX = nowX - mTouchStartX;
                int offsetY = nowY - mTouchStartY;
                Log.i("pq", "start:x=" + mTouchStartX + "y=" + mTouchStartY);
                mFloatParams.x += offsetX;
                mFloatParams.y += offsetY;
                if (mFloatParams.x < 0) {
                    mFloatParams.x = 0;
                }
                if (mFloatParams.x > maxDragX) {
                    mFloatParams.x = maxDragX;
                }
                if (mFloatParams.y < 0) {
                    mFloatParams.y = 0;
                }
                if (mFloatParams.y > maxDragY) {
                    mFloatParams.y = maxDragY;
                }

                Log.i("pq", "move:x=" + offsetX + "y=" + offsetY);
                Log.i("pq", "moveAfter:x=" + mFloatParams.x + "y=" + mFloatParams.y);
                mWindowManager.updateViewLayout(mContentView, mFloatParams);
                mTouchStartX = nowX;
                mTouchStartY = nowY;
                float deltaX = x - mStartX;
                float deltaY = y - mStartY;
                if (Math.abs(deltaX) >= 5 || Math.abs(deltaY) >= 5) {
                    isMove = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                break;
        }
        //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
        return isMove;
    }

    public void dismiss() {
        if (mContext == null) {
            return;
        }
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        if (windowManager != null && mContentView != null && mContentView.getParent() != null) {
            windowManager.removeView(mContentView);
        }
        if (mLiveContainer != null) {
            mLiveContainer.removeAllViews();
        }
        this.mContext = null;
    }

    public void addVideoView(List<RCRTCVideoView> videoViews) {
        if (videoViews != null && videoViews.size() > 0) {
            mLiveContainer.removeAllViews();
            for (int i = 0; i < videoViews.size(); i++) {
                RCRTCVideoView videoView = videoViews.get(i);
                ViewGroup parent = (ViewGroup) videoView.getParent();
                if (parent != null) {
                    parent.removeView(videoView);
                }
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                videoView.setScalingType(isLiveFromPc ? RendererCommon.ScalingType.SCALE_ASPECT_FIT : RendererCommon.ScalingType.SCALE_ASPECT_FILL);
                mLiveContainer.addView(videoView, layoutParams);
            }
        }
    }

    /**
     * 返回前台
     *
     * @param context
     */
    public void setTopApp(Context context) {
        if (AppUtils.isApplicationInBackground(context)) {
            //获取ActivityManager
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            //获得当前运行的task(任务)
            List<ActivityManager.RunningTaskInfo> taskInfoList = null;
            if (activityManager != null) {
                taskInfoList = activityManager.getRunningTasks(100);
            }
            if (taskInfoList != null) {
                for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                    //找到本应用的 task，并将它切换到前台
                    if (taskInfo.topActivity != null && taskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
                        activityManager.moveTaskToFront(taskInfo.id, 0);
                        break;
                    }
                }
            }
        } else {
            Activity topActivity = AppManager.Companion.getInstance().currentActivity();
            if (topActivity != null) {
                topActivity.finish();
            }
        }
    }

    public interface OnEventListener {
        void onClose();
    }
}
