package com.lukouguoji.module_base

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.coroutineScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.lukouguoji.module_base.adapter.bindAdapter
import com.lukouguoji.module_base.adapter.bindOnSelected
import com.lukouguoji.module_base.adapter.setEnable
import com.lukouguoji.module_base.adapter.setOnFocusChangeListener
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.interfaces.IOnFocusChangeListener
import com.lukouguoji.module_base.interfaces.IOnSpinnerSelected
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.ktx.logw
import com.lukouguoji.module_base.ktx.setTextAllCaps
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.service.viewModel.LoginViewModel
import com.lukouguoji.module_base.update.UpdateDialog
import com.lukouguoji.module_base.update.UploadUtil
import com.young.security.BCryptPasswordEncoder
import dev.utils.app.AppUtils
import dev.utils.app.ScreenUtils
import dev.utils.app.info.KeyValue
import dev.utils.app.share.SPUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.jessyan.autosize.internal.CustomAdapt

/**
 * ========== 开发调试开关 ==========
 * TODO: 正式发布前务必设置为 false
 */
private const val DEV_AUTO_LOGIN = false  // 自动登录开关

@Route(path = ARouterConstants.ACTIVITY_URL_LOGIN)
class LoginActivity : BaseActivity(),
    CustomAdapt {

    private lateinit var user: EditText
    private lateinit var pass: EditText
    private lateinit var loginButton: TextView
    private lateinit var viewModel: LoginViewModel

    private lateinit var tvPda: TextView
    private lateinit var tvTip: TextView
    private lateinit var spinner: Spinner
    private lateinit var spinnerUrl: Spinner
    private var updateDialog : UpdateDialog?=null

    private fun initView() {
        user = findViewById(R.id.inputUser)
        pass = findViewById(R.id.inputPass)
        loginButton = findViewById(R.id.loginButton)
        tvPda = findViewById(R.id.tv_pda)
        tvTip = findViewById(R.id.tv_tip)
        spinner = findViewById(R.id.spinner)
        spinnerUrl = findViewById(R.id.spinner_url)

        setTextAllCaps(user, true)

        setOnFocusChangeListener(user, object : IOnFocusChangeListener {
            override fun onFocusChange(hasFocus: Boolean) {
                if (!hasFocus) {
                    if (user.text.isNotEmpty()) {
                        viewModel.getUserRole(user.text.toString())
                    }
                }
            }
        })

        viewModel.userRoleBean.observe(this) {
            loge("获取")
            if (it == null) {
                tvTip.visibility = View.VISIBLE
                return@observe
            }
            tvTip.visibility = View.GONE
            loge("用户角色信息监听 ${it.roleTerm}")

            viewModel.roleTerm = it.roleTerm

            if (it.roleTerm == "0") {
                bindAdapter(
                    spinner,
                    listOf(KeyValue(it.getUserRoleName(), it.userRole))
                )
                setEnable(spinner, false)
                viewModel.userRole = it.userRole
            } else {
                bindAdapter(spinner, viewModel.dictList.value, "请选择角色")
                setEnable(spinner, true)
                viewModel.dictList.value?.indexOfFirst { b -> b.value == it.userRole }
                    ?.let { index ->
                        spinner.setSelection(index)
                    }
            }

            // ========== 开发调试：角色信息获取成功后自动登录 ==========
            // TODO: 正式发布前删除此代码块
            if (DEV_AUTO_LOGIN && user.text.toString() == "ADMIN") {
                loginButton.postDelayed({
                    val encodedPassword = "$2a$10$02ZpVb/bymrybmPE2Mu2C.O.JcMXTB..gkssaNn8q2EC.kUAfJP0S"
                    viewModel.login(user.text.toString(), encodedPassword)
                }, 200)  // 短暂延迟确保spinner更新完成
            }
        }
        bindOnSelected(spinner, object : IOnSpinnerSelected {
            override fun onSelected(position: Int) {
                if (viewModel.userRoleBean.value?.roleTerm != "0") {
                    viewModel.userRole = viewModel.dictList.value?.getOrNull(position)?.value ?: ""
                    loge("角色选中事件 ${viewModel.userRole}")
                }
            }
        })

        bindAdapter(spinnerUrl, viewModel.urlList)
        val recordUrl = SharedPreferenceUtil.getString(Constant.Share.ipAddress)
        if (recordUrl.isNotEmpty()) {
            val index = viewModel.urlList.indexOfFirst { it.value == recordUrl }
            if (index >= 0) {
                spinnerUrl.setSelection(index)
            }
        }

        bindOnSelected(spinnerUrl, object : IOnSpinnerSelected {
            override fun onSelected(position: Int) {
                viewModel.setBaseUrl(position)
                checkAppUpdate()
            }
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        checkAppUpdate()


        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
        viewModel.onCreated(this)
        initView()

        viewModel.loginLiveData.observe(this) {
            if (it == 1) {
                val screenWidth = ScreenUtils.getScreenWidth()
                val screenHeight = ScreenUtils.getScreenHeight()
                // 判断是否是平板
                // 平板是1280*800  pda是720*1280
                if (screenWidth.coerceAtLeast(screenHeight).toFloat() / screenWidth.coerceAtMost(
                        screenHeight
                    ).toFloat() == 1280f / 800f
                ) {
                    SPUtils.getPreference(this).put(Constant.Share.IS_PDA, false)
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_MAIN)
                        .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                        .navigation()
                } else {
                    SPUtils.getPreference(this).put(Constant.Share.IS_PDA, true)
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_PDA_ENTER)
                        .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                        .navigation()
                }

            } else if (it == 2) {
                Toast.makeText(this, "用户名密码错误！", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(this, "网络错误！", Toast.LENGTH_LONG).show()
            }
        }

        loginButton.setOnClickListener {
//            ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_MAIN)
//                .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()

            val encoder = BCryptPasswordEncoder()
            val hashPassword = encoder.encode(pass.text.toString())
            viewModel.login(user.text.toString(), hashPassword)
        }

        tvPda.setOnClickListener {
            ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_PDA_ENTER)
                .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                .navigation()
        }

        bindAdapter(spinner, viewModel.roleList, "请选择角色", R.layout.item_spinner_list_18sp)
        setEnable(spinner, false)

        // ========== 开发调试：自动登录 ==========
        // TODO: 正式发布前删除此行
        autoLoginForDev()
    }

    /**
     * 开发调试：自动登录
     * TODO: 正式发布前删除此方法或将 DEV_AUTO_LOGIN 设置为 false
     */
    private fun autoLoginForDev() {
        if (!DEV_AUTO_LOGIN) return

        // 延迟执行，确保UI初始化完成
        loginButton.postDelayed({
            // 设置用户名
            user.setText("ADMIN")

            // 手动触发获取角色信息
            // 角色信息获取成功后会在userRoleBean.observe中自动执行登录
            viewModel.getUserRole("ADMIN")
        }, 500)  // 延迟500ms确保ViewModel已初始化
    }


    private fun checkIsNeedLoginWithToken(){
        val token = SharedPreferenceUtil.getString(Constant.Share.token)
        if (token != "") {
            val isPda = SPUtils.getPreference(this).getBoolean(Constant.Share.IS_PDA, false)
            logw("自动登录")
            if (isPda) {
                ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_PDA_ENTER)
                    .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    .navigation()
            } else {
                ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_MAIN)
                    .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    .navigation()
            }
            return
        }
    }

    private fun checkAppUpdate(){
        val uploadUtil = UploadUtil()
        uploadUtil?.init(this)
        val versionCode = AppUtils.getAppVersionCode().toInt()
        lifecycle.coroutineScope.launch(Dispatchers.IO) {
            logw("checkAppUpdate: versionCode =$versionCode")
            uploadUtil?.getAppUpdate(versionCode){
                lifecycle.coroutineScope.launch {
                    if(it==null){
                        checkIsNeedLoginWithToken()
                    }else{
                        updateDialog = UpdateDialog(this@LoginActivity,it, uploadUtil)
                        updateDialog?.show()
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        updateDialog?.dismiss()
    }

    override fun isBaseOnWidth() = true

    override fun getSizeInDp(): Float {
        return if (ScreenUtils.isPortrait()) {
            400f
        } else {
            1152f
        }
    }

}
