package com.efounder.pansoft.chat.input;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.activity.SecretFileDisplayActivity;
import com.efounder.chat.activity.ViewSecretImageActivity;
import com.efounder.chat.activity.ViewSecretLetterActivity;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.utils.RSAUtil;
import com.efounder.chat.widget.SecretMessagePasswordDialog;
import com.efounder.chat.widget.SecretPassInputDialog;
import com.efounder.chat.widget.SecretSafeDialog;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.KeyboardUtils;

import net.sf.json.JSONObject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 加密输入密码对话框
 * Created by YQS on 2018/5/5.
 */

public class SecretInputView extends LinearLayout implements View.OnClickListener {
    private Context mContext;
    private LayoutInflater inflater;

    private View rootView;
    private EditText editText;
    private ImageView closeView;
    private TextView titleView;
    private SecrectInputViewListener listener;
    private IMStruct002 imstruct002;
    //消息的密码
    private String messagePwd;

    private TextView tvTips;
    private Button buttonEnter;

    //是否是自己发送的消息
    private boolean messageFromMySelf = false;
    //消息类型
    private short messageChildType;
    //私钥
    private static String privateKey;

    Disposable disposable;


    public SecretInputView(Context context) {
        this(context, null);
    }

    public SecretInputView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SecretInputView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs);
        mContext = context;
        initView(mContext);
    }

    private void initView(final Context mContext) {
        this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this.setGravity(Gravity.CENTER);
        //获取布局
        inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rootView = inflater.inflate(R.layout.wechatview_secretinputview_layout, this, true);
        editText = rootView.findViewById(R.id.et_password);
        titleView = rootView.findViewById(R.id.tvtitle);
        closeView = (ImageView) findViewById(R.id.iv_close);
        closeView.setOnClickListener(this);
        tvTips = (TextView) findViewById(R.id.tv_tips);
        buttonEnter = (Button) findViewById(R.id.button_enter);
        buttonEnter.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_close) {
            dismiss();
        } else if (id == R.id.button_enter) {
            String pass = editText.getText().toString();
            if (pass.trim().equals("")) {
                ToastUtil.showToastCenter(ResStringUtil.getString(R.string.open_planet_asset_password_dialog_password_not_empty));
                rootView.startAnimation(shakeAnimation(4));
                return;
            }
            if (privateKey == null) {
                ToastUtil.showToastCenter(ResStringUtil.getString(R.string.wechatview_key_empty_please));
                return;
            }
            messagePwd = pass;
            skipNextPage();
        }
    }

    //跳转到新界面
    private void skipNextPage() {
        Intent intent = new Intent();
        switch (messageChildType) {
            case MessageChildTypeConstant.subtype_secret_text://密信
                intent.setClass(mContext, ViewSecretLetterActivity.class);
                intent.putExtra("password", messagePwd);
                intent.putExtra("message", imstruct002.getMessage());
                break;
            case MessageChildTypeConstant.subtype_secret_image://密图
                intent.setClass(mContext, ViewSecretImageActivity.class);
                intent.putExtra("fromLocal", EnvironmentVariable.getProperty(CHAT_USER_ID).equals(String.valueOf(imstruct002.getFromUserId())));
                intent.putExtra("password", messagePwd);
                intent.putExtra("message", imstruct002.getMessage());
                break;
            case MessageChildTypeConstant.subtype_secret_file://密件
                intent.setClass(mContext, SecretFileDisplayActivity.class);
                intent.putExtra("fromLocal", EnvironmentVariable.getProperty(CHAT_USER_ID).equals(String.valueOf(imstruct002.getFromUserId())));
                intent.putExtra("password", messagePwd);
                intent.putExtra("message", imstruct002.getMessage());
                break;
            default:
                intent = null;
                break;
        }

        if (intent != null) {
            mContext.startActivity(intent);
            dismiss();
        }
    }


    //获取当前用户的私钥
    public void loadPrivateKey() {

        disposable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                String RSAPrivateKey = EnvironmentVariable.getProperty(RSAUtil.getCurrentPrivateKey());
                emitter.onNext(RSAPrivateKey);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                // ("生成私钥中..");
                showTcLoading(mContext, ResStringUtil.getString(R.string.common_text_generating_private_key));


            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                privateKey = s;
                // dismissLoading();
                dismissTcLoading();
                parseImstruct002();

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                // dismissLoading();
                dismissTcLoading();
                ToastUtil.showToast(mContext, ResStringUtil.getString(R.string.common_text_get_private_key_fail));
            }
        });
    }

    public void setImstruct(final IMStruct002 imstruct002) {
        this.imstruct002 = imstruct002;
        JSONObject jsonObject = JSONObject.fromObject(imstruct002.getMessage());
        //如果消息不是来自自己，并且消息中有password字段，首先显示基地密码输入框
        if (imstruct002.getFromUserId() != Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))
                && jsonObject.containsKey("password")) {
            SecretPassInputDialog dialog = new SecretPassInputDialog((Activity) mContext, new SecretPassInputDialog.OnEnterClick() {
                @Override
                public void passVerifySuccess(String passWord) {
                    show();
                }
            });
            dialog.show();
        } else {
            show();
        }
    }

    //显示该view
    public void show() {
//        this.setVisibility(View.VISIBLE);
//        showKeyboard(editText);
        if (privateKey == null) {
            loadPrivateKey();
        } else {
            parseImstruct002();
        }
    }

    //结束该view
    private void dismiss() {
        imstruct002 = null;
        messagePwd = null;
        if (disposable != null) {
            disposable.dispose();
        }

        //隐藏键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindowToken(), 0);
        ((Activity) mContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        reset();

        setBackgroundAlpha(1f);
        if (listener != null) {
            listener.secretInputViewClose();
        }
    }


    //重置一些设置
    private void reset() {
        this.setVisibility(View.GONE);
        tvTips.setVisibility(View.GONE);
        this.editText.setText("");

    }

    //解析消息
    private void parseImstruct002() {
        messageChildType = imstruct002.getMessageChildType();
        if (imstruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
            //消息来自自己
            messageFromMySelf = true;
        } else {
            messageFromMySelf = false;
        }

        try {
            JSONObject jsonObject = JSONObject.fromObject(imstruct002.getMessage());
            //消息不是来自自己 并且消息中包含密码字段
            if (!messageFromMySelf && jsonObject.containsKey("password")) {
                //使用私钥解密密码为明文
//                messagePwd = CertificateUtil.decrypt(jsonObject.getString("password"), privateKey);
                //todo 更改解密密码的方式
                messagePwd = RSAUtil.decryptByPrivateKey(jsonObject.getString("password"), privateKey);
                //从消息中移除密码字段并存入数据库
                jsonObject.remove("password");
                imstruct002.setMessage(jsonObject.toString());
                JFMessageManager.dbManager.update(imstruct002);

                //提示用户注意保存密码 谨防周围人员


                final SecretSafeDialog safeDialog = new SecretSafeDialog((Activity) mContext, new SecretSafeDialog.OnEnterClick() {
                    @Override
                    public void onEnterClick() {
                        //像用户展示密码，并且只展示一次
                        final SecretMessagePasswordDialog dialog = new SecretMessagePasswordDialog((Activity) mContext, messagePwd, new SecretMessagePasswordDialog.OnEnterClick() {
                            @Override
                            public void onEnterClick() {
                                //跳转新界面
                                skipNextPage();
                                dismiss();
                            }
                        });
                        dialog.show();
                    }
                });

                safeDialog.show();

            } else {
                //显示该view 并显示键盘
                setBackgroundAlpha(0.7f);
                this.setVisibility(View.VISIBLE);
                showKeyboard(editText);
            }

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToast(mContext, e.getMessage());
        }


    }


    //显示键盘
    public void showKeyboard(final EditText editText) {

        if (editText != null) {
            editText.post(new Runnable() {
                @Override
                public void run() {
                    KeyboardUtils.showSoftInput(editText);

                }
            });

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

    /**
     * 晃动动画
     *
     * @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 SecrectInputViewListener {
        //密码输入框被关闭
        void secretInputViewClose();
    }

    public void setSecrectInputViewListener(SecrectInputViewListener listener) {
        this.listener = listener;
    }

    public static void showTcLoading(Context context, String msg) {
//        Class class1 = null;
//        try {
//            class1 = Class.forName("com.pansoft.openplanet.widget.TCLoadingDataView");
//            Method showMethod = class1.getMethod("show", new Class[]{Context.class, String.class});
//            showMethod.invoke(null, new Object[]{context, msg});
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        LoadingDataUtilBlack.show(context, msg);
    }

    public static void dismissTcLoading() {
//        Class class1 = null;
//        try {
//            class1 = Class.forName("com.pansoft.openplanet.widget.TCLoadingDataView");
//            Method showMethod = class1.getMethod("dismiss", null);
//            showMethod.invoke(null, new Object[]{});
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        LoadingDataUtilBlack.dismiss();
    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
//        WindowManager.LayoutParams lp = ((Activity) mContext).getWindow()
//                .getAttributes();
//        lp.alpha = bgAlpha;
//        ((Activity) mContext).getWindow().setAttributes(lp);
    }
}
