package com.genlot.ninglottery.module.scan;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.genlot.nativesdk.SystemNI;
import com.genlot.nativesdk.model.GameCashTicket;
import com.genlot.nativesdk.model.GameTicket;
import com.genlot.nativesdk.sender.EventToken;
import com.genlot.ninglottery.R;
import com.genlot.ninglottery.base.BaseMVPActivity;
import com.genlot.ninglottery.base.InjectPresenter;
import com.genlot.ninglottery.game.GameActivity;
import com.genlot.ninglottery.game.GameManager;
import com.genlot.ninglottery.model.Constant;
import com.genlot.ninglottery.module.cancel.CancelActivity;
import com.genlot.ninglottery.module.cash.CashActivity;
import com.genlot.ninglottery.toolkit.LogTool;
import com.genlot.ninglottery.toolkit.TrainMode;
import com.genlot.ninglottery.widget.FeatureCodeKeyboard;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnFocusChange;

/**
 * @author ZhuYongKang
 * @description 兑奖扫描界面
 * @date 2019/10/8
 */
public class ScanActivity extends BaseMVPActivity implements IScanView{

    private FeatureCodeKeyboard mKeyboard;
    @InjectPresenter
    ScanPresenter mPresenter;
    StringBuilder scanResult = new StringBuilder();
    private int mType = Constant.TYPE_CASH;
    private String featureCode;

    @OnFocusChange({R.id.tv_code1, R.id.tv_code2, R.id.tv_code3, R.id.tv_code4, R.id.tv_code5, R.id.tv_code6, R.id.tv_code7})
    void onFocusChange(EditText view, boolean hasFocus) {
        if (hasFocus) {
            if (mKeyboard != null) {
                mKeyboard.changeEditText(view);
                mKeyboard.showKeyboard();
            }
        }
    }

    @OnClick(R.id.bt_back)
    void back() {
        finish();
    }

    @Override
    public int getLayoutID() {
        return R.layout.fragment_scan;
    }

    @Override
    public void initViews(Bundle savedInstanceState) {
        if (getIntent() != null) {
            mType = getIntent().getIntExtra(Constant.KEY_TYPE, Constant.TYPE_COPY);
        }
        if (mType == Constant.TYPE_COPY) {
            tvTitle.setText("复 制");
        } else if (mType == Constant.TYPE_CANCEL) {
            tvTitle.setText("注 销");
        } else {
            tvTitle.setText("兑 奖");
        }
        mKeyboard = new FeatureCodeKeyboard(this, et_code1, rl_keyboard_container, false);
        et_code1.requestFocus();
        mKeyboard.setOnKeyCodeFinish(new FeatureCodeKeyboard.KeyCodeFinishListener() {
            @Override
            public void onKeyCodeFinish() {
                featureCode = getInputFeatureCode();
                if (!TextUtils.isEmpty(featureCode)) {
                    if (mType == Constant.TYPE_COPY) {
                        if (GameManager.isTrainMode) {
                            GameTicket ticket = TrainMode.getGameTicket();
                            EventBus.getDefault().post(ticket);
                            finish();
                        } else {
                            mPresenter.t101007QueryTicket(featureCode);
                        }
                    } else if (mType == Constant.TYPE_CANCEL) {
                        if (GameManager.isTrainMode) {
                            GameTicket cancelTicket = TrainMode.getGameTicket();
                            Intent cancelIntent = new Intent(ScanActivity.this, CancelActivity.class);
                            cancelIntent.putExtra(Constant.KEY_TICKET, cancelTicket);
                            cancelIntent.putExtra(Constant.KEY_CODE, featureCode);
                            startActivity(cancelIntent);
                            finish();
                        } else {
                            mPresenter.t101007QueryTicket(featureCode);
                        }
                    } else {
                        if (GameManager.isTrainMode) {
                            GameCashTicket cashTicket = TrainMode.getCashTicket();
                            Intent cashIntent = new Intent(ScanActivity.this, CashActivity.class);
                            cashIntent.putExtra(Constant.KEY_TICKET, cashTicket);
                            cashIntent.putExtra(Constant.KEY_CODE, featureCode);
                            startActivity(cashIntent);
                            finish();
                        } else {
                            mPresenter.t101008CashQuery(featureCode);
                        }
                    }
                }
            }

            @Override
            public void onKeyClear() {
                clearCode();
            }
        });
        et_code1.addTextChangedListener(textChangedListener(et_code1));
        et_code2.addTextChangedListener(textChangedListener(et_code2));
        et_code3.addTextChangedListener(textChangedListener(et_code3));
        et_code4.addTextChangedListener(textChangedListener(et_code4));
        et_code5.addTextChangedListener(textChangedListener(et_code5));
        et_code6.addTextChangedListener(textChangedListener(et_code6));
        et_code7.addTextChangedListener(textChangedListener(et_code7));
        et_code1.setOnKeyListener(new MyOnKeyListener());
        et_code2.setOnKeyListener(new MyOnKeyListener());
        et_code3.setOnKeyListener(new MyOnKeyListener());
        et_code4.setOnKeyListener(new MyOnKeyListener());
        et_code5.setOnKeyListener(new MyOnKeyListener());
        et_code6.setOnKeyListener(new MyOnKeyListener());
        et_code7.setOnKeyListener(new MyOnKeyListener());
    }

