package com.cooleshow.base.widgets;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.cooleshow.base.utils.Utils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;


public class CommonPopupWindow extends PopupWindow {
    final PopupController controller;
    private static WindowManager wm;

    @Override
    public int getWidth() {
        return controller.mPopupView.getMeasuredWidth();
    }

    @Override
    public int getHeight() {
        return controller.mPopupView.getMeasuredHeight();
    }

    public interface ViewInterface {
        void getChildView(View view, int layoutResId);
    }

    private CommonPopupWindow(Context context) {
        controller = new PopupController(context, this);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        controller.setBackGroundLevel(1.0f);
    }

    public static class Builder {
        private final PopupController.PopupParams params;
        private ViewInterface listener;

        public Builder(Context context) {
            params = new PopupController.PopupParams(context);
        }

        /**
         * @param layoutResId 设置PopupWindow 布局ID
         * @return Builder
         */
        public Builder setView(int layoutResId) {
            params.mView = null;
            params.layoutResId = layoutResId;
            return this;
        }

        /**
         * @param view 设置PopupWindow布局
         * @return Builder
         */
        public Builder setView(View view) {
            params.mView = view;
            params.layoutResId = 0;
            return this;
        }

        /**
         * 设置子View
         *
         * @param listener ViewInterface
         * @return Builder
         */
        public Builder setViewOnclickListener(ViewInterface listener) {
            this.listener = listener;
            return this;
        }

        /**
         * 设置宽度和高度 如果不设置 默认是wrap_content
         *
         * @param width 宽
         * @return Builder
         */
        public Builder setWidthAndHeight(int width, int height) {
            params.mWidth = width;
            params.mHeight = height;
            return this;
        }

        /**
         * 设置背景灰色程度
         *
         * @param level 0.0f-1.0f
         * @return Builder
         */
        public Builder setBackGroundLevel(float level) {
            params.isShowBg = true;
            params.bg_level = level;
            return this;
        }

        /**
         * 是否可点击Outside消失
         *
         * @param touchable 是否可点击
         * @return Builder
         */
        public Builder setOutsideTouchable(boolean touchable) {
            params.isTouchable = touchable;
            return this;
        }

        /**
         * 设置动画
         *
         * @return Builder
         */
        public Builder setAnimationStyle(int animationStyle) {
            params.isShowAnim = true;
            params.animationStyle = animationStyle;
            return this;
        }

        public CommonPopupWindow create() {
            final CommonPopupWindow popupWindow = new CommonPopupWindow(params.mContext);
            params.apply(popupWindow.controller);
            if (listener != null && params.layoutResId != 0) {
                listener.getChildView(popupWindow.controller.mPopupView, params.layoutResId);
            }
            measureWidthAndHeight(popupWindow.controller.mPopupView);
            return popupWindow;
        }

        public void measureWidthAndHeight(View view) {
            int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(widthMeasureSpec, heightMeasureSpec);
        }

    }

    /**
     * 在Android7.0以后，PopupWindow的显示会有一个判断，当PopupWindow的高度大于屏幕的剩余高度时，会往控件上方超出。
     *
     * @param anchor
     */
    @Override
    public void showAsDropDown(View anchor) {
        adapterApiV24ForShowAsDropDown(anchor, 0, 0);
        super.showAsDropDown(anchor);
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        adapterApiV24ForShowAsDropDown(anchor, xoff, yoff);
        super.showAsDropDown(anchor, xoff, yoff);
    }


    public void adapterApiV24ForShowAsDropDown(View parent, int xoff, int offsetY) {

        if (null == parent) {
            return;
        }
        if (Build.VERSION.SDK_INT >= 24) {
            Rect visibleFrame = new Rect();
            parent.getGlobalVisibleRect(visibleFrame);
            int height;
            /**
             * 判断是否有导航栏
             */
            if (isShowNavBar(getContentView().getContext())) {
                height = parent.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom + Math.abs(offsetY);
            } else {
                /**
                 * 获取物理真实高度 才能在android 7.0以上遮住下面的TabHost
                 */
                height = getRealHeight() - visibleFrame.bottom + Math.abs(offsetY);
            }
            setHeight(height);
        }
        super.showAsDropDown(parent, xoff, offsetY);
    }

    public boolean isShowNavBar(Context context) {
        if (null == context) {
            return false;
        }
/**
 * 获取应用区域高度
 */
        Rect outRect1 = new Rect();
        try {
            ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
        } catch (ClassCastException e) {
            e.printStackTrace();
            return false;
        }
        int activityHeight = outRect1.height();
/**
 * 获取状态栏高度
 */
        int statuBarHeight = getStatusBarHeight();
/**
 * 屏幕物理高度 减去 状态栏高度
 */
        int remainHeight = getRealHeight() - statuBarHeight;
/**
 * 剩余高度跟应用区域高度相等 说明导航栏没有显示 否则相反
 */
        if (activityHeight == remainHeight) {
            return false;
        } else {
            return true;
        }

    }

    /**
     * 获取真实屏幕高度
     *
     * @return
     */
    public int getRealHeight() {
        if (null == wm) {
            wm = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE);
        }
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wm.getDefaultDisplay().getRealSize(point);
        } else {
            wm.getDefaultDisplay().getSize(point);
        }
        return point.y;
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    public int getStatusBarHeight() {
        return QMUIStatusBarHelper.getStatusbarHeight(Utils.getApp());
    }
}