package aicare.net.cn.sdk.ailinksdkdemoandroid.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.regex.Pattern;

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;


/**
 * 修改信息的弹框
 */
public class MoveDataDialogFragment extends DialogFragment implements View.OnClickListener {

    private String TAG = MoveDataDialogFragment.class.getName();

    public static final int EMAIL = 2;
    public static final int NAME = 1;
    public static final int PAW = 3;

    @IntDef({EMAIL, NAME, PAW})
    @Retention(RetentionPolicy.SOURCE)
    public @interface MoveDataType {
    }

    private Context mContext;

    private OnDialogListener mOnDialogListener;
    private EditText mEtName;
    private TextView mTvCancel, mTvSucceed, mTvTitle, mTvTitleHint;
    private int mNameLength = 32;
    private CharSequence mTitle = "";
    private CharSequence mTitleHint;
    private CharSequence mContent = "";
    private CharSequence mContentHint = "";
    private CharSequence mCancel = "";
    @ColorInt
    private int mCancelColor = 0;
    private CharSequence mOkStr = "";
    private String mRegular = "";
    @ColorInt
    private int mOkColor = 0;
    private boolean mBottom;
    /**
     * 点击确定后是否自动关闭,默认true
     */
    private boolean autoDismiss = true;
    /**
     * 是否显示灰色背景
     */
    private boolean mBackground = true;

    /**
     * 点击空白区域是否关闭
     */
    private boolean mCancelBlank;

    /**
     * 是否显示
     */
    private boolean mShow;
    /**
     * 类型
     */
    private int mType;
    /**
     * 确认按钮背景
     */
    private Drawable drawable;


    public static MoveDataDialogFragment newInstance() {
        return new MoveDataDialogFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_FRAME, R.style.MyDialog);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        setStyle(STYLE_NO_FRAME, R.style.MyDialog);

