package com.ez.ertc.meeting.widget;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import androidx.annotation.ArrayRes;
import androidx.annotation.StringRes;

import com.ez.ertc.meeting.R;
import com.ez.ertc.meeting.utils.ViewUtil;

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

/**
 * 扩展AlertDialog
 * 主要方便做按钮标识
 */
public class EZDialog extends Dialog {

    public static final int STYLE_CENTER = 0;
    public static final int STYLE_BOTTOM = 1;

    public static final int BUTTON_HORIZONTAL = 0;
    public static final int BUTTON_VERTICAL = 2;

    public static final int NO_ACTION_KEY = 0;
    public static final int UNSET_TEXT_COLOR = 0;

    private Builder mBuilder;

    private TextView mTitle;
    private TextView mMessage;
    private TextView subMessage;
    private View mButtonLayoutDivider;
    private LinearLayout mContentLayout;
    private LinearLayout mButtonLayout;
    private Button positiveButton;

    private int mStyle;

    protected EZDialog(Context context, int style) {
        super(context, (style & 1) == 1 ? R.style.ezmBottomDialog : R.style.ezmCommonDialog);
        mStyle = style;
        if ((style & 1) == 1) {
            getWindow().setGravity(Gravity.BOTTOM | Gravity.CENTER);
        } else {
            getWindow().setGravity(Gravity.CENTER);
        }
        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getWindow().setAttributes(lp);
    }

    protected EZDialog(Builder builder) {
        this(builder.mContext, builder.mStyle);
        mBuilder = builder;
        setCancelable(builder.mCancelable);
        setCanceledOnTouchOutside(builder.mCancelable);
        setOnCancelListener(builder.mOnCancelListener);
        setOnDismissListener(builder.mOnDismissListener);
        setOnKeyListener(builder.mOnKeyListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ezm_ezviz_dialog_layout);
        findViews();
        if (mBuilder != null) {
            initViews();
        }
    }

    private void findViews() {
        mTitle = (TextView) findViewById(R.id.title);
        mMessage = (TextView) findViewById(R.id.message);
        subMessage = (TextView) findViewById(R.id.subMessage);
        mContentLayout = (LinearLayout) findViewById(R.id.content_layout);
        mButtonLayout = (LinearLayout) findViewById(R.id.button_layout);
        mButtonLayoutDivider = findViewById(R.id.button_layout_divider);

        mTitle.getPaint().setFakeBoldText(true);
    }

    private void initViews() {
        createTitleMessage();
        createCustomView();
        createButtons();
    }

    /**
     * 生成标题消息内容
     */
    private void createTitleMessage() {
        if (!TextUtils.isEmpty(mBuilder.mTitle)) {
            mTitle.setText(mBuilder.mTitle);
            mTitle.setVisibility(View.VISIBLE);
        } else {
            mTitle.setText("");
            mTitle.setVisibility(TextUtils.isEmpty(mBuilder.mMessage) ? View.GONE : View.INVISIBLE);
        }

        if (!TextUtils.isEmpty(mBuilder.mMessage)) {
            mMessage.setText(mBuilder.mMessage);
            if (mBuilder.mMessage instanceof SpannableString){
                mMessage.setMovementMethod(LinkMovementMethod.getInstance());
                mMessage.setHighlightColor(getContext().getResources().getColor(android.R.color.transparent));
            }
            mMessage.setVisibility(View.VISIBLE);
        } else {
            mMessage.setText("");
            mMessage.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(mBuilder.mSubMessage)){
            subMessage.setText(mBuilder.mSubMessage);
            subMessage.setVisibility(View.VISIBLE);
        } else {
            subMessage.setText("");
            subMessage.setVisibility(View.GONE);
        }
    }

