package com.doverfuelingsolutions.issp.view

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.SystemApi
import com.doverfuelingsolutions.issp.data.GlobalData
import com.doverfuelingsolutions.issp.databinding.ActivityLoginBinding
import com.doverfuelingsolutions.issp.utils.PermissionUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class LoginActivity : AppCompatActivity(),
    View.OnClickListener {

    companion object {
        fun start(context: Context) {
            Intent(context, LoginActivity::class.java).let { context.startActivity(it) }
        }
    }

    private val loginViewModel: LoginViewModel by viewModels()
    private val binding: ActivityLoginBinding by lazy { DataBindingUtil.setContentView(this, R.layout.activity_login) }
    private val snackbar: Snackbar by lazy {
        Snackbar.make(binding.loginForm, "", 4000)
            .apply { anchorView = binding.loginForm }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.lifecycleOwner = this
        binding.loginViewModel = loginViewModel
        binding.buttonLogin.setOnClickListener(this)
        binding.buttonPreference.setOnClickListener(this)

        PermissionUtil.requestPermissions(this)

        if (GlobalData.isLogin) {
            startMain()
        } else if (!loginViewModel.accountName.value.isNullOrBlank() && !loginViewModel.password.value.isNullOrBlank()) {
            submit()
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.buttonLogin -> submit()
            binding.buttonPreference -> PreferenceActivity.start(this)
        }
    }

    override fun onBackPressed() {
        if (loginViewModel.submitting.value == false) super.onBackPressed()
    }

    private fun submit() {
        if (loginViewModel.submitting.value == true) return

        lifecycleScope.launch {
            loginViewModel.submitting.value = true
            val accountName = loginViewModel.accountName.value
            val password = loginViewModel.password.value
            when {
                accountName.isNullOrBlank() || password.isNullOrBlank() -> snackbar.setText(R.string.input_not_right).show()
                else -> {
                    val result = SystemApi.login(accountName, password)
                    if (!result.success) snackbar.setText(StringUtil.get(R.string.login_fail_reason, result.message)).show()
                    else {
                        GlobalData.isLogin = true
                        // 并发
                        val deferredPhone = async { SystemApi.sessionInfo() }
                        val deferredLogo = async { SystemApi.stationLogo() }
                        val deferredPayment = async { SystemApi.paymentParam() }
                        // 油站号码
                        val resultPhone = deferredPhone.await()
                        if (resultPhone.success && resultPhone.data?.phoneNumber?.isBlank() == false) {
                            DFSLog.d("station phone: ${resultPhone.data.phoneNumber}")
                            GlobalData.stationTel.set(resultPhone.data.phoneNumber)
                        }
                        // 油站 LOGO
                        val resultLogo = deferredLogo.await()
                        if (resultLogo.success && resultLogo.data != null) {
                            DFSLog.d("station logo file: ${resultLogo.data}")
                            GlobalData.stationLogoFileName.set(resultLogo.data)
                        }
                        // 支付参数
                        val resultPayment = deferredPayment.await()
                        if (resultPayment.success && resultPayment.data != null) {
                            GlobalData.paymentId.set(resultPayment.data.PaymentId)
                            GlobalData.paymentName.set(resultPayment.data.DispalyName)
                        }

                        startMain()
                    }
                }
            }
            loginViewModel.submitting.value = false
        }
    }

    private fun startMain() {
        MainActivity.start(this@LoginActivity)
        finish()
    }

    class LoginViewModel : ViewModel() {
        val accountName = MutableLiveData(GlobalData.accountName.get())
        val password = MutableLiveData(GlobalData.password.get())
        val submitting = MutableLiveData(false)
    }
}