    @Override
    public void onResume() {
        super.onResume();
        clearCode();
    }

    private void clearCode() {
        et_code1.setText("");
        et_code2.setText("");
        et_code3.setText("");
        et_code4.setText("");
        et_code5.setText("");
        et_code6.setText("");
        et_code7.setText("");
        et_code1.requestFocus();
    }

    class MyOnKeyListener implements View.OnKeyListener{

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    //PDF417做了加密，先解密
                    String decryptFeatureCode = SystemNI.rc4DecryptData(scanResult.toString());
                    LogTool.logD("scanResult:" + decryptFeatureCode);
                    if (decryptFeatureCode.length() >= 28) {
                        et_code1.setText(decryptFeatureCode.substring(0,4));
                        et_code2.setText(decryptFeatureCode.substring(4,8));
                        et_code3.setText(decryptFeatureCode.substring(8,12));
                        et_code4.setText(decryptFeatureCode.substring(12,16));
                        et_code5.setText(decryptFeatureCode.substring(16,20));
                        et_code6.setText(decryptFeatureCode.substring(20,24));
                        et_code7.setText(decryptFeatureCode.substring(24,28));
                    }
                    scanResult.delete(0, scanResult.length());
                } else {
                    scanResult.append(keyCodeToChar(keyCode));
                }
            }
            return true;
        }
    }

    public String keyCodeToChar(int code){
        switch(code){
            //数字键10个 + 符号10个
            case KeyEvent.KEYCODE_0: return  "0";
            case KeyEvent.KEYCODE_1: return  "1";
            case KeyEvent.KEYCODE_2: return  "2";
            case KeyEvent.KEYCODE_3: return  "3";
            case KeyEvent.KEYCODE_4: return  "4";
            case KeyEvent.KEYCODE_5: return  "5";
            case KeyEvent.KEYCODE_6: return  "6";
            case KeyEvent.KEYCODE_7: return  "7";
            case KeyEvent.KEYCODE_8: return  "8";
            case KeyEvent.KEYCODE_9: return  "9";

            //字母键26个小写 + 26个大写
            case KeyEvent.KEYCODE_A: return  "A" ;
            case KeyEvent.KEYCODE_B: return  "B" ;
            case KeyEvent.KEYCODE_C: return  "C" ;
            case KeyEvent.KEYCODE_D: return  "D";
            case KeyEvent.KEYCODE_E: return  "E" ;
            case KeyEvent.KEYCODE_F: return  "F";
            case KeyEvent.KEYCODE_G: return  "G" ;
            case KeyEvent.KEYCODE_H: return  "H" ;
            case KeyEvent.KEYCODE_I: return  "I" ;
            case KeyEvent.KEYCODE_J: return  "J" ;
            case KeyEvent.KEYCODE_K: return  "K";
            case KeyEvent.KEYCODE_L: return  "L";
            case KeyEvent.KEYCODE_M: return  "M";
            case KeyEvent.KEYCODE_N: return  "N" ;
            case KeyEvent.KEYCODE_O: return  "O" ;
            case KeyEvent.KEYCODE_P: return  "P";
            case KeyEvent.KEYCODE_Q: return  "Q" ;
            case KeyEvent.KEYCODE_R: return  "R" ;
            case KeyEvent.KEYCODE_S: return  "S" ;
            case KeyEvent.KEYCODE_T: return  "T" ;
            case KeyEvent.KEYCODE_U: return  "U" ;
            case KeyEvent.KEYCODE_V: return  "V" ;
            case KeyEvent.KEYCODE_W: return  "W";
            case KeyEvent.KEYCODE_X: return  "X" ;
            case KeyEvent.KEYCODE_Y: return  "Y" ;
            case KeyEvent.KEYCODE_Z: return  "Z" ;

            //符号键11个 + 11个
            case KeyEvent.KEYCODE_COMMA: return ",";
            case KeyEvent.KEYCODE_PERIOD: return  ".";
            case KeyEvent.KEYCODE_SLASH: return "/";
            case KeyEvent.KEYCODE_BACKSLASH: return "\\";
            case KeyEvent.KEYCODE_APOSTROPHE: return  "'";
            case KeyEvent.KEYCODE_SEMICOLON:  return ";";
            case KeyEvent.KEYCODE_LEFT_BRACKET: return  "[";
            case KeyEvent.KEYCODE_RIGHT_BRACKET: return  "]";
            case KeyEvent.KEYCODE_GRAVE: return  "`";
            case KeyEvent.KEYCODE_EQUALS: return  "=";
            case KeyEvent.KEYCODE_MINUS: return  "-";
            default: return "";
        }
    }

    private TextWatcher textChangedListener(View view) {
        return 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) {
                if (s.length() > 3) {
                    if (view == et_code1) {
                        et_code2.requestFocus();
                    } else if (view == et_code2) {
                        et_code3.requestFocus();
                    } else if (view == et_code3) {
                        et_code4.requestFocus();
                    } else if (view == et_code4) {
                        et_code5.requestFocus();
                    } else if (view == et_code5) {
                        et_code6.requestFocus();
                    } else if (view == et_code6) {
                        et_code7.requestFocus();
                    } else if (view == et_code7) {
                        getInputFeatureCode();
                    }
                }
            }
        };
    }

    private String getInputFeatureCode() {
        StringBuilder stringBuilder = new StringBuilder();
        String str1 = et_code1.getText().toString().trim();
        String str2 = et_code2.getText().toString().trim();
        String str3 = et_code3.getText().toString().trim();
        String str4 = et_code4.getText().toString().trim();
        String str5 = et_code5.getText().toString().trim();
        String str6 = et_code6.getText().toString().trim();
        String str7 = et_code7.getText().toString().trim();
        if (TextUtils.isEmpty(str1) || str1.length() < 4) {
            ToastUtils.showShort(R.string.tips_input1);
            et_code1.postDelayed(() -> et_code1.requestFocus(), 20);
            return "";
        } else if (TextUtils.isEmpty(str2) || str2.length() < 4) {
            ToastUtils.showShort(R.string.tips_input2);
            et_code2.postDelayed(() -> et_code2.requestFocus(), 20);
            return "";
        } else if (TextUtils.isEmpty(str3) || str3.length() < 4) {
            ToastUtils.showShort(R.string.tips_input3);
            et_code3.postDelayed(() -> et_code3.requestFocus(), 20);
            return "";
        } else if (TextUtils.isEmpty(str4) || str4.length() < 4) {
            ToastUtils.showShort(R.string.tips_input4);
            et_code4.postDelayed(() -> et_code4.requestFocus(), 20);
            return "";
        } else if (TextUtils.isEmpty(str5) || str5.length() < 4) {
            ToastUtils.showShort(R.string.tips_input5);
            et_code5.postDelayed(() -> et_code5.requestFocus(), 20);
            return "";
        } else if (TextUtils.isEmpty(str6) || str6.length() < 4) {
            ToastUtils.showShort(R.string.tips_input6);
            et_code6.postDelayed(() -> et_code6.requestFocus(), 20);
            return "";
        } else if (TextUtils.isEmpty(str7) || str7.length() < 4) {
            ToastUtils.showShort(R.string.tips_input7);
            et_code7.postDelayed(() -> et_code7.requestFocus(), 20);
            return "";
        }
        return stringBuilder.append(str1).append(str2).append(str3).append(str4).append(str5)
                .append(str6).append(str7).toString();
    }

    @Override
    public void onQuerySuccess(Bundle bundle) {
        dismissLoading();
        switch (mType) {
            case Constant.TYPE_COPY:
                GameTicket copyTicket = bundle.getParcelable(EventToken.EVENT_KEY_RESULT_OBJECT);
                EventBus.getDefault().post(copyTicket);
                finish();
                break;
            case Constant.TYPE_CASH:
                GameCashTicket cashTicket = bundle.getParcelable(EventToken.EVENT_KEY_RESULT_OBJECT);
                Intent cashIntent = new Intent(this, CashActivity.class);
                cashIntent.putExtra(Constant.KEY_TICKET, cashTicket);
                cashIntent.putExtra(Constant.KEY_CODE, featureCode);
                startActivity(cashIntent);
                finish();
                break;
            case Constant.TYPE_CANCEL:
                GameTicket cancelTicket = bundle.getParcelable(EventToken.EVENT_KEY_RESULT_OBJECT);
                Intent cancelIntent = new Intent(this, CancelActivity.class);
                cancelIntent.putExtra(Constant.KEY_TICKET, cancelTicket);
                cancelIntent.putExtra(Constant.KEY_CODE, featureCode);
                startActivity(cancelIntent);
                finish();
                break;
        }
    }

    @Override
    public void onQueryFail(String message) {
        dismissLoading();
        runOnUiThread(() -> {
            if (message != null) {
                EventBus.getDefault().post(message);
            }
            finish();
        });
    }

    @BindView(R.id.textView)
    TextView tvTitle;
    @BindView(R.id.tv_code1)
    public EditText et_code1;
    @BindView(R.id.tv_code2)
    public EditText et_code2;
    @BindView(R.id.tv_code3)
    public EditText et_code3;
    @BindView(R.id.tv_code4)
    public EditText et_code4;
    @BindView(R.id.tv_code5)
    public EditText et_code5;
    @BindView(R.id.tv_code6)
    public EditText et_code6;
    @BindView(R.id.tv_code7)
    public EditText et_code7;
    @BindView(R.id.keyboard_container)
    public RelativeLayout rl_keyboard_container;

}