        Dialog dialogView = new Dialog(requireContext(), R.style.MyDialog);// 创建自定义样式dialog
        dialogView.setCancelable(false);//设置是否可以关闭
        dialogView.setCanceledOnTouchOutside(mCancelBlank);//设置点击空白处是否可以取消
        dialogView.setOnKeyListener((dialog, keyCode, event) -> {
            if (mCancelBlank) {
                return false;
            } else {
                //返回不关闭
                return keyCode == KeyEvent.KEYCODE_BACK;
            }
        });
        return dialogView;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dialog_move_data, container);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mContext = view.getContext();
        init(view, mType);
        initData(mTitle, mTitleHint, mContent, mContentHint, mCancelColor, mOkColor, mType);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                WindowManager.LayoutParams params = window.getAttributes();
                if (mBackground) {
                    params.dimAmount = 0.5f;
                } else {
                    params.dimAmount = 0f;
                }
                if (mBottom) {
                    params.y = 10;//设置Dialog距离底部的距离
                    params.gravity = Gravity.BOTTOM;
                }
                window.setAttributes(params);
            }
        }
    }


    /**
     * 初始化控件
     */
    private void init(View view, int type) {
        mEtName = view.findViewById(R.id.et_move_data_context);
        mTvCancel = view.findViewById(R.id.tv_move_data_cancel);
        mTvSucceed = view.findViewById(R.id.tv_move_data_ok);
        mTvTitle = view.findViewById(R.id.tv_move_data_title);
        mTvTitleHint = view.findViewById(R.id.tv_move_data_title_hint);
        if (type == NAME) {
            mEtName.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    String name = s.toString().trim();
                    if (name.length() > mNameLength) {
                        mEtName.setText(name.substring(0, mNameLength));
                        mEtName.setSelection(mEtName.getText().length());
                    }
                }
            });
        } else if (type == EMAIL) {
            mEtName.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
            mEtName.setSelection(mEtName.getText().length());
        }
        if (!TextUtils.isEmpty(mRegular)) {
            mEtName.setFilters(new InputFilter[]{(charSequence, start, end, dest, dstart, dend) -> {
                boolean isChinese = Pattern.matches(mRegular, charSequence.toString());
                if (isChinese) {
                    return "";
                }
                return null;
            }});
        }
        if (mOnDialogListener != null) {
            mOnDialogListener.onModifyName(mEtName);
        }
        mTvCancel.setOnClickListener(this);
        mTvSucceed.setOnClickListener(this);
    }

    /**
     * 点击确定后是否自动关闭,默认true
     *
     * @param autoDismiss 默认true
     * @return MoveDataDialogFragment
     */
    public MoveDataDialogFragment setAutoDismiss(boolean autoDismiss) {
        this.autoDismiss = autoDismiss;
        return this;
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_move_data_cancel) {
            if (mOnDialogListener != null) {
                mOnDialogListener.onCancelListener(v);
            }
            dismiss();
        } else if (i == R.id.tv_move_data_ok) {
            if (mOnDialogListener != null) {
                String data = mEtName.getText().toString().trim();
                mOnDialogListener.onSucceedListener(v, data);
            }
            if (!mEtName.getText().toString().trim().isEmpty() && autoDismiss) {
                dismiss();
            }
        }
    }

    /**
     * 初始化数据
     *
     * @param title       标题
     * @param titleHint   标题提示
     * @param content     输入框内容
     * @param contentHint 输入框提示
     * @param cancelColor 取消颜色
     * @param okColor     确定颜色
     * @param type        类型(名称,email){@link MoveDataType}
     */
    private void initData(CharSequence title, CharSequence titleHint, CharSequence content,
                          CharSequence contentHint, int cancelColor, int okColor, int type) {
        setTitle(title, titleHint);
        setContent(content, contentHint, type);
        setCancel("", cancelColor);
        setOk("", okColor, drawable);
    }


    /**
     * @param content     输入框内容
     * @param contentHint 输入框提示
     * @param type        {@link MoveDataType}
     * @return
     */
    public MoveDataDialogFragment setContent(CharSequence content, CharSequence contentHint, @MoveDataType int type) {
        this.mType = type;
        if (mType == NAME) {
            if (mContent != null && mContent.length() > mNameLength) {
                mContent = content.toString().substring(0, mNameLength);
            } else {
                this.mContent = content;
            }
        } else {
            this.mContent = content;
        }
        this.mContentHint = contentHint;
        if (mEtName != null) {
            if (mContent != null && !mContent.equals("")) {
                mEtName.setText(mContent);
                mEtName.setSelection(mEtName.getText().length());
            } else if (mContent == null) {
                mEtName.setText("");
            }
            if (mContentHint != null && !mContentHint.equals("")) {
                mEtName.setHint(mContentHint);
            } else if (mContentHint == null || mContentHint.equals("")) {
                mEtName.setHint("");
            }
            if (mType == PAW) {
                mEtName.setInputType(8194);
                mEtName.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            }


        }
        return this;
    }


    public MoveDataDialogFragment setTitle(CharSequence title, CharSequence titleHint) {
        this.mTitle = title;
        this.mTitleHint = titleHint;
        if (mTvTitle != null) {
            if (mTitle != null && !mTitle.equals("")) {
                mTvTitle.setVisibility(View.VISIBLE);
                mTvTitle.setText(mTitle);
            } else if (mTitle == null) {
                mTvTitle.setVisibility(View.GONE);
            }
        }
        if (mTvTitleHint != null) {
            if (mTitleHint != null && mTitleHint.length() != 0) {
                mTvTitleHint.setVisibility(View.VISIBLE);
                mTvTitleHint.setText(mTitleHint);
            } else {
                mTvTitleHint.setVisibility(View.GONE);
            }
        }
        return this;
    }

    public MoveDataDialogFragment setCancel(CharSequence cancel, @ColorInt int cancelColor) {
        this.mCancel = cancel;
        this.mCancelColor = cancelColor;
        if (mTvCancel != null) {
            if (mCancel != null && !mCancel.equals("")) {
                mTvCancel.setVisibility(View.VISIBLE);
                mTvCancel.setText(mCancel);
            } else if (mCancel == null) {
                mTvCancel.setVisibility(View.GONE);
            }
            if (mCancelColor > 0) {
                mTvCancel.setTextColor(mCancelColor);
            }


        }
        return this;
    }


    /**
     * 确认按钮
     */
    public MoveDataDialogFragment setOk(CharSequence ok, @ColorInt int okColor) {

        return setOk(ok, okColor, null);
    }


    public MoveDataDialogFragment setOk(CharSequence ok, @ColorInt int okColor, Drawable drawable) {
        this.mOkStr = ok;
        this.mOkColor = okColor;
        this.drawable = drawable;
        if (mTvSucceed != null) {
            if (mOkStr != null && !mOkStr.equals("")) {
                mTvSucceed.setVisibility(View.VISIBLE);
                mTvSucceed.setText(mOkStr);
            } else if (mOkStr == null) {
                mTvSucceed.setVisibility(View.GONE);
            }
            if (mOkColor > 0) {
                mTvSucceed.setTextColor(mOkColor);
            }
            if (drawable != null) {
                mTvSucceed.setBackground(drawable);
            }
        }
        return this;
    }


    /**
     * 设置edittext输入的过滤
     *
     * @param regular 过滤的正则
     * @return
     */
    public MoveDataDialogFragment setFilters(String regular) {
        this.mRegular = regular;
        return this;
    }


    /**
     * 设置dialog是否在底部
     */
    public MoveDataDialogFragment setBottom(boolean bottom) {
        mBottom = bottom;
        return this;
    }


    /**
     * 设置dialog是否有灰色背景,默认显示灰色背景
     */
    public MoveDataDialogFragment setBackground(boolean background) {
        mBackground = background;
        return this;
    }

    /**
     * 设置点击空白区域是否可以关闭,默认false
     */
    public MoveDataDialogFragment setCancelBlank(boolean cancelable) {
        mCancelBlank = cancelable;
        return this;
    }

    public MoveDataDialogFragment setOnDialogListener(OnDialogListener mOnDialogListener) {
        this.mOnDialogListener = mOnDialogListener;
        return this;
    }

    public MoveDataDialogFragment setNameLength(int nameLength) {
        mNameLength = nameLength;
        return this;
    }


    public MoveDataDialogFragment setOkBack(int nameLength) {
        mNameLength = nameLength;
        return this;
    }


    /**
     * 当前是否显示
     */
    public boolean isShow() {
        return mShow;
    }


    @Override
    public void show(@NonNull FragmentManager manager, @Nullable String tag) {
        try {
            if (!mShow) {
                super.show(manager, tag);
                mShow = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void show(@NonNull FragmentManager manager) {
        this.show(manager, "HintDataDialogFragment");
    }


    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        mShow = false;
    }


    @Override
    public void dismiss() {
        try {
            mShow = false;
            super.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface OnDialogListener {

        /**
         * 取消的点击事件
         */
        default void onCancelListener(View v) {
        }

        /**
         * 成功的点击事件
         */
        default void onSucceedListener(View v, String data) {
        }

        /**
         * 修改名称的控件
         */
        default void onModifyName(EditText v) {
        }


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mShow = false;
    }


    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            dialog.setOnDismissListener(this);
            DisplayMetrics dm = new DisplayMetrics();
            if (getActivity() != null) {
                getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
                if (dialog.getWindow() != null)
                {
                    //设置宽度为80%
                    dialog.getWindow().setLayout((int) (dm.widthPixels * 0.8),
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                }
            }
        }
    }
}
