package com.ytpm.hydtw.activity

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.os.SystemClock
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Base64
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.PhoneUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.ytpm.hydtw.R
import com.ytpm.hydtw.dao.Config
import com.ytpm.hydtw.dao.UserInfo
import com.ytpm.hydtw.databinding.ActivityLoginBinding
import com.ytpm.hydtw.loading.GlobalLoading
import com.ytpm.hydtw.network.BaseRetrofit
import com.ytpm.hydtw.network.Callback2
import com.ytpm.hydtw.utils.GameNetworkUtils
import com.ytpm.hydtw.utils.UserInfoSpUtils
import com.ytpm.hydtw.utils.WechatLoginHelper
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

class LoginActivity : FragmentActivity(), WechatLoginHelper.WechatLoginListener {

    private val TAG: String = this::class.java.simpleName
    private var wechatLoginHelper: WechatLoginHelper? = null
    private lateinit var binding: ActivityLoginBinding
    private var progress = 0
    private var countdownTimer: CountDownTimer? = null
    private var isCheck = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
    }

    private fun getWxConfig() {

        BaseRetrofit.getInstance().apiService.configs.enqueue(object : Callback2<Config>() {
            override fun success(body: Config?) {
                SPUtils.getInstance().put("WxAppId", body?.appId)
                wechatLoginHelper = WechatLoginHelper.getInstance(this@LoginActivity)
                binding.loginBtnLl.visibility = View.VISIBLE
                wechatLoginHelper?.login(this@LoginActivity)
            }

            override fun fail(msg: String?) {
                ToastUtils
                    .make()
                    .setMode(ToastUtils.MODE.DARK)
                    .setGravity(Gravity.CENTER, 0, 0)
                    .setTopIcon(R.mipmap.icon_fail)
                    .setDurationIsLong(true)
                    .show(msg)
            }
        })
    }

    private fun initView() {

        val isfirst = SPUtils.getInstance().getBoolean("isFirst", true)

        if (isfirst) {
            binding.dialogYs.visibility = View.VISIBLE
        }

        binding.dialogYs.setOnClickListener { }

        binding.agree.setOnClickListener {
            SPUtils.getInstance().put("isFirst", false)
            binding.dialogYs.visibility = View.GONE
        }

        binding.cancel.setOnClickListener {
            finish()
        }

        val dc =
            "感谢您使用好运答题王APP，在您使用本软件过程中，我们可能会对您的部分个人信息进行收集、使用和共享。请您仔细阅读"
        val spannableText = SpannableStringBuilder(dc)

        val ts1 = "《服务协议》"
        val ts2 = "《隐私政策》"
        val ts3 =
            "，并确定完全了解我们对您个人信息的处理规则。如您同意《服务协议》与《隐私政策》，请点击“同意”开始使用好运答题王，我们会尽全力保护您的个人信息安全。"
        spannableText.append(ts1)
        spannableText.append("与")
        spannableText.append(ts2)
        spannableText.append(ts3)

        // 设置前景色
        val colorSpan = ForegroundColorSpan(Color.BLUE)
        spannableText.setSpan(
            colorSpan,
            56,
            62,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        // 设置前景色
        val colorSpan2 = ForegroundColorSpan(Color.BLUE)
        spannableText.setSpan(
            colorSpan2,
            63,
            69,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        // 设置点击事件
        val clickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                val intent = Intent(this@LoginActivity, WebActivity::class.java)
                intent.putExtra("title", "用户协议")
                intent.putExtra("index", 1)
                startActivity(intent)
            }
        }


        // 设置点击事件
        val clickableSpan1 = object : ClickableSpan() {
            override fun onClick(widget: View) {
                val intent = Intent(this@LoginActivity, WebActivity::class.java)
                intent.putExtra("title", "隐私政策")
                intent.putExtra("index", 0)
                startActivity(intent)
            }
        }

        spannableText.setSpan(
            clickableSpan,
            56,
            62,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        spannableText.setSpan(
            clickableSpan1,
            63,
            69,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        binding.loginTs.text = spannableText
        binding.loginTs.movementMethod = LinkMovementMethod.getInstance()

        binding.yszc.setOnClickListener {
            val intent = Intent(this@LoginActivity, WebActivity::class.java)
            intent.putExtra("title", "隐私政策")
            intent.putExtra("index", 0)
            startActivity(intent)
        }
        binding.yhxy.setOnClickListener {
            val intent = Intent(this@LoginActivity, WebActivity::class.java)
            intent.putExtra("title", "用户协议")
            intent.putExtra("index", 1)
            startActivity(intent)
        }

        binding.loginBtnLl.visibility = View.GONE

        binding.activityLoginCheckBox.isChecked = true

        binding.activityLoginCheckBox.setOnCheckedChangeListener { _, isChecked ->
            isCheck = isChecked
        }

        val token = SPUtils.getInstance().getString("token")
        if (token.isNullOrEmpty()) {
            binding.loginBtnLl.visibility = View.VISIBLE
            binding.progressLl.visibility = View.GONE
        } else {
            binding.loginBtnLl.visibility = View.GONE
            binding.progressLl.visibility = View.VISIBLE
            startCountdown(100000, 50)
        }

        binding.loginBtnLl.setOnClickListener {
            if (!isCheck) {
                Toast.makeText(it.context, "请阅读并同意用户协议和隐私政策", Toast.LENGTH_SHORT)
                    .show()
                return@setOnClickListener
            }

            getWxConfig()
        }
    }

    private fun startCountdown(millisInFuture: Long, countDownInterval: Long) {
        countdownTimer?.cancel() // 取消之前的倒计时

        countdownTimer = object : CountDownTimer(millisInFuture, countDownInterval) {
            override fun onTick(millisUntilFinished: Long) {
                progress++
                binding.activityLoginProgressTx.text = "$progress%"
                binding.activityLoginProgress.progress = progress
                if (progress >= 100) {
                    jump()
                }
            }

            override fun onFinish() {
            }
        }.start()
    }

    override fun onResume() {
        super.onResume()
        countdownTimer?.start()
//        jiema()
    }

    fun jiema() {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HS89i7hileTjC1fjOEQYBh5rLC8MikuYsWeL3iYOvFwlR2+DJPbvKUeh3xY+hDCeh7o3u8Hk22DA5Fa0PF+PmI/c3r7t7EPJcVMY+f7fFeC94qChOZqzzBbmBnLgNaIQmb6DQ9zvu7t+uAHyLyVTnTgy/DycwmQWMH0D6TXOgeqGdvPefYIPG4/qsOrdpwOPOwuRaEObjrDSTNRjrDbJzM5vqqjLbkhTIRCB2qjo3AYd64rOqgoujSMPsPNONQQ3kfGOdRk/izGk45Td6aVMiTVXOUdxUfZSyErLnUjYj+a/KWjniF2+PkGAURFCVwYVdIV+oA5hWApyX9canZU0t2SmQi5l06jTzd2utM3qBDZaXNZAxg5/6OHOaJ1iPM60FOZ0moN0G690Tni9Fg+TQ+wl5MCxaWEmqboYG57qM3WiOYxv2qNh8jjBXth/ll2emN9/MYpFKv60NqF9yUZm4SbcF1zg9wqQwr+ZBQbiHBCrqKHuozmpzQwNawC03IDSeh3psgNvqsxg9hPLWEk9MCb2ASG8d5jof5f91mK66UlRHOtVGa/oS3kSKFabSUifqtySwz/5lyvefVv/pUXbcWK8FgHostCDNDedEjx67F8dGN+q96qUSHxolOdT2m6mp8aBi0HCbfkK1R32wjfLF00rP3jjNF7lVCQqxFRLo6+1lj4EDuC6EUNyO52DzucAFabOV+PjPn8s9XZNHliYtsmddTFMtLOZBiOSFlICrXOBE7iCds7hjoO7aTKWJBbG5y0g/m/NKQUAWd4lDvuOBxvXFLIcytdtwrG1r4TG/J4hWXFrMkNHmesrydvJvLkI/oVpZZwfRGs+29VK769mjGseM/Q6JeVWOUofw9tC4sLjg7qlhCqo3i2QdS9AnTPe5a+F8mSv2XuMWIa13I7Tgzqap"
        val ddfdf = decryptAES(ddd, "1234567890123456", "IM['KJK'XCK[=Xil")
        LogUtils.e("======dfdfdf=====${ddfdf}")
    }

    // 假设已知密钥和IV（需替换为真实值）
    fun decryptAES(encryptedBase64: String, key: String, iv: String): String {
        val encryptedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT)
        val secretKey = SecretKeySpec(key.toByteArray(), "AES")
        val ivSpec = IvParameterSpec(iv.toByteArray())
        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec)
        val decryptedBytes = cipher.doFinal(encryptedBytes)
        return String(decryptedBytes)
    }

    override fun onDestroy() {
        super.onDestroy()
        countdownTimer?.cancel()
    }

    override fun onStop() {
        super.onStop()
        countdownTimer?.cancel()
    }


    private fun jump() {
        countdownTimer?.cancel() // 取消之前的倒计时
        val intent = Intent(this@LoginActivity, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    override fun onLoginSuccess(code: String?) {
        LogUtils.e("dfdfdfdf${code}")
        startLogin(code)
    }

    override fun onLoginFailed(errorMsg: String?) {
        ToastUtils.showShort(errorMsg)
    }

    private fun startLogin(code: String?) {
        GlobalLoading.getInstance().show(this)

        val ip = NetworkUtils.getIPAddress(true)
        val operatorName = PhoneUtils.getSimOperatorName()
        val model = DeviceUtils.getModel()

        val map = HashMap<String, Any>()
        map["alias"] = Build.ID
        map["brand"] = Build.BRAND
        map["ipLocation"] = GameNetworkUtils(this).getMobileIpAddress().toString()
        map["ipOperator"] = operatorName
        map["loginIp"] = ip
        map["model"] = model
        map["wxCode"] = code!!

        val requestBody = BaseRetrofit.getRequestBodyByMapToJson(map)

        BaseRetrofit.getInstance().apiService.login(requestBody)
            .enqueue(object : Callback2<UserInfo>() {
                override fun success(body: UserInfo?) {

                    if (body != null) {
                        UserInfoSpUtils().putUserInfo(body)
                    }

                    startLoading()
                }

                override fun fail(msg: String?) {
                    ToastUtils
                        .make()
                        .setMode(ToastUtils.MODE.DARK)
                        .setGravity(Gravity.CENTER, 0, 0)
                        .setTopIcon(R.mipmap.icon_fail)
                        .setDurationIsLong(true)
                        .show(msg)
                }
            })
    }


    private fun startLoading() {
        binding.loginBtnLl.visibility = View.GONE
        binding.progressLl.visibility = View.VISIBLE
        startCountdown(100000, 50)
    }

    fun simulateClick(view: View) {
        val downTime = SystemClock.uptimeMillis()
        val eventTime = SystemClock.uptimeMillis() + 100
        val x = view.x + view.width / 2f
        val y = view.y + view.height / 2f

        // 构建触摸事件
        val downEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y, 0)
        val upEvent =
            MotionEvent.obtain(downTime + 100, eventTime + 100, MotionEvent.ACTION_UP, x, y, 0)

        // 分发事件
        view.dispatchTouchEvent(downEvent)
        view.dispatchTouchEvent(upEvent)

        // 回收事件
        downEvent.recycle()
        upEvent.recycle()
    }

}
