package com.unis.sxzcl.widget.menu;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.unis.sxzcl.R;
import com.unis.sxzcl.databinding.MenuLabelItemLayoutBinding;
import com.xyxsbj.mylibrary.tool.DPTool;

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

/**
 * 包名: com.unis.sxzcl.widget.menu
 * 类名: SimpleDownMenu
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2017/10/18
 * 更新人:
 * 更新时间: 2020/11/26 15:57
 * 更新说明:
 * 版本号: 1.0
 */
public class SimpleDownMenu extends LinearLayout {

    private Context mContext;
    private boolean verLine = true;//是否带中间分割线
    private int mTextColor = 0;//未点击颜色
    private int mTextSelColor = 0;//点击颜色
    private float mTextSize = 0;//文字大小

    private RelativeLayout oldView;
    private int selPositon = -1;
    private PopupWindow popupWindow;
    private FrameLayout popContainer;
    private List<SimpleDownModel> modelList;
    private List<View> popupViews;
    private View popBackView;
    private View popView;

    private List<RelativeLayout> itemView = new ArrayList<>();

    public SimpleDownMenu(Context context) {
        super(context, null);
        mContext = context;
    }

    public SimpleDownMenu(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
        mContext = context;
    }

    public SimpleDownMenu(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        setOrientation(HORIZONTAL);
    }

    /*** 字体未选中颜色 ***/
    public SimpleDownMenu setTextColor(int textColor) {
        mTextColor = textColor;
        return this;
    }

    /*** 设置字体已选中颜色 ***/
    public SimpleDownMenu setTextSelColor(int textSelColor) {
        mTextSelColor = textSelColor;
        return this;
    }

    /*** 设置是否绘制竖向分割线 ***/
    public SimpleDownMenu setVerLine(boolean isVerLine) {
        this.verLine = isVerLine;
        return this;
    }

    /*** 设置文字大小 ***/
    public SimpleDownMenu setTextSize(float size) {
        mTextSize = size;
        return this;
    }

    /**
     * 初始化方法
     *
     * @param tabTexts 标题集合
     * @param views    弹出框View集合
     * @return
     */
    public SimpleDownMenu initMenu(List<SimpleDownModel> tabTexts, View... views) {
        popupViews = new ArrayList<>();
        for (int i = 0; i < views.length; i++) {
            popupViews.add(views[i]);
        }
        initMenu(tabTexts, popupViews);
        return this;
    }

    /**
     * 初始化方法
     *
     * @param tabTexts   标题集合
     * @param popupViews 弹出框View集合
     * @return
     */
    public SimpleDownMenu initMenu(List<SimpleDownModel> tabTexts, List<View> popupViews) {
        this.modelList = tabTexts;
        this.popupViews = popupViews;
        setBackgroundResource(R.drawable.simple_menu_bg);
        //初始化筛选标题
        if (verLine) {//带中间分割线
            for (int i = 0; i < tabTexts.size(); i++) {
                addTab(tabTexts.get(i), i);
                if (i < tabTexts.size() - 1)
                    addVerLines();
            }
        } else {//不带中间分割线
            for (int i = 0; i < tabTexts.size(); i++) addTab(tabTexts.get(i), i);
        }

//        popBackView.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                closeMenu();
//            }
//        });
        return this;
    }

