package com.feasycom.feasybeacon.ui.splash

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.CountDownTimer
import android.text.SpannableString
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.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Button
import android.widget.CheckBox
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.feasycom.feasybeacon.R
import com.feasycom.feasybeacon.databinding.FragmentSplashBinding
import com.feasycom.feasybeacon.logic.utils.getBoolean
import com.feasycom.feasybeacon.logic.utils.putBoolean
import com.feasycom.feasybeacon.logic.utils.putInt
import com.feasycom.feasybeacon.logic.utils.putStr
import com.feasycom.feasybeacon.ui.about.AgreementActivity
import com.feasycom.feasybeacon.ui.base.BaseFragment
import com.feasycom.feasybeacon.ui.dialog.FirstDialogFragment
import com.feasycom.util.SharedPreferencesUtil.putBoolean

class SplashFragment : BaseFragment<FragmentSplashBinding>() {

    private lateinit var mFirstDialogFragment: FirstDialogFragment

    // 使用 ViewModel 来管理数据
    private val splashViewModel by viewModels<SplashViewModel>()

    // 获取 ViewBinding 对象的方法
    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?
    ) = FragmentSplashBinding.inflate(inflater, container, false)

    // 倒计时器对象，用于处理倒计时功能
    private val countDownTimer: CountDownTimer by lazy {
        object : CountDownTimer(5000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                // 更新倒计时文本
                binding.toMain.text = getString(R.string.countdown, millisUntilFinished / 1000)
            }

            override fun onFinish() {
                // 取消倒计时器并执行进入逻辑
                countDownTimer.cancel()
                firstIn()
            }
        }
    }

    // 初始化视图
    override fun initView() {
        // 使用 Glide 加载启动图片
        Glide.with(this).load(R.drawable.loading).into(binding.splashIv)
        // 启动倒计时器
        countDownTimer.start()
    }

    // 清除过滤器设置
    private fun clearFilter() {
        requireContext().putStr("device_BEACON_name", "")
        requireContext().putStr("device_SENSOR_name", "")
        requireContext().putStr("device_SETTING_name", "")
        requireContext().putStr("device_BATCH_name", "")
        requireContext().putInt("device_BEACON_rssi", -100)
        requireContext().putInt("device_SENSOR_rssi", -100)
        requireContext().putInt("device_SETTING_rssi", -100)
        requireContext().putInt("device_BATCH_rssi", -100)
    }

    // 初始化事件监听器
    override fun initEvent() {
        // 清除过滤器设置
        clearFilter()
        // 下载启动图片
        splashViewModel.downloadSplash("beacon")
        // 观察启动图片的 LiveData
        splashViewModel.mSplashLiveData.observe(this as LifecycleOwner) {
            val orNull = it.getOrNull()
            if (orNull != null) {
                // 使用 Glide 加载下载的启动图片
                Glide.with(requireActivity()).load(orNull).into(binding.splashIv)
            }
        }
        // 处理“toMain”按钮的点击事件
        binding.toMain.setOnClickListener {
            // 取消倒计时器
            countDownTimer.cancel()
            // 进入下一个界面
            firstIn()
        }
    }

    // 处理首次进入应用的逻辑
    private fun firstIn() {
        if (::mFirstDialogFragment.isInitialized)  return

        // 检查是否是首次进入应用
        val isFirstTime = requireContext().getBoolean("firstTime", false)
        mFirstDialogFragment = FirstDialogFragment().apply {
            onAgree = {
                requireContext().putBoolean("firstTime", true)
                dismiss()
                findNavController().navigate(R.id.action_splashFragment_to_beaconFragment)
            }
            onRefuse = { requireActivity().finish() }
        }

        if (!isFirstTime && !mFirstDialogFragment.isAdded) {
            // 显示用户协议对话框
            mFirstDialogFragment.show(requireActivity().supportFragmentManager, "firstTime")
        } else {
            // 导航到 Beacon 页面
            findNavController().navigate(R.id.action_splashFragment_to_beaconFragment)
        }
    }

    private fun showUserAgreementDialog() {
        // 创建对话框
        val dialog = Dialog(requireContext(), R.style.BaseDialogStyle)
        // 加载对话框视图
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.privacy_dialog, null)
//        val view = LayoutInflater.from(requireContext()).inflate(R.layout.first_dialog, null)
        // 获取对话框中的控件
        val mConfirmButton = view.findViewById<Button>(R.id.confirm_button)
        val mDisagreeButton = view.findViewById<Button>(R.id.disagree_button)
