package com.tofly.ghrq_route.common.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.common.ui.dialog.DeviceBindBottomDialog;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.systemConfig.SystemConfigTool;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.module.user.domain.UserBean.PDA_BIND_STATUS;
import com.tofly.ghrq_route.module.user.domain.UserMenuBean;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.common.util.sharedPreference.SharePreUtil;

import java.util.List;
import java.util.Timer;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zombiexq on 2016/6/13.
 */
public class UiLogin extends BaseUi {
    @BindView(R.id.ui_login_setting)
    TextView uiLoginSetting;
    @BindView(R.id.ui_login_name)
    EditText uiLoginName;
    @BindView(R.id.imageview_user_close)
    ImageView imageviewUserClose;
    @BindView(R.id.ui_login_pass)
    EditText uiLoginPass;
    @BindView(R.id.imageview_pass_close)
    ImageView imageviewPassClose;
    @BindView(R.id.ui_login_submit)
    Button uiLoginSubmit;
    @BindView(R.id.ui_login_checkbox)
    CheckBox uiLoginCheckbox;
    @BindView(R.id.ui_login_reg)
    TextView uiLoginReg;
    @BindView(R.id.login_progress)
    ProgressBar loginProgress;
    @BindView(R.id.text_backup_mode)
    TextView textBackupMode;

    private String username, password;
    private boolean bRemembered = false;
    private boolean bNeedRelogin = false;
    private boolean bNeedEncPass = true;
    private DBDaoHelper dbDaoHelper;

