package com.unis.sxzcl.ui.login;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;

import com.google.android.material.textfield.TextInputLayout;
import com.unis.model.DataCallback;
import com.unis.model.UserModel;
import com.unis.model.bean.CaptchaBean;
import com.unis.model.bean.LoginBean;
import com.unis.model.login_log.LogFirst;
import com.unis.model.login_log.LoginLog;
import com.unis.model.login_log.LoginLogDelAllTask;
import com.unis.model.login_log.LoginLogFirstTask;
import com.unis.model.login_log.LoginLogListTask;
import com.unis.model.login_log.LoginLogSaveTask;
import com.unis.sxzcl.base.BaseFragment;
import com.unis.sxzcl.databinding.FragmentLoginBinding;
import com.unis.sxzcl.ui.home.MainActivity;
import com.unis.sxzcl.util.VersionCheckTool;
import com.unis.sxzcl.widget.BottomMultipleListDialog;
import com.unis.sxzcl.widget.MultipleBean;
import com.xyxsbj.mylibrary.tool.ActivityTool;
import com.xyxsbj.mylibrary.tool.ETTool;
import com.xyxsbj.mylibrary.tool.FileUtil;
import com.xyxsbj.mylibrary.tool.LogTool;
import com.xyxsbj.mylibrary.tool.StringTool;
import com.xyxsbj.mylibrary.tool.ToastTool;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * 包名: com.unis.sxzcl.ui.login
 * 类名: LoginFragment
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/11/12 11:16
 * 更新人:
 * 更新时间: 2020/11/12 11:16
 * 更新说明:
 * 版本号: 1.0
 */
public class LoginFragment extends BaseFragment<FragmentLoginBinding> {

    private String mName;
    private String mPassword;
    private VersionCheckTool mVersionCheckTool;
    private String mRegistrationID;
    private BottomMultipleListDialog mLogListDialog;
    private String captchaKey;

