package cn.muchinfo.rma.view.base.login

import android.content.Intent
import android.os.Bundle
import android.text.InputType.*
import android.view.Gravity
import android.widget.EditText
import cn.muchinfo.rma.R
import cn.muchinfo.rma.business.commodity.CommodityManager
import cn.muchinfo.rma.business.future.FutureManager
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.netManage.base.InteractiveException
import cn.muchinfo.rma.view.MainActivity
import cn.muchinfo.rma.view.MyApplication
import cn.muchinfo.rma.view.autoWidget.autoSize
import cn.muchinfo.rma.view.autoWidget.textColorInt
import cn.muchinfo.rma.view.autoWidget.textSizeAuto
import cn.muchinfo.rma.view.base.BaseActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import mtp.polymer.com.autowidget.dialog.createLoadingDialog
import mtp.polymer.com.autowidget.utils.TaskUiModel
import mtp.polymer.com.autowidget.utils.bindTaskStatus
import org.jetbrains.anko.*

class LoginActivity : BaseActivity<LoginViewModel>() {
    private var loginCodeEditText: EditText? = null
    private var loginPwdEditText: EditText? = null
    private val dialog by lazy { createLoadingDialog(hintStr = "登录中...") }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        buildView()
    }

    private fun buildView() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this)

        dialog.bindTaskStatus(context = this, taskUiModelData = viewModel.loadingDialogStatus)

        verticalLayout {

            imageView {
                imageResource = R.mipmap.login_top
            }.lparams(matchParent, autoSize(507))

            imageView {
                imageResource = R.mipmap.login_logo
            }.lparams(autoSize(306), autoSize(306)) {
                gravity = Gravity.CENTER_HORIZONTAL
                topMargin = -autoSize(150)
            }

            // 登录账号
            linearLayout {
                gravity = Gravity.CENTER_VERTICAL

                imageView {
                    imageResource = R.mipmap.login_code
                }.lparams(autoSize(43), autoSize(43))

                editText {
                    setText(SPUtils.getInstance().getString("login"))
                    loginCodeEditText = this
                    hint = "手机号码/登录账号"
                    background = null
                    textSizeAuto = 34
                }.lparams(matchParent, wrapContent) {
                    leftMargin = autoSize(53)
                }

            }.lparams(matchParent, autoSize(100)) {
                setMargins(autoSize(108), autoSize(60), autoSize(108), 0)
            }

            view {
                backgroundColorResource = R.color.rma_blue_color
            }.lparams(matchParent, autoSize(1)) {
                leftMargin = autoSize(108)
                rightMargin = autoSize(108)
            }

            // 密码
            linearLayout {
                gravity = Gravity.CENTER_VERTICAL

                imageView {
                    imageResource = R.mipmap.login_pwd
                }.lparams(autoSize(43), autoSize(43))

                editText {
                    setText(SPUtils.getInstance().getString("psw"))
                    loginPwdEditText = this
                    hint = "登录密码"
                    background = null
                    textSizeAuto = 34
                    inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD

                }.lparams(matchParent, wrapContent) {
                    leftMargin = autoSize(53)
                }

            }.lparams(matchParent, autoSize(100)) {
                setMargins(autoSize(108), autoSize(60), autoSize(108), 0)
            }

            view {
                backgroundColor = R.color.rma_blue_color
            }.lparams(matchParent, autoSize(1)) {
                leftMargin = autoSize(108)
                rightMargin = autoSize(108)
            }

            button {
                gravity = Gravity.CENTER_HORIZONTAL
                text = "登录"
                textSizeAuto = 40
                textColorInt = R.color.white
                backgroundResource = R.mipmap.login_btn
            }.lparams(autoSize(721), autoSize(143)) {
                gravity = Gravity.CENTER_HORIZONTAL
                topMargin = autoSize(85)
            }.onClick {
                // 开始登录
                login()
            }

            linearLayout {
                button {
                    text = "注册账号"
                    textSizeAuto = 31
                    textColorInt = R.color.rma_gray_color
                    background = null
                }

                view {
                    backgroundColor = R.color.rma_hint_text_color_ccc
                }.lparams(autoSize(1), autoSize(43)) {
                    gravity = Gravity.CENTER_VERTICAL
                    leftMargin = autoSize(65)
                }

                button {
                    text = "忘记密码？"
                    textSizeAuto = 31
                    textColorInt = R.color.rma_gray_color
                    background = null
                }.lparams() {
                    leftMargin = autoSize(65)
                }
            }.lparams(wrapContent, wrapContent) {
                gravity = Gravity.CENTER_HORIZONTAL
                topMargin = autoSize(34)
            }
        }
    }

    private fun checkInput(): Boolean {
        if (loginCodeEditText!!.text.isEmpty()) {
            ToastUtils.showLong("请输入手机号码或登录账号")
            return false
        }
        if (loginPwdEditText!!.text.isEmpty()) {
            ToastUtils.showLong("请输入登录密码")
            return false
        }

        return true
    }

    private fun login() {
        if (!checkInput())
            return

        viewModel.loadingDialogStatus.value = TaskUiModel.inFlight()
        SPUtils.getInstance().put("login", loginCodeEditText!!.text.toString().trim())
        SPUtils.getInstance().put("psw", loginPwdEditText!!.text.toString())
        viewModel.login(
            code = loginCodeEditText!!.text.toString().trim(),
            password = loginPwdEditText!!.text.toString()
        ) { isCompleted, err ->
            GlobalScope.launch(Dispatchers.Main) {
                if (!isCompleted) {
                    viewModel.loadingDialogStatus.value =
                        TaskUiModel.failed(InteractiveException(GlobalDataCollection.instance?.getErrorString(err?.message ?: "") ?: "") )
                    return@launch
                }
                viewModel.loginQuery { isCompleted, err ->
//                    run {
//
//                    }
                    if (!isCompleted) {
                        viewModel.loadingDialogStatus.value =
                            TaskUiModel.failed(
                                InteractiveException(
                                    GlobalDataCollection.instance
                                        ?.getErrorString(err?.message ?: "") ?: ""
                                )
                            )
                        return@loginQuery
                    }
                    MyApplication.getInstance()?.futureManager?.queryGoodsList { isCompleted, err ->
                        viewModel.loadingDialogStatus.value = TaskUiModel.success(msg = "登录成功")
                        goHomePage()
                    }
                }
            }
        }
    }

    private fun goHomePage() {
        val intent = Intent()
        intent.setClass(this, MainActivity::class.java)
        ActivityUtils.startActivity(intent)
        finish()
    }
}