package com.yzx.escreen.activity

import android.app.Activity
import android.view.View
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_FAIL
import com.yzx.escreen.MainActivity
import com.yzx.escreen.R
import com.yzx.escreen.activity.base.BaseActivity
import com.yzx.escreen.config.Config
import com.yzx.escreen.model.BaseUser
import com.yzx.escreen.model.TabEntity
import com.yzx.escreen.model.User
import com.yzx.escreen.presenter.LoginPresenter
import com.yzx.escreen.presenter.LoginView
import com.yzx.escreen.utils.hideNavigationBar
import com.yzx.escreen.utils.setSrc
import kotlinx.android.synthetic.main.activity_login.accountEdit
import kotlinx.android.synthetic.main.activity_login.accountLayout
import kotlinx.android.synthetic.main.activity_login.img1
import kotlinx.android.synthetic.main.activity_login.img2
import kotlinx.android.synthetic.main.activity_login.loginBtn
import kotlinx.android.synthetic.main.activity_login.pswCheckbox
import kotlinx.android.synthetic.main.activity_login.pswEdit
import kotlinx.android.synthetic.main.activity_login.qrCodeImg
import kotlinx.android.synthetic.main.activity_login.qrLayout
import kotlinx.android.synthetic.main.activity_login.qrRefresh
import kotlinx.android.synthetic.main.activity_login.tabLayout
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class LoginActivity : BaseActivity<LoginPresenter>(), LoginView {

    companion object {
        fun active(act: Activity) {
            act.startActivity<LoginActivity>()
        }
    }

    private var mTicket = ""
    private var isPageShow = true
    private var qrLoading = false

    override val inflateId: Int
        get() = R.layout.activity_login

    override fun initView() {
        val tabData = arrayListOf<CustomTabEntity>()
        tabData.add(TabEntity("账号密码登录", 0, 0))
        tabData.add(TabEntity("微信扫码登录", 0, 0))
        tabLayout.setTabData(tabData)
        tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                if (position == 0) {
                    qrLayout.visibility = View.GONE
                    accountLayout.visibility = View.VISIBLE
                    SPUtils.getInstance().put("last_login_tab_index",0)
                } else {
                    qrLayout.visibility = View.VISIBLE
                    accountLayout.visibility = View.GONE
                    SPUtils.getInstance().put("last_login_tab_index",1)
                    KeyboardUtils.hideSoftInput(this@LoginActivity)
                    qrLoading = true
                    mPresenter?.getWXQrCode()
                }
            }

            override fun onTabReselect(position: Int) {

            }
        })
        val lastLoginTabIndex = SPUtils.getInstance().getInt("last_login_tab_index",0)
        if(lastLoginTabIndex == 1){
            qrLayout.visibility = View.VISIBLE
            accountLayout.visibility = View.GONE
            tabLayout.currentTab = 1
            qrLoading = true
            mPresenter?.getWXQrCode()
        }
        loginBtn.setOnClickListener {
            this.doLogin()
        }
        val isSavePsw = SPUtils.getInstance().getBoolean("is_save_psw", false)
        if (isSavePsw) {
            pswCheckbox.isChecked = true
            val phone = SPUtils.getInstance().getString("login_save_phone", "")
            val psw = SPUtils.getInstance().getString("login_save_psw", "")
            accountEdit.setText(phone)
            pswEdit.setText(psw)
        } else {
            pswCheckbox.isChecked = false
        }

        var env = Config.getEvn()
        img1.setSrc(env.LOGO)
        img2.setSrc(env.APP_NAME)
        qrRefresh.setOnClickListener {
            if(qrLoading){
                toast("刷新中，请稍后")
                return@setOnClickListener
            }
            qrLoading = true
            mPresenter?.getWXQrCode(true)
        }
    }

    private fun doLogin() {
        val phone = accountEdit.text.toString()
        val psw = pswEdit.text.toString()
        if (phone.isBlank()) {
            showDialogToast("请输入账号", icon = QMUITipDialog.Builder.ICON_TYPE_FAIL)
            return
        }
        if (psw.isBlank()) {
            showDialogToast("请输入密码", icon = QMUITipDialog.Builder.ICON_TYPE_FAIL)
            return
        }
        showLoading("登录中...")
        if(pswCheckbox.isChecked){
            SPUtils.getInstance().put("is_save_psw",true)
            SPUtils.getInstance().put("login_save_phone",phone)
            SPUtils.getInstance().put("login_save_psw",psw)
        }else{
            SPUtils.getInstance().put("is_save_psw",false)
            SPUtils.getInstance().remove("login_save_phone")
            SPUtils.getInstance().remove("login_save_psw")
        }
        mPresenter?.login(phone, psw)
    }

    override fun initData() {

    }

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

    override fun onLoginSuccess(user: BaseUser, list: MutableList<BaseUser>) {
        val teaList = list.filter {
            return@filter it.type == 0
        }
        when {
            teaList.isEmpty() -> {

                if(user.type == 0){
                    mPresenter?.switchUser(user.token, user.user_id, user.school_id)
                }else{
                    hideLoading()
                    this.showDialogToast("无登录权限", icon = ICON_TYPE_FAIL)
                }
            }

            teaList.size == 1 -> {  //多个角色
                val item = teaList[0]
                mPresenter?.switchUser(user.token, item.user_id, item.unit_id)
            }

            else -> {
                mPresenter?.getUserRoleList(user.token)
            }
        }
    }

    override fun onLoginError(msg: String) {
        hideLoading()
        showDialogToast(msg, icon = ICON_TYPE_FAIL)
    }

    override fun onUserInfoSuccess(user: User) {
        hideLoading()
        startActivity<MainActivity>()
        finish()
    }

    override fun onWxQrCodeSuccess(imgUrl: String, ticket: String,refresh:Boolean) {
        qrLoading = false
        qrCodeImg.setSrc(imgUrl)
        mTicket = ticket
        mPresenter?.loginQuery(ticket)
        if(refresh){
            toast("刷新成功")
        }
    }

    override fun onWxQrCodeError(msg: String,refresh:Boolean) {
        qrLoading = false
        if(refresh){
            toast(msg.ifBlank {
                "刷新失败"
            })
        }
    }

    override fun onDestroy() {
        qrCodeImg?.apply {
            removeCallbacks(mRun)
        }
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        this.isPageShow = true
    }

    override fun onStop() {
        super.onStop()
        this.isPageShow = false
    }

    private var mBindDialog: QMUIDialog? = null
    private var mOverTimeDialog: QMUIDialog? = null

    private  var mRun = Runnable {
        if(isPageShow){
            mPresenter?.loginQuery(mTicket)
        }
    }

    override fun onLoginQuerySuccess(user: BaseUser, code: Int) {
        when (code) {
            0 -> {
                if (user.direct_login == 1) {
                    mPresenter?.getUserLoginInfo(user.token)
                } else {
                    mPresenter?.getUserRoleInfoByPhone(user.phone, user.tmp_token)
                }
            }

            451 -> {
                if (mBindDialog == null) {
                    mBindDialog = QMUIDialog.MessageDialogBuilder(this)
                        .setTitle("温馨提示")
                        .setMessage("您还未绑定微信公众，请绑定后再试！")
                        .addAction("知道了") { dialog, index ->
                            dialog.dismiss()
                        }
                        .create()
                    mBindDialog?.show()
                    mBindDialog?.hideNavigationBar()
                } else if (!mBindDialog!!.isShowing) {
                    mBindDialog?.show()
                }
                qrCodeImg.postDelayed(mRun, 1000)
            }

            452 -> {
                qrCodeImg.postDelayed(mRun, 1000)
            }

            else -> {
                if (mOverTimeDialog == null) {
                    mOverTimeDialog = QMUIDialog.MessageDialogBuilder(this)
                        .setTitle("温馨提示")
                        .setMessage("二维码已使用，请重新扫码！")
                        .addAction("知道了") { dialog, index ->
                            dialog.dismiss()
                        }
                        .create()
                    mOverTimeDialog!!.show()
                    mOverTimeDialog!!.hideNavigationBar()
                } else if (!mOverTimeDialog!!.isShowing) {
                    mOverTimeDialog?.show()
                }
                mPresenter?.getWXQrCode()
            }
        }
    }

    override fun onUserListSuccess(list: MutableList<BaseUser>, token: String) {
        LogUtils.d("onUserListSuccess", list)
        hideLoading()
        val builder = QMUIDialog.MenuDialogBuilder(this)
        list.forEach {
            builder.addItem(
                it.unit_name
            ) { dialog, which ->
                LogUtils.d("itemClick", which)
                val item = list[which]
                showLoading("登录中...")
                if(item.school_id>0){
                    mPresenter?.switchUnit(item.user_id, item.unit_id,token)
                }else{
                    mPresenter?.switchUser(token, item.user_id, item.unit_id)
                }
            }
        }
        builder.show()
    }
}