    @Override
    protected FragmentLoginBinding getViewBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentLoginBinding.inflate(inflater, container, false);
    }

    @Override
    protected void init() {
        setStatusBarWhite(false);

        mRegistrationID = JPushInterface.getRegistrationID(getContext());
        LogTool.i("极光推送registrationID:" + mRegistrationID);

        mBinding.btnLogin.setOnClickListener(v -> {
            //登录
            verifyCode();
        });
        mBinding.etName.addTextChangedListener(new ErrorTextWatcher(mBinding.layoutName));
        mBinding.etPassword.addTextChangedListener(new ErrorTextWatcher(mBinding.layoutPassword));
        mBinding.etCode.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                verifyCode();
            }
            return false;
        });

        mBinding.tvLog.setOnClickListener(v -> {
            // 展示登录历史
            showLogDialog(null);
            new LoginLogListTask(this::showLoginLogs).execute();
        });

        mBinding.ivCode.setOnClickListener(v -> {
            getCaptcha();
        });
    }

    @Override
    protected void onFirstShow() {

        // 版本检查
        mVersionCheckTool = new VersionCheckTool(getContext())
                .setUpdateCallback((data, newest) -> {
                    if (!newest)// 不是新版本时启动对话框并下载
                        mVersionCheckTool.showUpdateDialog(data.get(0));
                })
                .setError(error -> {
                })
                .start();

        // 展示最新登录过的账号密码
        new LoginLogFirstTask(this::showLogFirst).execute();

        // 获取验证码
        getCaptcha();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mVersionCheckTool != null)
            mVersionCheckTool.destroy();
        mVersionCheckTool = null;
    }

    /**
     * 获取验证码
     */
    private void getCaptcha() {
        captchaKey = null;
        showProgress("正在获取验证码...");
        UserModel.get().getCaptcha(new DataCallback<CaptchaBean>() {
            @Override
            public void onSuccess(CaptchaBean data) {
                FileUtil.decodeBase64Bitmap(data.image, bitmap -> {
                    hideProgress();
                    if (bitmap == null) {
                        mBinding.layoutCode.setVisibility(View.GONE);
                        return;
                    }
                    mBinding.layoutCode.setVisibility(View.VISIBLE);
                    captchaKey = data.key;
                    mBinding.ivCode.setImageBitmap(bitmap);
                });
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                hideProgress();
                mBinding.layoutCode.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 验证码校验
     */
    private void verifyCode() {
        if (StringTool.isEmpty(captchaKey)) {
            // 无验证码时直接登录
            login();
            return;
        }
        String code = ETTool.getData(mBinding.etCode);
        if (StringTool.isEmpty(code)) {
            ToastTool.showLong("请输入验证码");
            return;
        }
        showProgress("正在校验验证码...");
        UserModel.get().verifyCode(captchaKey, code, new DataCallback<String>() {
            @Override
            public void onSuccess(String data) {
                login();
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                hideProgress();
            }
        });
    }


    /**
     * 登录
     */
    private void login() {
        if (!verify()) return;

        showProgress("正在登陆...", false);
        UserModel.get().login(mName, mPassword, mRegistrationID, new DataCallback<LoginBean>() {
            @Override
            public void onSuccess(LoginBean data) {

                if (!isActive()) return;
                hideProgress();

                // 保存登录历史到数据库
                LoginLog loginLog = new LoginLog();
                loginLog.name = mName;
                loginLog.pwd = mPassword;
                new LoginLogSaveTask().execute(loginLog);

                // 跳转首页
                ActivityTool.startActivity(getContext(), MainActivity.class);
                finish();

            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (!isActive()) return;
                hideProgress();
            }
        });
    }

    /**
     * 输入校验
     */
    private boolean verify() {

        mName = ETTool.getData(mBinding.etName);
        if (StringTool.isEmpty(mName)) {
            mBinding.layoutName.setError("账号不得为空");
            return false;
        }
        mPassword = ETTool.getData(mBinding.etPassword);
        if (StringTool.isEmpty(mPassword)) {
            mBinding.layoutPassword.setError("密码不得为空");
            return false;
        }
        return true;
    }

    /**
     * 显示第一条登录信息
     */
    public void showLogFirst(LogFirst loginLog) {
        if (!isActive()) return;
        if (loginLog == null) return;
        mBinding.etName.setText(loginLog.name);
        mBinding.etPassword.setText(loginLog.pwd);
    }

    /**
     * 显示登陆历史对话框
     */
    public void showLoginLogs(List<LoginLog> logList) {
        if (!isActive()) return;
        if (logList == null || logList.isEmpty()) {
            ToastTool.showLong("没有登录历史");
            return;
        }
        // 转换列表信息
        List<MultipleBean> list = new ArrayList<>();
        for (LoginLog log : logList) {
            list.add(new MultipleBean(log.name, log.pwd));
        }
        // 显示登录日志对话框
        showLogDialog(list);
    }

    /**
     * 显示登录日志对话框
     */
    private void showLogDialog(List<MultipleBean> list) {
        if (mLogListDialog == null) {
            // 创建对话框
            mLogListDialog = new BottomMultipleListDialog(getContext())
                    .setTitle("切换账号")
                    .setEnterText("清空登录历史")
                    .hideTwoList()
                    .hideThreeList()
                    .setOneCallback((v1, b1) -> {
                        // 选择账号进行回显
                        mBinding.etName.setText(b1.getName());
                        mBinding.etPassword.setText(b1.getExtras());
                        return true;
                    })
                    .setEnterCallback((v12, b1, b2, b3) -> {
                        // 清理历史
                        new LoginLogDelAllTask().execute();
                        return true;
                    });
        }
        // 赋值列表 并显示
        mLogListDialog.setListOne(list)
                .show();
    }

    public class ErrorTextWatcher implements TextWatcher {

        private TextInputLayout mTextInputLayout;

        public ErrorTextWatcher(TextInputLayout textInputLayout) {
            mTextInputLayout = textInputLayout;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (mTextInputLayout != null) mTextInputLayout.setError(null);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

}
