package com.efounder.chat.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import androidx.appcompat.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.tbs.Md5Tool;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ClickUtils;
import com.utilcode.util.ReflectUtils;

/**
 * 密码输入对话框
 *
 * @author YQS
 */

public class SecretPassInputDialog {

    private Activity mContext;
    private int mWidth;
    private int mHeight;
    public static String CLEAR_PASSWORD = "";
    /**
     * 升级的文字信息
     */
    private TextView newVersionInforTv;

    /**
     * 面板占屏幕宽度的百分比
     */
    private static final float WIDTHFRACTION = 0.8f;
    private AlertDialog alertDialog;

    private TextView title;
    private TextView tvError;
    private Button butEnter;
    private View rootView;
    private TextView tips;
    private EditText editText;
    private OnEnterClick onEnterClick;
    public static boolean isVerifyPwd = false;
    private TextView forgetPwdView;


    private void getWindowWidthAndHeight() {
        WindowManager m = mContext.getWindowManager();
        Display d = m.getDefaultDisplay();
        mWidth = d.getWidth();
        mHeight = d.getHeight();
    }


    public SecretPassInputDialog(Activity context, OnEnterClick onEnterClick) {
        this.mContext = context;
        this.onEnterClick = onEnterClick;
        getWindowWidthAndHeight();
        init();
    }


    /**
     * 设置标题
     *
     * @param msg
     */
    public void setTitle(String msg) {
        title.setText(msg);
    }


    private void init() {

        rootView = LayoutInflater.from(mContext).inflate(R.layout.secret_mesage_pass_input_dialog, null);

        title = rootView.findViewById(R.id.title);
        tvError = rootView.findViewById(R.id.tv_error);
        tvError.setVisibility(View.INVISIBLE);
        butEnter = rootView.findViewById(R.id.but_enter);
        editText = rootView.findViewById(R.id.et_password);
        editText.setTextColor(JfResourceUtil.getSkinColor(R.color.wechat_white_or_black));
        forgetPwdView = rootView.findViewById(R.id.tv_forgetpwd);
        tips = (TextView) rootView.findViewById(R.id.tips);
        ClickUtils.applySingleDebouncing(forgetPwdView, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转重置密码的界面
                ReflectUtils reflectUtils = ReflectUtils.reflect("com.pansoft.openplanet.activity.ResetPasswordActivity");
                reflectUtils.method("start", mContext, EnvironmentVariable.getUserName(), true);
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                tvError.setText("");
            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        butEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pass = editText.getText().toString();

                if (pass.trim().equals("")) {
                    tvError.setText(ResStringUtil.getString(R.string.open_planet_asset_password_dialog_password_not_empty));
                    tvError.setVisibility(View.VISIBLE);
                    rootView.setAnimation(shakeAnimation(5));
                    //ToastUtil.showToast(mContext,"密码不能为空");
                    return;
                }
                if (Md5Tool.hashKey(pass).equals(EnvironmentVariable.getPassword())) {
                    CLEAR_PASSWORD = pass;
                    isVerifyPwd = true;
                    dismiss();
                    if (onEnterClick != null) {
                        onEnterClick.passVerifySuccess(pass);
                    }
                    //mContext.startActivity(new Intent(mContext, MyWalletActivity.class));
                } else {
                    tvError.setText(ResStringUtil.getString(R.string.open_planet_asset_password_dialog_password_error));

                    //如果只设置setAnimation（TranslateAnimation）那么在使用的时候只会执行一次，
                    // 只有当setAnimation和startAnimation 一起设置才会在触发条件达到的时候动画会重复执行。
                    rootView.startAnimation(shakeAnimation(4));
                    //rootView.setAnimation(mShowAction);
                    tvError.setVisibility(View.VISIBLE);
                }


            }
        });

        alertDialog = new AlertDialog.Builder(mContext)
                .setCancelable(true).create();
        alertDialog.setView(rootView);
    }


    public void show() {

        alertDialog.show();
        Window window = alertDialog.getWindow();
        //不邪恶这行，圆角无效
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        window.setBackgroundDrawableResource(R.drawable.new_version_round_shape);
//        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.new_version_scale_open);
        setDialogSize(alertDialog, rootView);
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                showKeyboard(editText);

            }
        },300);


    }

    public void showKeyboard(EditText editText) {
        if (editText != null) {
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) editText
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    public void dismiss() {
//        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.new_version_scale_close);
//        newVersionContentView.startAnimation(animation);
        alertDialog.dismiss();

    }

    public TextView getTips() {
        return tips;
    }

    public SecretPassInputDialog setTips(TextView tips) {
        this.tips = tips;
        return this;
    }

    /**
     * 根据屏幕的宽度来设置面板的宽度
     * 高度自适应
     *
     * @param alertDialog
     * @param view
     */
    private void setDialogSize(AlertDialog alertDialog, View view) {
        //为获取屏幕宽、高
        WindowManager.LayoutParams p = alertDialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = WindowManager.LayoutParams.WRAP_CONTENT;
        p.width = (int) (mWidth * WIDTHFRACTION);
        p.gravity = Gravity.CENTER;
        alertDialog.getWindow().setAttributes(p);
    }

    /**
     * 晃动动画
     *
     * @param counts
     * @return
     */
    public static Animation shakeAnimation(int counts) {
        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(counts));
        translateAnimation.setDuration(100);
        return translateAnimation;
    }

    public interface OnEnterClick {
        void passVerifySuccess(String passWord);
    }
}