    private Timer mtimer = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_login);
        ButterKnife.bind(this);
        dbDaoHelper = DBDaoHelper.getInstance();

        initView();
        initData();
        initListener();

        checkPermission();
    }

    private void initView() {
        setDarkStatusBar();
    }

    private void initData() {
        //创建父路径
        FileUtil.makeDirs(C.dir.base);

        //创建地图文件路径,存放tpk背景图和geodatabase管线数据
        FileUtil.makeDirs(C.dir.data);

        //检测灾备模式是否开启
        //startCheckBackupTimer();
    }

    private void initListener() {
         /*
        用户名更改监听操作
         */
        uiLoginName.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 strInput = s.toString();
                if (strInput.isEmpty()) {
                    imageviewUserClose.setVisibility(View.GONE);
                } else {
                    imageviewUserClose.setVisibility(View.VISIBLE);
                }
                uiLoginPass.setText("");
            }
        });

        uiLoginPass.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) {
                bNeedEncPass = true;
                String strInput = s.toString();
                if (strInput.isEmpty()) {
                    imageviewPassClose.setVisibility(View.GONE);
                } else {
                    imageviewPassClose.setVisibility(View.VISIBLE);
                }
            }
        });

        uiLoginPass.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_GO){
                login(false);
            }
            return false;
        });
    }

    private void checkLogin(){
        boolean hasToken = false;
        boolean hasName = false;
        String token = "";
        String name = "";
        String userid = "";
        UserBean savedUser = null;

        /*判断用户是否登陆过，并且拿到数据库中的用户token，否则则视为未登录过*/
        UserBean rememberedUser = SharePreUtil.getLoginInfo(this);
        bRemembered = SharePreUtil.getIsLogined(UiLogin.this);
        bNeedRelogin = SharePreUtil.getIsNeedReLogin(this);
        uiLoginCheckbox.setChecked(bRemembered);
        if (!bRemembered){
            if (rememberedUser != null){
                uiLoginName.setText(rememberedUser.getUsername());
            }
            return;
        }

        if (rememberedUser != null){
            String saveName = rememberedUser.getUsername();
            if (saveName != null && !saveName.isEmpty()){
                hasName = true;
                name = saveName;
                uiLoginName.setText(name);
            }

            String savePassword = rememberedUser.getPassword();
            if (savePassword != null && !savePassword.isEmpty()){
/*                AESUtils aesUtils = AESUtils.getInstance(BaseApp.AES_CODE_KEY.getBytes());
                password = aesUtils.decryptHexToString(savePassword, CharEncoding.UTF_8);*/
                uiLoginPass.setText(savePassword);
                bNeedEncPass = false;
            }

            String saveUserId = rememberedUser.getUserid();
            if (saveUserId != null && !saveUserId.isEmpty()){
                userid = saveUserId;
                savedUser = dbDaoHelper.queryUserByUserId(userid);
                if (savedUser != null){
                    hasToken = true;
                    token = savedUser.getToken();
                }
            }
        }

        if (isNetworkConnected()){
            /*如果获取到token，向服务器请求用户信息*/
            if (!bNeedRelogin && bRemembered && hasToken && hasName){
                 checkUserBind(name, token);
            }
        }else {
            if (!bNeedRelogin){
                /*if (savedUser != null){
                    BaseApp.getInstance().setLoginUser(savedUser);
                    OfflineWorkTool.setOffline(true);
                    gotoUiMain();
                }else */{
                    toast("当前网络不可用，请稍后再试!");
                }
            }
        }
    }

    private int READ_FINE_LOCATION_REQUEST_CODE = 100;
    private void checkPermission(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            String locationPermission = Manifest.permission.ACCESS_FINE_LOCATION;
            String storageWritePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            String phoneStatePermission = Manifest.permission.READ_PHONE_STATE;
            if (checkSelfPermission(locationPermission) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(storageWritePermission) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(phoneStatePermission) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{locationPermission, storageWritePermission, phoneStatePermission},
                        READ_FINE_LOCATION_REQUEST_CODE);
            }else {
                checkLogin();
                BaseApp.getInstance().getDevieImei();
            }
        }else {
            checkLogin();
            BaseApp.getInstance().getDevieImei();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == READ_FINE_LOCATION_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(this.getClass().getSimpleName(), "READ_FINE_LOCATION Permission Granted!");
            }else {
                Log.e(this.getClass().getSimpleName(), "READ_FINE_LOCATION Permission Denied!");
            }
            if (grantResults[1] == PackageManager.PERMISSION_GRANTED){
                Log.d(this.getClass().getSimpleName(), "WRITE_EXTERNAL_STORAGE Permission Granted!");
            }else {
                Log.e(this.getClass().getSimpleName(), "WRITE_EXTERNAL_STORAGE Permission Denied!");
            }
            if (grantResults[2] == PackageManager.PERMISSION_GRANTED){
                Log.d(this.getClass().getSimpleName(), "READ_PHONE_STATE Permission Granted!");
                checkLogin();
                BaseApp.getInstance().getDevieImei();
            }else {
                Log.e(this.getClass().getSimpleName(), "READ_PHONE_STATE Permission Denied!");
                toast("用户登录需要获取收手机IMEI号码，请赋予相应的权限。");
            }
        }
    }

    public boolean isValid() {
        username = uiLoginName.getText().toString();
        password = uiLoginPass.getText().toString();
        if (username.length() == 0) {
            toast("请输入登录名");
            return false;
        }
        if (password.length() == 0) {
            toast("请输入密码");
            return false;
        }

        if (bNeedEncPass) {
            password = BaseApp.SHA1EncodeString(password);
        }

        return true;
    }

    private void login(boolean forceLogin){
        if (isValid()) {
            hideSoftKeyboard();
            showLoading();
            UserInfoTool userInfoTool = UserInfoTool.getInstance();
            userInfoTool.userLoginOnline(this, username, password, forceLogin, new UserCallBack(){
                @Override
                public void onLogin(boolean isSuccess, int errorCode, String errMsg, UserBean user) {
                    super.onLogin(isSuccess, errorCode, errMsg, user);
                    hideLoading();
                    if (isSuccess){
                    }/*else {
                        if (errorCode == URLResponseCode.ErrorCode.LOGIN_RELOGIN_ERROR){
                            //showAlreadyLoginAlert();
                            login(true);
                        }
                    }*/
                }

                @Override
                public void onCheckPdaBind(boolean isSuccess, int errorCode, String errMsg, int bind_status) {
                    super.onCheckPdaBind(isSuccess, errorCode, errMsg, bind_status);
                    if (isSuccess) {
                        if (bind_status == PDA_BIND_STATUS.PDA_UNBIND.getStatus()) {
                            showDeviceBindDialog();
                        }else if (bind_status == PDA_BIND_STATUS.PDA_BINDED.getStatus()){
                            getUserMenus();
                        }
                    }
                }

                /*@Override
                public void onGetUserMenus(boolean isSuccess, int errorCode, String errMsg, List<UserMenuBean> menus) {
                    super.onGetUserMenus(isSuccess, errorCode, errMsg, menus);
                    if (isSuccess){
                        setRemeberUser();
                        if (C.bLoginCheckServerConfig_debug)
                            checkServerConfigData();
                        if (menus != null){
                            gotoUiMain();
                        }
                    }else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        toast(errMsg);
                    }
                }*/
            });
        }
    }

    private void showAlreadyLoginAlert(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.ui_login_submit);
        builder.setMessage(R.string.ui_login_relogin);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> login(true));
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void checkUserBind(String username, final String token) {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.checkPdaBinded(this, new UserCallBack(){
            @Override
            public void onCheckPdaBind(boolean isSuccess, int errorCode, String errMsg, int bind_status) {
                super.onCheckPdaBind(isSuccess, errorCode, errMsg, bind_status);
                if (isSuccess) {
                    if (bind_status == PDA_BIND_STATUS.PDA_BINDED.getStatus()) {//设备已绑定
                        getUserInfo(username, token);
                    }else if (bind_status == PDA_BIND_STATUS.PDA_UNBIND.getStatus()){
                        showDeviceBindDialog(username, token);
                    }
                }
            }
        });
    }

    private void getUserInfo(String username, final String token){
        String strUploading = getString(R.string.logining_wait);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getUserInfo(this, username, token, new UserCallBack(){
            @Override
            public void onGetAccountInfo(boolean isSuccess, int errorCode, String errMsg, UserBean user) {
                super.onGetAccountInfo(isSuccess, errorCode, errMsg, user);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess){
                    getUserMenus();
                }
            }
        });
    }

    private void showDeviceBindDialog(){
        DeviceBindBottomDialog bindBottomDialog = new DeviceBindBottomDialog(this);
        bindBottomDialog.setOnDeviceBindedd(isSuccess -> {
            if (isSuccess){
                getUserMenus();
            }
        });
        bindBottomDialog.show();
    }

    private void showDeviceBindDialog(String username, final String token){
        DeviceBindBottomDialog bindBottomDialog = new DeviceBindBottomDialog(this);
        bindBottomDialog.setOnDeviceBindedd(isSuccess -> {
            if (isSuccess){
               getUserInfo(username, token);
            }
        });
        bindBottomDialog.show();
    }

    private void getUserMenus() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getUserMenus(this, new UserCallBack() {
            @Override
            public void onGetUserMenus(boolean isSuccess, int errorCode, String errMsg, List<UserMenuBean> userMenus) {
                super.onGetUserMenus(isSuccess, errorCode, errMsg, userMenus); {
                    setRemeberUser();
                    if (C.bLoginCheckServerConfig_debug)
                        checkServerConfigData();
                    if (userMenus != null){
                        //getRestrictFile();
                        gotoUiMain();
                    }
                }
            }
        });
    }

    private void gotoUiMain(){
        BaseApp.getInstance().startBackgroundOfflineWorkService(this);
        Bundle bundle = new Bundle();
        String title = getResources().getString(R.string.app_name) + " (" + BaseApp.getAppVersionName() + ")";
        bundle.putString("title", title);
        forward(HomeActivity.class, bundle);//跳转到隐患列表
    }

    private void checkServerConfigData(){
        SystemConfigTool systemConfigTool = SystemConfigTool.getInstance();
        systemConfigTool.updateServerConfig(this);
    }

    private void showLoading(){
        uiLoginSubmit.setText(R.string.ui_login_in_progress);
        uiLoginSubmit.setEnabled(false);
        loginProgress.setVisibility(View.VISIBLE);
        loginProgress.bringToFront();
    }

    private void hideLoading(){
        uiLoginSubmit.postDelayed(() -> {
            uiLoginSubmit.setText(R.string.ui_login_submit);
            uiLoginSubmit.setEnabled(true);
            loginProgress.setVisibility(View.GONE);
        }, 200);
    }

    private void setRemeberUser() {
        if (uiLoginCheckbox.isChecked()){
            bRemembered = true;
            bNeedRelogin = false;
            SharePreUtil.setIsLogined(UiLogin.this, true);
            SharePreUtil.setIsNeedReLogin(UiLogin.this, false);
        }else {
            SharePreUtil.setIsLogined(UiLogin.this, false);
        }
    }

    @OnClick({R.id.ui_login_setting, R.id.imageview_user_close, R.id.imageview_pass_close, R.id.ui_login_submit, R.id.ui_login_reg})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ui_login_setting:{
                Intent intent = new Intent();
                intent.putExtra("title", getString(R.string.setting_title));
                intent.setClass(UiLogin.this, UiSetting.class);
                startActivity(intent);
                BaseApp.getInstance().cancelAllRequest(getClass().getName());
            }
            break;
            case R.id.imageview_user_close:{
                uiLoginName.setText("");
                uiLoginPass.setText("");
            }
            break;
            case R.id.imageview_pass_close:{
                uiLoginPass.setText("");
            }
            break;
            case R.id.ui_login_submit:{
                login(false);
            }
            break;
            case R.id.ui_login_reg: {
                Intent intent = new Intent();
                intent.setClass(UiLogin.this, UiRegisterAccount.class);
                startActivity(intent);
            }
            break;
        }
    }

    @Override
    protected void onStop() {
        BaseApp.cancelRequest(getClass().getName());
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mtimer != null)
            mtimer.cancel();
        mtimer = null;
    }
}
