package com.bc_chat.account

import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.account.contract.LoginContract
import com.bc_chat.account.databinding.ActivityLoginBinding
import com.bc_chat.account.presenter.LoginPresenter
import com.bc_chat.bc_base.WebViewActivity
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.utils.StringUtils
import com.zhaohaoting.framework.abs.BaseNoActionBarActivity
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.Preferences
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.Utils
import kotlinx.android.synthetic.main.activity_login.*
import java.lang.Exception

/**
 * author：Created by zhaohaoting on 2019/2/20
 * email：526309416@qq.com
 * desc：登录
 */
@Route(path = RouteConfig.LOGIN_ACTIVITY)
class LoginActivity : BaseNoActionBarActivity<LoginPresenter>(), View.OnClickListener, LoginContract.View {

    private val binding by lazy {
        rootDataBinding as ActivityLoginBinding
    }
    private val handler = Handler(Looper.getMainLooper())

    override fun initPresenter(): LoginPresenter = LoginPresenter(this)

    override fun onInit() {
        setLightMode(resources.getColor(R.color.white), true, false)
        binding.onClickEvent = this
        val protocol = tv_protocol.text
        StringUtils.protocol(this, protocol, tv_protocol) {
            presenter.loadWebPage(Const.WebPageType.USER_PROTOCOL)
        }
        if (Const.Action.NEED_LOGIN.equals(intent.getStringExtra("action"))) {
            CustomDialog.Builder(this)
                    .setMessage("您的帐号在别的设备上登录，请妥善保管好自己的密码！")
                    .setPositiveButton("确定", null)
                    .create().show()
        }
        binding.etAccount.setText(Preferences.getString(Const.LAST_LOGIN_PHONE, ""))
    }

    override fun showLoading(vararg task: Any?) {
        super.showLoading(task)
        binding.btnLogin.isEnabled = false
    }

    override fun loginFailure(exception: Exception?) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            binding.btnLogin.isEnabled = true
            dismissLoading(null)
        } else {
            handler.post {
                binding.btnLogin.isEnabled = true
                dismissLoading(null)
            }
        }
    }

    override fun loginSuccess(userId: String?) {
        handler.post {
            binding.btnLogin.isEnabled = true
            Preferences.saveString(Const.LAST_LOGIN_USER_ID, userId)
            Preferences.saveString(Const.LAST_LOGIN_PHONE, binding.etAccount.text.toString())
            dismissLoading(null)
            ARouter.getInstance().build(RouteConfig.MAIN_ACTIVITY).navigation()
            finish()
        }
    }

    override fun loadWebPageSuccess(content: String) {
        WebViewActivity.startActivity(this, content, "用户协议", 1)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_login -> {
                val phone = binding.etAccount.text.toString().trim()
                val password = binding.etPassword.text.toString().trim()
                when {
                    phone.isNullOrEmpty() -> {
                        ToastUtils.show("请输入账号")
                        return
                    }
                    !Utils.isSimplePasswrod(password) -> {
                        ToastUtils.show("输入的密码不能少于六位")
                        return
                    }
                }
                presenter.login(phone, password)
            }
            R.id.tv_forget_password -> ARouter.getInstance().build(RouteConfig.FORGET_PASSWORD_ACTIVITY).navigation(this, FORPAD)
            R.id.tv_register -> ARouter.getInstance().build(RouteConfig.REGISTER_ACTIVITY).navigation(this, REGISTER)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return@onActivityResult
        when (requestCode) {
            REGISTER -> finish()
            FORPAD -> ToastUtils.show("密码修改成功,请重新登录")
        }
    }

    companion object {
        const val FORPAD = 1
        const val REGISTER = 2
        const val NEED_LOGIN = 3
        const val ACTION_EXIT_LOGIN = "exit_login"
        const val ACTION_NEED_LOGIN = "need_login"
        const val ACTION_LOCK_LOGIN = "lock_login"

        fun startActivity(activity: Activity) {
            val intent = Intent(activity, LoginActivity::class.java)
            activity.startActivity(intent)
        }

        fun start(activity: Activity, type: String) {
            val intent = Intent(activity, LoginActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            intent.action = type
            activity.startActivity(intent)
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_login
    }
}