    @SuppressLint("WrongConstant")
    private void initPopupWindow() {
        //初始化Popupwindow
        popView = View.inflate(mContext, R.layout.popup_simple_layout, null);
        popContainer = popView.findViewById(R.id.popContainer);
//        popBackView = popView.findViewById(R.id.popBackView);
//        popupWindow = new PopupWindow(getWindowWidth() / 4 * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow = new PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(popView);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//        popupWindow.setAnimationStyle(R.style.anim_simple_menu);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                BaseActivity baseActivity = (BaseActivity) mContext;
//                if (baseActivity != null)
//                    baseActivity.hideNavigation();
                closeMenu();
            }
        });
    }

    private int getWindowWidth() {
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }



    /*** 创建tab的布局 ***/
    public SimpleDownMenu addTab(SimpleDownModel model, int position) {
        MenuLabelItemLayoutBinding binding = MenuLabelItemLayoutBinding.inflate(LayoutInflater.from(mContext));
        RelativeLayout relativeLayout = binding.getRoot();
        addView(relativeLayout, new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        itemView.add(relativeLayout);

        String text;
        if (model.getTextRes() != 0) {
            text = mContext.getResources().getString(model.getTextRes());
        } else {
            text = model.getText();
        }
        binding.tvContent.setText(text);
//        initTextView(relativeLayout, model);
        initImageLeft(binding.ivLeft, model);
        initImageRight(binding.ivRight, model);

        relativeLayout.setTag(position);
        relativeLayout.setOnClickListener(this::switchMenu);
        return this;
    }

    /*** 绘制中间竖线 ***/
    private void addVerLines() {
        View v = new View(mContext);
        v.setBackgroundResource(R.color.colorLine2);
        LayoutParams params = new LayoutParams(1, LayoutParams.MATCH_PARENT);
        params.topMargin = DPTool.dp2px(mContext, 8);
        params.bottomMargin = DPTool.dp2px(mContext, 8);
        addView(v, params);
    }

    /*** 创建tab的文字布局 ***/
    private void initTextView(RelativeLayout view, SimpleDownModel model) {
        String text;
        if (model.getTextRes() != 0) {
            text = mContext.getResources().getString(model.getTextRes());
        } else {
            text = model.getText();
        }
        TextView textView = new TextView(mContext);
        textView.setText(text);
        if (mTextSize != 0)
            textView.setTextSize(mTextSize);
        textView.setSingleLine();
        textView.setEllipsize(TextUtils.TruncateAt.END);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        textView.setLayoutParams(params);
        view.addView(textView);
    }

    /*** 创建tab的图片的布局 ***/
    private void initImageLeft(ImageView imageView, SimpleDownModel model) {
        Drawable drawable = null;
        if (model.getLeftDraRes() != 0) {
            drawable = ContextCompat.getDrawable(mContext, model.getLeftDraRes());
        } else if (model.getLeftDra() != null) {
            drawable = model.getLeftDra();
        } else {
            imageView.setVisibility(GONE);
        }
//        view.addView(initImageView(drawable));
        imageView.setImageDrawable(drawable);
    }

    private void initImageRight(ImageView imageView, SimpleDownModel model) {
        Drawable drawable = null;
        if (model.getRightDraRes() != 0) {
            drawable = ContextCompat.getDrawable(mContext, model.getRightDraRes());
        } else if (model.getRightDra() != null) {
            drawable = model.getRightDra();
        } else {
            imageView.setVisibility(GONE);
        }

//        ImageView imageView = initImageView(drawable);
//        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
//        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
//        imageView.setLayoutParams(params);
//        view.addView(imageView);
        imageView.setImageDrawable(drawable);
    }

    private ImageView initImageView(Drawable drawable) {
        ImageView imageView = new ImageView(mContext);
        if (drawable != null)
            imageView.setImageDrawable(drawable);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        int ma = DPTool.dp2px(mContext, 8);
        params.leftMargin = ma;
        params.rightMargin = ma;
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        imageView.setLayoutParams(params);
        return imageView;
    }

    /**
     * 切换菜单
     */
    private void switchMenu(View view) {
        int position = (int) view.getTag();
        if (selPositon != -1) {
            ImageView leftView = (ImageView) oldView.getChildAt(0);
            TextView textView = (TextView) oldView.getChildAt(1);
            ImageView rightView = (ImageView) oldView.getChildAt(2);
            setMenuTextColor(textView, false);
            SimpleDownModel model = modelList.get(selPositon);
            if (model.isLeftAnimation())
                setAnimationOut(leftView);
            if (model.isRightAnimation())
                setAnimationOut(rightView);
        } else {
            showPopupWindow();
        }
        RelativeLayout childAt = (RelativeLayout) view;
        ImageView leftView = (ImageView) childAt.getChildAt(0);
        TextView textView = (TextView) childAt.getChildAt(1);
        ImageView rightView = (ImageView) childAt.getChildAt(2);
        if (position != selPositon) {
            selPositon = position;
            setMenuTextColor(textView, true);
            SimpleDownModel model = modelList.get(selPositon);
            if (model.isLeftAnimation())
                setAnimationIn(leftView);
            if (model.isRightAnimation())
                setAnimationIn(rightView);
            popContainer.removeAllViews();
            popContainer.addView(popupViews.get(position));
        } else {
            closeMenu();
        }
        oldView = childAt;
    }

    private void showPopupWindow() {
        if (popupWindow == null)
            initPopupWindow();
//        int[] location = new int[2];
//        getLocationOnScreen(location);
//        int v = (int) (getX() - getWindowWidth() / 4);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            popupWindow.showAsDropDown(this, -v, 0, Gravity.CENTER);
//        } else {
//        popupWindow.showAtLocation(this, Gravity.NO_GRAVITY, getWindowWidth() / 4, location[1] + getHeight());
        popupWindow.showAsDropDown(this);
//        }
//        setPopAnimationIn(popView);
    }

    //设置文字颜色 是否选中
    private void setMenuTextColor(TextView textView, boolean b) {
        if (b) {//选中
            if (mTextSelColor == 0)
                textView.setTextColor(ContextCompat.getColor(mContext, R.color.colorAccent));
            else
                textView.setTextColor(mTextSelColor);
        } else {//未选中
            if (mTextColor == 0)
                textView.setTextColor(ContextCompat.getColor(mContext, R.color.colorText1));
            else
                textView.setTextColor(mTextColor);
        }
    }

    /*** 关闭menu ***/
    public void closeMenu() {
        closeMenu(null, selPositon);
    }

    public void closeMenu(String tabText) {
        closeMenu(tabText, selPositon);
    }

    public void closeMenu(String tabText, int position) {
        selPositon = position;
        if (selPositon != -1) {
            RelativeLayout view = itemView.get(position);
            ImageView leftView = (ImageView) view.getChildAt(0);
            TextView textView = (TextView) view.getChildAt(1);
            if (tabText != null)
                textView.setText(tabText);
            setMenuTextColor(textView, false);

            ImageView rightView = (ImageView) view.getChildAt(2);
            SimpleDownModel model = modelList.get(selPositon);
            if (model.isLeftAnimation())
                setAnimationOut(leftView);
            if (model.isRightAnimation())
                setAnimationOut(rightView);
            selPositon = -1;
        }
//            oldView = null;
        boolean showing = popupWindow.isShowing();
        if (showing) {
            popupWindow.dismiss();
        }
    }

    /*** 设置当前展开的标题内容 ***/
    public void setTabText(String text) {
        TextView textView = (TextView) oldView.getChildAt(1);
        textView.setText(text);
    }

    private void setAnimationIn(View view) {
        ObjectAnimator//
                .ofFloat(view, "rotation", 0.0F, 180.0F)//
                .setDuration(200)//
                .start();
    }

    private void setAnimationOut(View view) {
        ObjectAnimator//
                .ofFloat(view, "rotation", -180.0F, 0.0F)//
                .setDuration(200)//
                .start();
    }


    private void setPopAnimationIn(View view) {
        AnimationSet set = new AnimationSet(true);
        set.setDuration(200);
        Animation scaleAnimation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0);
        Animation alphaAnimation = new AlphaAnimation(0, 1);
        set.addAnimation(scaleAnimation);
        set.addAnimation(alphaAnimation);
        view.startAnimation(set);
    }

    private void setPopAnimationOut(View view) {
        AnimationSet set = new AnimationSet(true);
        set.setDuration(200);
        Animation scaleAnimation = new ScaleAnimation(1, 0, 1, 0);
        Animation alphaAnimation = new AlphaAnimation(1, 0);
        set.addAnimation(scaleAnimation);
        set.addAnimation(alphaAnimation);
    }

}
