package com.tengshisoft.mainmodule.base;

import android.content.Intent;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Base64;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.tengshisoft.mainmodule.R;
import com.tengshisoft.mainmodule.R2;
import com.tenlionsoft.baselib.constant.GlobalProvider;
import com.tenlionsoft.baselib.constant.LionActions;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.beans.AppTokenUser;
import com.tenlionsoft.baselib.core.beans.BaseSuccessBean;
import com.tenlionsoft.baselib.core.beans.LoginUser;
import com.tenlionsoft.baselib.core.network.update.CheckUpdateUtils;
import com.tenlionsoft.baselib.core.network.update.service.DownloadService;
import com.tenlionsoft.baselib.core.network.update.utils.Constants;
import com.tenlionsoft.baselib.core.retrofit_net.BaseUrlApi;
import com.tenlionsoft.baselib.core.retrofit_net.RetrofitManager;
import com.tenlionsoft.baselib.core.retrofit_net.api.BaseApiService;
import com.tenlionsoft.baselib.core.retrofit_net.bean.VersionBean;
import com.tenlionsoft.baselib.core.retrofit_net.conver.RxTransformer;
import com.tenlionsoft.baselib.core.widget.base.BaseActivity;
import com.tenlionsoft.baselib.utils.AesUtil;
import com.tenlionsoft.baselib.utils.AppUtils;
import com.tenlionsoft.baselib.utils.EncryptUtils;
import com.tenlionsoft.baselib.utils.ExceptionHandler;
import com.tenlionsoft.baselib.utils.LogUtils;
import com.tenlionsoft.baselib.utils.UserLgUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import okhttp3.RequestBody;

/**
 * 登录页面
 */
@Route(path = PathConfig.PATH_MODULE_MAIN_LOGIN)
public class LoginActivity extends BaseActivity {
    @BindView(R2.id.et_user_phone)
    EditText mEtUserPhone;
    @BindView(R2.id.et_user_pwd)
    EditText mEtUserPwd;
    @BindView(R2.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R2.id.tv_change_pwd)
    TextView mTvChangePwd;
    @BindView(R2.id.iv_show_pwd)
    ImageView mIvShowPwd;
    @BindView(R2.id.iv_clear_phone)
    ImageView mIvClosePhone;
    @BindView(R2.id.cb_remember)
    CheckBox mCbRemember;
    private Unbinder mUnbinder;
    private boolean isShowPwd = false;
    private boolean isRememberPwd = false;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void doShowOptions() {

    }