    /**
     * 生成自定义View
     */
    private void createCustomView() {
        View customView = null;
        if (mBuilder.mView != null) {
            customView = mBuilder.mView;
        } else if (mBuilder.mViewLayoutResId != 0) {
            customView = LayoutInflater.from(getContext()).inflate(mBuilder.mViewLayoutResId, mContentLayout, false);
        }

        if (customView != null) {
            if (mTitle.getVisibility() == View.GONE) {
                mContentLayout.setPadding(0, 0, 0, 0);
            }
            mContentLayout.addView(customView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        }
    }

    /**
     * 生成所有按钮相关内容
     */
    private void createButtons() {
        List<Button> buttons = new ArrayList<>();
        if (!TextUtils.isEmpty(mBuilder.mButtonTexts[BUTTON_NEUTRAL + 3])) {
            buttons.add(createButton(BUTTON_NEUTRAL, mBuilder.mButtonTexts[BUTTON_NEUTRAL + 3],
                mBuilder.mButtonTextColors[BUTTON_NEUTRAL + 3], mBuilder.mButtonActionKeys[BUTTON_NEUTRAL + 3],
                mBuilder.mButtonOnClickListeners[BUTTON_NEUTRAL + 3]));
        }
        if (!TextUtils.isEmpty(mBuilder.mButtonTexts[BUTTON_NEGATIVE + 3])) {
            buttons.add(0, createButton(BUTTON_NEGATIVE, mBuilder.mButtonTexts[BUTTON_NEGATIVE + 3],
                mBuilder.mButtonTextColors[BUTTON_NEGATIVE + 3], mBuilder.mButtonActionKeys[BUTTON_NEGATIVE + 3],
                mBuilder.mButtonOnClickListeners[BUTTON_NEGATIVE + 3]));
        }
        if (!TextUtils.isEmpty(mBuilder.mButtonTexts[BUTTON_POSITIVE + 3])) {
            buttons.add(positiveButton = createButton(BUTTON_POSITIVE, mBuilder.mButtonTexts[BUTTON_POSITIVE + 3],
                mBuilder.mButtonTextColors[BUTTON_POSITIVE + 3], mBuilder.mButtonActionKeys[BUTTON_POSITIVE + 3],
                mBuilder.mButtonOnClickListeners[BUTTON_POSITIVE + 3]));
        }

        if (buttons.size() > 0) {
            mButtonLayoutDivider.setVisibility(View.VISIBLE);
            int buttonStyle = mStyle & 2;
            Button button;
            if (buttonStyle == BUTTON_HORIZONTAL && buttons.size() == 2) {
                mButtonLayout.setOrientation(LinearLayout.HORIZONTAL);
                button = buttons.get(0);
                button.setBackgroundResource(R.drawable.ezm_ezviz_dialog_left_button);
                mButtonLayout.addView(button);

                mButtonLayout.addView(createButtonDivider(false));

                button = buttons.get(1);
                button.setBackgroundResource(R.drawable.ezm_ezviz_dialog_right_button);
                mButtonLayout.addView(button);
            } else {
                mButtonLayout.setOrientation(LinearLayout.VERTICAL);
                for (int i = buttons.size() - 1; i > -1; i--) {
                    if (i < buttons.size() - 1) {
                        mButtonLayout.addView(createButtonDivider(true));
                    }

                    button = buttons.get(i);
                    button.setBackgroundResource(
                        i == 0 ? R.drawable.ezm_ezviz_dialog_bottom_button : R.drawable.ezm_ezviz_dialog_normal_button);
                    mButtonLayout.addView(button);
                }
            }
        } else {
            mButtonLayoutDivider.setVisibility(View.GONE);
        }
    }

    /**
     * 创建单个按钮
     */
    @SuppressLint("NewApi")
    private Button createButton(final int whichButton, CharSequence text, int textColor, int actionKey,
                                final OnClickListener listener) {
        Button button = new Button(getContext());
        button.setLayoutParams(
            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
        button.setTextColor(textColor == UNSET_TEXT_COLOR ? getContext().getResources()
            .getColor(whichButton == BUTTON_POSITIVE ? R.color.ezm_ezviz_dialog_positive_button_text_color
                : R.color.ezm_ezviz_dialog_button_text_color) : textColor);
        button.setText(text);
        button.setContentDescription(actionKey == NO_ACTION_KEY ? null : Integer.toString(actionKey));
        button.setTextSize(TypedValue.COMPLEX_UNIT_PX,
            getContext().getResources().getDimensionPixelSize(R.dimen.ezm_ezviz_dialog_button_text_size));
        button.setMinHeight(getContext().getResources().getDimensionPixelSize(R.dimen.ezm_ezviz_dialog_button_minHeight));

        int paddingLeftRight =
            getContext().getResources().getDimensionPixelSize(R.dimen.ezm_ezviz_dialog_button_padding_left_right);
        int paddingTopBottom =
            getContext().getResources().getDimensionPixelSize(R.dimen.ezm_ezviz_dialog_button_padding_top_bottom);
        button.setPadding(paddingLeftRight, paddingTopBottom, paddingLeftRight, paddingTopBottom);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClick(EZDialog.this, whichButton);
                }
                if (listener == null || !mBuilder.isConsumePos)
                    dismiss();
            }
        });
        return button;
    }

    /**
     * 创建按钮间隔线
     */
    private View createButtonDivider(boolean horizontalOrVertical) {
        View divider = new View(getContext());
        divider.setBackgroundColor(getContext().getResources().getColor(R.color.ezm_ezviz_dialog_divider_color));
        divider.setLayoutParams(new ViewGroup.LayoutParams(
            horizontalOrVertical ? ViewGroup.LayoutParams.MATCH_PARENT : ViewUtil.dp2px(getContext(), 0.5f),
            horizontalOrVertical ? ViewUtil.dp2px(getContext(), 0.5f) : ViewGroup.LayoutParams.MATCH_PARENT));
        return divider;
    }

    public void setMessage(CharSequence message) {
        if (!TextUtils.isEmpty(message)) {
            mMessage.setText(message);
            mMessage.setVisibility(View.VISIBLE);
        } else {
            mMessage.setText("");
            mMessage.setVisibility(View.GONE);
        }
    }

    public Button getPositiveButton(){
        return positiveButton;
    }

    public static class Builder {

        private Context mContext;
        private int mStyle;
        private CharSequence mTitle;
        private CharSequence mMessage;
        private CharSequence mSubMessage;
        private boolean mCancelable = true;
        private OnCancelListener mOnCancelListener;
        private OnDismissListener mOnDismissListener;
        private OnKeyListener mOnKeyListener;

        private View mView;
        private int mViewLayoutResId;

        private final int[] mButtonActionKeys;
        private final int[] mButtonTextColors;
        private final CharSequence[] mButtonTexts;
        private final OnClickListener[] mButtonOnClickListeners;

        private CharSequence[] mItems;
        private ListAdapter mListAdapter;
        private OnClickListener mListOnClickListeners;
        private int[] mCheckedItems;
        private boolean mIsSingleChoice;
        private boolean mIsMultiChoice;
        private boolean isConsumePos;
        private OnMultiChoiceClickListener mOnMultiChoiceClickListener;
        private AdapterView.OnItemSelectedListener mOnItemSelectedListener;

        /**
         * 构造Builder
         * 默认：对话框居中；按钮水平排列
         */
        public Builder(Context context) {
            this(context, 0);
        }

        /**
         * 构造Builder
         *
         * @param style 对话框居中{@link EZDialog#STYLE_CENTER}或底部{@link EZDialog#STYLE_BOTTOM}，按钮水平排列{@link
         * EZDialog#BUTTON_HORIZONTAL}或
         * 垂直排列{@link EZDialog#BUTTON_VERTICAL}，可以使用"|"同时设置对话框样式和按钮样式
         */
        public Builder(Context context, int style) {
            mContext = context;
            mStyle = style;

            mButtonActionKeys = new int[3];
            mButtonTextColors = new int[3];
            mButtonTexts = new CharSequence[3];
            mButtonOnClickListeners = new OnClickListener[3];
        }

        public Builder setTitle(@StringRes int titleId) {
            mTitle = mContext.getText(titleId);
            return this;
        }

        public Builder setTitle(CharSequence title) {
            mTitle = title;
            return this;
        }

        public Builder setMessage(@StringRes int messageId) {
            mMessage = mContext.getText(messageId);
            return this;
        }

        public Builder setMessage(CharSequence message) {
            mMessage = message;
            return this;
        }

        public Builder setSubMessage(@StringRes int messageId) {
            mSubMessage = mContext.getText(messageId);
            return this;
        }

        public Builder setSubMessage(CharSequence message) {
            mSubMessage = message;
            return this;
        }

        public Builder setCancelable(boolean cancelable) {
            mCancelable = cancelable;
            return this;
        }

        public Builder setOnCancelListener(OnCancelListener onCancelListener) {
            mOnCancelListener = onCancelListener;
            return this;
        }

        public Builder setOnDismissListener(OnDismissListener onDismissListener) {
            mOnDismissListener = onDismissListener;
            return this;
        }

        public Builder setOnKeyListener(OnKeyListener onKeyListener) {
            mOnKeyListener = onKeyListener;
            return this;
        }

        private Builder setItems(@ArrayRes int itemsId, OnClickListener listener) {
            mItems = mContext.getResources().getTextArray(itemsId);
            mListAdapter = null;
            mListOnClickListeners = listener;
            return this;
        }

        private Builder setItems(CharSequence[] items, OnClickListener listener) {
            mItems = items;
            mListAdapter = null;
            mListOnClickListeners = listener;
            return this;
        }

        private Builder setAdapter(ListAdapter adapter, OnClickListener listener) {
            mItems = null;
            mListAdapter = adapter;
            mListOnClickListeners = listener;
            return this;
        }

        private Builder setMultiChoiceItems(@ArrayRes int itemsId, int[] checkedItems,
                                            OnMultiChoiceClickListener listener) {
            mItems = mContext.getResources().getTextArray(itemsId);
            mListAdapter = null;
            mCheckedItems = checkedItems;
            mIsMultiChoice = true;
            mOnMultiChoiceClickListener = listener;
            return this;
        }

        private Builder setMultiChoiceItems(CharSequence[] items, int[] checkedItems,
            OnMultiChoiceClickListener listener) {
            mItems = items;
            mListAdapter = null;
            mCheckedItems = checkedItems;
            mIsMultiChoice = true;
            mOnMultiChoiceClickListener = listener;
            return this;
        }

        private Builder setSingleChoiceItems(@ArrayRes int itemsId, int checkedItem, OnClickListener listener) {
            mItems = mContext.getResources().getTextArray(itemsId);
            mListAdapter = null;
            mCheckedItems = new int[] { checkedItem };
            mIsSingleChoice = true;
            mListOnClickListeners = listener;
            return this;
        }

        private Builder setSingleChoiceItems(CharSequence[] items, int checkedItem, OnClickListener listener) {
            mItems = items;
            mListAdapter = null;
            mCheckedItems = new int[] { checkedItem };
            mIsSingleChoice = true;
            mListOnClickListeners = listener;
            return this;
        }

        private Builder setSingleChoiceItems(ListAdapter adapter, int checkedItem, OnClickListener listener) {
            mItems = null;
            mListAdapter = adapter;
            mCheckedItems = new int[] { checkedItem };
            mIsSingleChoice = true;
            mListOnClickListeners = listener;
            return this;
        }

        private Builder setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
            mOnItemSelectedListener = listener;
            return this;
        }

        public Builder setView(int layoutResId) {
            mView = null;
            mViewLayoutResId = layoutResId;
            return this;
        }

        public Builder setView(View view) {
            mView = view;
            mViewLayoutResId = 0;
            return this;
        }

        /**
         * setButton
         */
        public Builder setButton(int which, @StringRes int textId, int textColor, int actionKey,
                                 OnClickListener listener) {
            int index = which + 3;
            mButtonActionKeys[index] = actionKey;
            mButtonTexts[index] = mContext.getText(textId);
            mButtonTextColors[index] = textColor;
            mButtonOnClickListeners[index] = listener;
            return this;
        }

        public Builder setButton(int which, CharSequence text, int textColor, int actionKey, OnClickListener listener) {
            int index = which + 3;
            mButtonActionKeys[index] = actionKey;
            mButtonTexts[index] = text;
            mButtonTextColors[index] = textColor;
            mButtonOnClickListeners[index] = listener;
            return this;
        }

        public Builder setButton(int which, @StringRes int textId, int actionKey, OnClickListener listener) {
            return setButton(which, textId, UNSET_TEXT_COLOR, actionKey, listener);
        }

        public Builder setButton(int which, CharSequence text, int actionKey, OnClickListener listener) {
            return setButton(which, text, UNSET_TEXT_COLOR, actionKey, listener);
        }

        public Builder setButton(int which, @StringRes int textId, OnClickListener listener) {
            return setButton(which, textId, UNSET_TEXT_COLOR, NO_ACTION_KEY, listener);
        }

        public Builder setButton(int which, CharSequence text, OnClickListener listener) {
            return setButton(which, text, UNSET_TEXT_COLOR, NO_ACTION_KEY, listener);
        }

        /**
         * setPositiveButton
         */
        public Builder setPositiveButton(@StringRes int textId, int textColor, int actionKey,
                                         OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_POSITIVE, textId, textColor, actionKey, listener);
        }

        public Builder setPositiveButton(CharSequence text, int textColor, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_POSITIVE, text, textColor, actionKey, listener);
        }

        public Builder setPositiveButton(@StringRes int textId, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_POSITIVE, textId, actionKey, listener);
        }

        public Builder setPositiveButton(CharSequence text, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_POSITIVE, text, actionKey, listener);
        }

        public Builder setPositiveButton(@StringRes int textId, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_POSITIVE, textId, listener);
        }

        public Builder setPositiveButton(CharSequence text, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_POSITIVE, text, listener);
        }

        /**
         * setNegativeButton
         */
        public Builder setNegativeButton(@StringRes int textId, int textColor, int actionKey,
                                         OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEGATIVE, textId, textColor, actionKey, listener);
        }

        public Builder setNegativeButton(CharSequence text, int textColor, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEGATIVE, text, textColor, actionKey, listener);
        }

        public Builder setNegativeButton(@StringRes int textId, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEGATIVE, textId, actionKey, listener);
        }

        public Builder setNegativeButton(CharSequence text, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEGATIVE, text, actionKey, listener);
        }

        public Builder setNegativeButton(@StringRes int textId, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEGATIVE, textId, listener);
        }

        public Builder setNegativeButton(CharSequence text, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEGATIVE, text, listener);
        }

        /**
         * setNeutralButton
         */
        public Builder setNeutralButton(@StringRes int textId, int textColor, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEUTRAL, textId, textColor, actionKey, listener);
        }

        public Builder setNeutralButton(CharSequence text, int textColor, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEUTRAL, text, textColor, actionKey, listener);
        }

        public Builder setNeutralButton(@StringRes int textId, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEUTRAL, textId, actionKey, listener);
        }

        public Builder setNeutralButton(CharSequence text, int actionKey, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEUTRAL, text, actionKey, listener);
        }

        public Builder setNeutralButton(@StringRes int textId, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEUTRAL, textId, listener);
        }

        public Builder setNeutralButton(CharSequence text, OnClickListener listener) {
            return setButton(DialogInterface.BUTTON_NEUTRAL, text, listener);
        }

        public Builder setDismissConsume(boolean isConsume) {
            isConsumePos = isConsume;
            return this;
        }

        public EZDialog create() {
            final EZDialog dialog = new EZDialog(this);
            return dialog;
        }

        public EZDialog show() {
            final EZDialog dialog = create();
            dialog.show();
            return dialog;
        }
    }
}