//        val btnIsCheckedCB = view.findViewById<CheckBox>(R.id.user_privacy_cb)

        // 取消按钮点击事件处理
        mDisagreeButton.setOnClickListener {
            dialog.dismiss()
            requireActivity().finish()
        }

        // 确定按钮点击事件处理
        mConfirmButton.setOnClickListener {
            // 将用户首次进入标志设置为 true
            requireContext().putBoolean("first", true)
            dialog.dismiss()
            // 导航到 BeaconFragment
            findNavController().navigate(R.id.action_splashFragment_to_beaconFragment)
        }

        // 用户协议点击事件处理
        val userAgreementClick = object : ClickableSpan() {
            override fun onClick(widget: View) {
                // 启动用户协议界面
                startActivityWithAgreementType(1)
            }
        }

        // 隐私协议点击事件处理
        val privacyAgreementClick = object : ClickableSpan() {
            override fun onClick(widget: View) {
                // 启动隐私协议界面
                startActivityWithAgreementType(2)
            }
        }

        // 创建用户协议 SpannableString
        val userSpan = createUserSpan(userAgreementClick)
        // 创建隐私协议 SpannableString
        val privacySpan = createPrivacySpan(privacyAgreementClick)

        // 创建显示的 SpannableStringBuilder
        val stringBuilder = createStringBuilder(userSpan, privacySpan)

        // 设置对话框内容
        setContentToDialog(view, stringBuilder)

//        // 设置确定按钮状态和点击监听
//        setConfirmButtonStateAndListener(mConfirmButton, btnIsCheckedCB)

        // 设置对话框属性并显示
        setDialogAttributesAndShow(dialog, view)
    }

    // 启动用户协议或隐私协议界面
    private fun startActivityWithAgreementType(type: Int) {
        val intent = Intent(requireContext(), AgreementActivity::class.java)
        intent.putExtra("type", type)
        requireContext().startActivity(intent)
    }

    // 创建用户协议 SpannableString
    private fun createUserSpan(clickableSpan: ClickableSpan): SpannableString {
        val userSpan = SpannableString(getString(R.string.userAgreement))
        userSpan.setSpan(clickableSpan, 0, userSpan.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        userSpan.setSpan(
            ForegroundColorSpan(Color.parseColor("#D1894A")),
            0,
            userSpan.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return userSpan
    }

    // 创建隐私协议 SpannableString
    private fun createPrivacySpan(clickableSpan: ClickableSpan): SpannableString {
        val privacySpan = SpannableString(getString(R.string.privacyAgreement))
        privacySpan.setSpan(clickableSpan, 0, privacySpan.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        privacySpan.setSpan(
            ForegroundColorSpan(Color.parseColor("#D1894A")),
            0,
            privacySpan.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return privacySpan
    }

    // 创建显示的 SpannableStringBuilder
    private fun createStringBuilder(userSpan: SpannableString, privacySpan: SpannableString): SpannableStringBuilder {
        return SpannableStringBuilder(getString(R.string.userAndPrivacyAgreementPrefix)).apply {
            append("《").append(userSpan).append("》")
            append(getString(R.string.and))
            append("《").append(privacySpan).append("》")
            append(getString(R.string.userAndPrivacyAgreementSuffix))
        }
    }

    // 设置对话框内容
    private fun setContentToDialog(view: View, stringBuilder: SpannableStringBuilder) {
        val contentTextView = view.findViewById<TextView>(R.id.contentTextView)
        contentTextView?.let {
            it.movementMethod = LinkMovementMethod.getInstance()
            it.text = stringBuilder
            it.highlightColor = ContextCompat.getColor(requireContext(), R.color.transparent)
        }
    }

//    // 设置确定按钮状态和点击监听
//    private fun setConfirmButtonStateAndListener(btnDialogConfirm: Button, btnIsCheckedCB: CheckBox) {
//        btnDialogConfirm.isEnabled = false
//        btnIsCheckedCB.setOnCheckedChangeListener { _, isChecked ->
//            btnDialogConfirm.isEnabled = isChecked
//            btnDialogConfirm.setTextColor(
//                if (isChecked) ContextCompat.getColor(requireContext(), R.color.red)
//                else ContextCompat.getColor(requireContext(), R.color.grey)
//            )
//        }
//    }

    // 设置对话框属性并显示
    private fun setDialogAttributesAndShow(dialog: Dialog, view: View) {
        dialog.setContentView(view)
        dialog.setCancelable(false)
        dialog.window?.apply {
            val lp = attributes
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT
            attributes = lp
        }
        dialog.show()
    }

    // 销毁 Fragment
    override fun onDestroy() {
        super.onDestroy()
        // 取消倒计时器以避免内存泄漏
        countDownTimer.cancel()
    }

}
