package com.gingersoft.gsa.cloud.table.mvp.ui.widget;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
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.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.ui.widget.keyboard.VirtualKeyboardView;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;
import com.qmuiteam.qmui.QMUILog;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author : bin
 * @create date: 2020-10-28
 * @update date: 2020-10-28
 * @description:
 */
public class KeyboardDialog extends Dialog {

    private static final String TAG = "KeyboardDialog";

    private Activity mContext;

    private VirtualKeyboardView virtualKeyboardView;
    private GridView mGridView;
    private MaterialEditText ed_text;

    private ArrayList<Map<String, String>> keyboardValueList;
    // 动画时长
    private final static int mAnimationDuration = 300;
    // 持有 ContentView，为了做动画
    private View mContentView;
    private boolean mIsAnimating = false;

    public KeyboardDialog(Activity context) {
        super(context, R.style.QMUI_BottomSheet);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //noinspection ConstantConditions
        getWindow().getDecorView().setPadding(0, 0, 0, 0);

        // 在底部，宽度撑满
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER;

        int screenWidth = QMUIDisplayHelper.getScreenWidth(getContext());
        int screenHeight = QMUIDisplayHelper.getScreenHeight(getContext());
        params.width = screenWidth < screenHeight ? screenWidth : screenHeight;
        getWindow().setAttributes(params);
        setCanceledOnTouchOutside(false);
    }

    @Override
    public void setContentView(int layoutResID) {
        mContentView = LayoutInflater.from(getContext()).inflate(layoutResID, null);
        super.setContentView(mContentView);
    }

    @Override
    public void setContentView(@NonNull View view, ViewGroup.LayoutParams params) {
        mContentView = view;
        super.setContentView(view, params);
    }

    public View getContentView() {
        return mContentView;
    }

    @Override
    public void setContentView(@NonNull View view) {
        mContentView = view;
        super.setContentView(view);
    }

    /**
     * BottomSheet升起动画
     */
    private void animateUp() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);
        mContentView.startAnimation(set);
    }

    /**
     * BottomSheet降下动画
     */
    private void animateDown() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f
        );
        AlphaAnimation alpha = new AlphaAnimation(1, 0);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);
        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mIsAnimating = true;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIsAnimating = false;
                /**
                 * Bugfix： Attempting to destroy the window while drawing!
                 */
                mContentView.post(new Runnable() {
                    @Override
                    public void run() {
                        // java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{22dbf5b V.E...... R......D 0,0-1080,1083} not attached to window manager
                        // 在dismiss的时候可能已经detach了，简单try-catch一下
                        try {
                            KeyboardDialog.super.dismiss();
                        } catch (Exception e) {
                            QMUILog.w(TAG, "dismiss error\n" + Log.getStackTraceString(e));
                        }
                    }
                });
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mContentView.startAnimation(set);
    }

    @Override
    public void show() {
        super.show();
        animateUp();
    }

    @Override
    public void dismiss() {
        if (mIsAnimating) {
            return;
        }
        animateDown();
    }

    public KeyboardDialog build() {
        View contentView = buildViews();
        setContentView(contentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (QMUIDisplayHelper.getScreenHeight(mContext) * 0.7)));
        return this;
    }

    private View buildViews() {
        View view = View.inflate(mContext, getContentViewLayoutId(), null);
        ed_text = view.findViewById(R.id.ed_text);
        QMUIAlphaTextView tv_sure = view.findViewById(R.id.tv_sure);
        QMUIAlphaTextView tv_cancel = view.findViewById(R.id.tv_cancel);
        virtualKeyboardView = view.findViewById(R.id.virtualKeyboardView);

        // 设置不调用系统键盘
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            ed_text.setInputType(InputType.TYPE_NULL);
        } else {
            mContext.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(ed_text, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        virtualKeyboardView.setFocusable(true);
        virtualKeyboardView.setFocusableInTouchMode(true);
//        virtualKeyboardView.startAnimation(enterAnim);
        virtualKeyboardView.setVisibility(View.VISIBLE);

        keyboardValueList = virtualKeyboardView.getValueList();
        virtualKeyboardView.getLayoutBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mGridView = virtualKeyboardView.getGridView();
        mGridView.setOnItemClickListener(onItemClickListener);

        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = getText();
                if (onCallBackListener != null && !TextUtils.isEmpty(text)) {
                    if (Double.parseDouble(text) > 0) {
                        onCallBackListener.onSure(text);
                    } else {
                        ArmsUtils.makeText(mContext, "自定義金額必須>0");
                    }
                }
                dismiss();
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        return view;
    }

    private String getText() {
        return ed_text.getText().toString();
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

            if (position < 11 && position != 9) {    //点击0~9按钮

                String amount = ed_text.getText().toString().trim();
                amount = amount + keyboardValueList.get(position).get("name");

                ed_text.setText(amount);

                Editable ea = ed_text.getText();
                ed_text.setSelection(ea.length());
            } else {

                if (position == 9) {      //点击退格键
                    String amount = ed_text.getText().toString().trim();
                    if (!amount.contains(".")) {
                        amount = amount + keyboardValueList.get(position).get("name");
                        ed_text.setText(amount);

                        Editable ea = ed_text.getText();
                        ed_text.setSelection(ea.length());
                    }
                }

                if (position == 11) {      //点击退格键
                    String amount = ed_text.getText().toString().trim();
                    if (amount.length() > 0) {
                        amount = amount.substring(0, amount.length() - 1);
                        ed_text.setText(amount);

                        Editable ea = ed_text.getText();
                        ed_text.setSelection(ea.length());
                    }
                }
            }
        }
    };

    protected int getContentViewLayoutId() {
        return R.layout.table_dialog_keyboard;
    }

    private OnCallBackListener onCallBackListener;

    public KeyboardDialog setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
        return this;
    }

    public interface OnCallBackListener {
        void onSure(String number);

    }
}