    @Override
    protected void clearSearch() {

    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    public void initData() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        mUnbinder = ButterKnife.bind(this);
        mRlTitleBar.setVisibility(View.GONE);
        refreshView(STATE_LOAD_SUCCESS);
        mRlNotify.setVisibility(View.GONE);
        mBtnConfirm.setOnClickListener(v -> login());
        isRememberPwd = UserLgUtils.getCheckRemember();
        mCbRemember.setChecked(isRememberPwd);
        mCbRemember.setOnCheckedChangeListener((compoundButton, b) -> {
            isRememberPwd = b;
            UserLgUtils.setCheckRemember(b);
        });
        mIvShowPwd.setOnClickListener(v -> {
            Editable etext = mEtUserPwd.getText();
            Selection.setSelection(etext, etext.length());
            if (isShowPwd) {
                isShowPwd = false;
                mEtUserPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                mIvShowPwd.setBackgroundResource(R.drawable.ic_hide_pwd);
            } else {
                isShowPwd = true;
                mIvShowPwd.setBackgroundResource(R.drawable.ic_show_pwd);
                mEtUserPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
        });
        setEditTextInhibitInputSpeChat(mEtUserPhone);
        setEditTextInhibitInputSpeChat(mEtUserPwd);
        mEtUserPhone.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) {
                if (!TextUtils.isEmpty(s)) {
                    mIvClosePhone.setVisibility(View.VISIBLE);
                } else {
                    mIvClosePhone.setVisibility(View.INVISIBLE);
                }
            }
        });


        String username = UserLgUtils.getUserName();
        if (!TextUtils.isEmpty(username)) {
            mEtUserPhone.setText(username);
        }
        if (isRememberPwd) {
            String passWord = UserLgUtils.getPassword();
            if (!TextUtils.isEmpty(passWord)) {
                mEtUserPwd.setText(passWord);
                login();
            }
        }
        setTouchDelegate(mIvClosePhone, 40);
        mIvClosePhone.setOnClickListener(v -> mEtUserPhone.setText(""));
        mTvChangePwd.setOnClickListener(v -> ARouter.getInstance()
            .build(PathConfig.PATH_MODULE_COMMON_ACTIVITY_FORGET_PWD)
            .navigation());

    }

    /**
     * 登录
     */
    public void login() {
        if (checkUserInputInfo()) {
            String userName = mEtUserPhone.getText().toString().trim();
            String pwd = mEtUserPwd.getText().toString().trim();
            doLoginApp(userName, pwd);
        }
    }

    /**
     * 登录
     */
    private void doLoginApp(String name, String pwd) {
        hideSoftKeyboard();
        refreshLoginState(11);
        String deviceId = AppUtils.getDeviceId(mActivity);
        String md5Pwd = EncryptUtils.encryptMD5ToStringTimes(pwd, 3);
        LoginUser info = new LoginUser();
        info.setAppVersion(AppUtils.getAppVersionCode());
        info.setAppId(BaseUrlApi.APP_VERSION_ID);
        info.setPassword(md5Pwd);
        info.setUsername(name);
        info.setDeviceNo(deviceId);
        Gson gson = new Gson();
        String obj = gson.toJson(info);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), obj);
        RetrofitManager.getInstance()
            .create(BaseApiService.class)
            .doLogin(body)
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<BaseSuccessBean>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(BaseSuccessBean baseUserBean) {
                    if (!TextUtils.isEmpty(baseUserBean.getData())) {
                        byte[] decode = Base64.decode(baseUserBean.getData(), Base64.DEFAULT);
                        try {
                            String loginUserInfo = AesUtil.aesCommonDecoder(PathConfig.SECRET, new String(decode, "UTF-8"));
                            LogUtils.e(loginUserInfo);
                            if (!TextUtils.isEmpty(loginUserInfo)) {
                                AppTokenUser appTokenUser = gson.fromJson(loginUserInfo, AppTokenUser.class);
                                refreshLoginState(12);
                                //是网格员
                                UserLgUtils.setLoginInfo(loginUserInfo);
                                UserLgUtils.setPassword(pwd);
                                UserLgUtils.setAvatar(appTokenUser.getAvatar());
                                UserLgUtils.setEmail(appTokenUser.getEmail());
                                UserLgUtils.setId(appTokenUser.getId());
                                UserLgUtils.setName(appTokenUser.getName());
                                UserLgUtils.setUserName(appTokenUser.getUsername());
                                UserLgUtils.setPhone(appTokenUser.getPhone());
                                UserLgUtils.setToken(baseUserBean.getData());
                                GlobalProvider.save(mActivity, "token", baseUserBean.getData());
                                GlobalProvider.save(mActivity, "userId", appTokenUser.getId());
                                GlobalProvider.save(mActivity, "userName", appTokenUser.getUsername());
                                GlobalProvider.save(mActivity, "name", appTokenUser.getName());
                                UserLgUtils.setUserDeptId(new Gson().toJson(appTokenUser.getDepartments()));
                                if (isRememberPwd) {
                                    UserLgUtils.setPassword(pwd);
                                }
                                ARouter.getInstance()
                                    .build(PathConfig.PATH_MODULE_MAIN_NAVIGATION_HOME)
                                    .withString(LionActions.EXTRA_PUSH_MSG, getIntent().getStringExtra(LionActions.EXTRA_PUSH_MSG))
                                    .withInt(LionActions.EXTRA_MSG_TYPE, getIntent().getIntExtra(LionActions.EXTRA_MSG_TYPE, -1))
                                    .withString("to", getIntent().getStringExtra("to"))
                                    .withString("time", getIntent().getStringExtra("time"))
                                    .withString(LionActions.EXTRA_MSG_CONF_ID, getIntent().getStringExtra(LionActions.EXTRA_MSG_CONF_ID))
                                    .navigation();
                                finish();
                            } else {
                                ToastUtils.show("登录失败,请稍后重试.");
                                refreshLoginState(12);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtils.show("登录失败,请稍后重试.");
                            refreshLoginState(12);
                        }
                    } else {
                        ToastUtils.show("登录失败,请稍后重试.");
                        refreshLoginState(12);
                    }
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    refreshLoginState(12);
                    int i = ExceptionHandler.handleExceptionWithLogin(e);
                    if (i == 40502) {
                        checkPermission();
                    }
                }

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * TODO 登录强制更新
     */
    private void checkPermission() {
        RetrofitManager.getInstance()
            .create(BaseApiService.class)
            .doCheckAppVersion(BaseUrlApi.APP_VERSION_ID)
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<VersionBean>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(VersionBean successBean) {
                    if (successBean != null && successBean.getData() > 0) {
                        if (CheckUpdateUtils.checkcode(LoginActivity.this, successBean.getData() + "")) {
                            startDownloadApk();
                        }
                    }
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
    }

    /**
     * 开始下载Apk
     */
    private void startDownloadApk() {
        ToastUtils.show("检测到新版本,开始下载,请在通知栏查看下载进度");
        Intent intent = new Intent(mActivity, DownloadService.class);
        intent.putExtra(Constants.APK_DOWNLOAD_URL, BaseUrlApi.APP_DOWNLOAD_URL);
        startService(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 10086:
                    login();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 校验用户输入的账号密码
     *
     * @return
     */
    private boolean checkUserInputInfo() {
        String userName = mEtUserPhone.getText().toString().trim();
        String pwd = mEtUserPwd.getText().toString().trim();
        // || !RegexUtils.isMobileExact(userName)
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.show("账号有误,请重新输入.");
            return false;
        }
        if (TextUtils.isEmpty(pwd)) {
            ToastUtils.show("密码不能为空.");
            return false;
        }
        return true;
    }

    /**
     * 刷新登录按钮的状态
     *
     * @param state 11登录中  12登录失败或成功
     */
    private void refreshLoginState(int state) {
        switch (state) {
            case 11://登录中
                mBtnConfirm.setEnabled(false);
                mBtnConfirm.setText("登录中...");
                break;
            case 12://登录失败后成功
                mBtnConfirm.setEnabled(true);
                mBtnConfirm.setText("登录");
                break;
        }
    }


}
