package com.base.scanqrclear.ui.main

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ConcatAdapter
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.base.BaseFragment
import com.base.scanqrclear.bean.FunctionUIBean
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_ADDRESS
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_CONTACT
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_EMAIL
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_EVENT
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_FACEBOOK
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_INSTAGRAM
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_MESSAGE
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_PAYPAL
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_SCAN
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_SPOTIFY
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_TELEPHONE
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_TEXT
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_WEBSITE
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_WHATSAPP
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_WIFI
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_X
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_YOUTUBE
import com.base.scanqrclear.bean.config.AdConfigBean.Companion.adsConfigBean
import com.base.scanqrclear.databinding.FragmentCreateBinding
import com.base.scanqrclear.luma.WeatherInterface
import com.base.scanqrclear.luma.WeatherUtils
import com.base.scanqrclear.qr.QrStyleActivity
import com.base.scanqrclear.ui.addressqr.AddressDialog.showAddressDialog
import com.base.scanqrclear.ui.concatadapt.AdAdapter
import com.base.scanqrclear.ui.contact.ContractActivity
import com.base.scanqrclear.ui.email.EmailActivity
import com.base.scanqrclear.ui.event.EventActivity
import com.base.scanqrclear.ui.facebookqr.FacebookDialog.showFacebookDialog
import com.base.scanqrclear.ui.insqr.InstagramDialog.showInstagramDialog
import com.base.scanqrclear.ui.message.MessageActivity
import com.base.scanqrclear.ui.paypalqr.PaypalDialog.showPaypalDialog
import com.base.scanqrclear.ui.scan.ScanOtherActivity
import com.base.scanqrclear.ui.spotifyqr.SpotifyDialog.showSpotifyDialog
import com.base.scanqrclear.ui.telephone.TelephoneActivity
import com.base.scanqrclear.ui.text.TextActivity
import com.base.scanqrclear.ui.website.WebsiteActivity
import com.base.scanqrclear.ui.whatsappqr.WhatsappDialog.showWhatsappDialog
import com.base.scanqrclear.ui.widget.guideview.Component
import com.base.scanqrclear.ui.widget.guideview.GuideBuilder
import com.base.scanqrclear.ui.widget.guideview.LottieComponent
import com.base.scanqrclear.ui.wifi.WifiActivity
import com.base.scanqrclear.ui.xqr.XDialog.showXDialog
import com.base.scanqrclear.ui.youtubeqr.YoutubeDialog.showYoutubeDialog
import com.base.scanqrclear.utils.AppPreferences
import com.base.scanqrclear.utils.BarUtils
import com.gyf.immersionbar.ktx.immersionBar
import kotlin.random.Random

class CreateFragment : BaseFragment<FragmentCreateBinding>(FragmentCreateBinding::inflate) {


    private val concatAdapter: ConcatAdapter = ConcatAdapter()

    private var functionRvAdapter1: FunctionRvAdapter? = null
    private var functionRvAdapter2: FunctionRvAdapter? = null
    private var headAdapter: HeadAdapter? = null

    private val functions1 by lazy(LazyThreadSafetyMode.NONE) {
        listOf(
            FunctionUIBean(KEY_SCAN, R.mipmap.h_scan, resources.getString(R.string.scan)),
            FunctionUIBean(KEY_WIFI, R.mipmap.h_wifi, resources.getString(R.string.wifi)),
            FunctionUIBean(KEY_TEXT, R.mipmap.h_text, resources.getString(R.string.text)),
            FunctionUIBean(KEY_EMAIL, R.mipmap.h_email, resources.getString(R.string.email)),
            FunctionUIBean(KEY_WEBSITE, R.mipmap.h_website, resources.getString(R.string.website)),
            FunctionUIBean(KEY_EVENT, R.mipmap.h_event, resources.getString(R.string.event)),
            FunctionUIBean(KEY_CONTACT, R.mipmap.h_contact, resources.getString(R.string.contact)),
//                FunctionUIBean(KEY_LOCATION, R.mipmap.h_loction, resources.getString(R.string.location)),
            FunctionUIBean(
                KEY_TELEPHONE,
                R.mipmap.h_telephone,
                resources.getString(R.string.telephone)
            ),
            FunctionUIBean(KEY_MESSAGE, R.mipmap.h_message, resources.getString(R.string.message)),
        )
    }

    private val functions2 by lazy(LazyThreadSafetyMode.NONE) {
        listOf(
            FunctionUIBean(KEY_YOUTUBE, R.mipmap.h_youtube, "Youtube"),
            FunctionUIBean(KEY_WHATSAPP, R.mipmap.h_whatsapp, "Whatsapp"),
            FunctionUIBean(KEY_FACEBOOK, R.mipmap.h_facebook, "Facebook"),
            FunctionUIBean(KEY_INSTAGRAM, R.mipmap.h_instagram, "Instagram"),
            FunctionUIBean(KEY_X, R.mipmap.h_x, "X"),
            FunctionUIBean(KEY_SPOTIFY, R.mipmap.h_spotify, "Spotify"),
            FunctionUIBean(KEY_PAYPAL, R.mipmap.h_paypal, "Paypal"),
            FunctionUIBean(KEY_ADDRESS, R.mipmap.h_address, resources.getString(R.string.address)),
        )
    }


    override fun initView() {
        super.initView()
        binding.space.layoutParams.height = BarUtils.getStatusBarHeight()
        // binding.ivVip.updatePadding(top = BarUtils.getStatusBarHeight())

        binding.rv.adapter = concatAdapter

        headAdapter = HeadAdapter(this).apply {
            concatAdapter.addAdapter(this)
            submitList(listOf(""))
        }

        functionRvAdapter1 = FunctionRvAdapter().apply {
            itemClick = ::itemClick
            concatAdapter.addAdapter(this)
            submitList(arrayListOf(functions1))
        }

        concatAdapter.addAdapter(AdAdapter().apply { submitList(listOf("")) })

        functionRvAdapter2 = FunctionRvAdapter().apply {
            tittle = resources.getString(R.string.other)
            itemClick = ::itemClick
            concatAdapter.addAdapter(this)
            submitList(arrayListOf(functions2))
        }

        if (adsConfigBean.homeShowNative) {
            AdsMgr.showNative(binding.flAd, R.layout.layout_admob_item)
        } else {
            binding.flAd.visibility = View.GONE
        }
    }

    private fun itemClick(key: String) {
        val activity = requireActivity() as MainActivity?
        activity?.let {
            if (adsConfigBean.functionInShowAd) {
                AdsMgr.showInsert(it, false, object : AdsShowCallBack() {
                    override fun close(where: Int) {
                        itemKeyClick(key)
                    }

                    override fun failed(where: Int) {
                        itemKeyClick(key)

                    }

                    override fun googleFailed(where: Int) {
                        itemKeyClick(key)
                    }
                })
            } else {
                itemKeyClick(key)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setWeather() {
        val weatherEntity = WeatherUtils.getWeatherEntity()
        val icon: Int
        var value = 22
        if (weatherEntity == null) {
            binding.tvWeather.visibility = View.GONE
        } else {
            val subBean = weatherEntity.list[0]
            val min = subBean.tempMin.toInt()
            val max = subBean.tempMax.toInt()
            if (min == max) {
                value = max
            }
            if (min < max) {
                value = Random.nextInt(min, max)
            }
            icon = when (WeatherUtils.getWeatherType(subBean.iconDay.toInt())) {
                "Sunny day" -> R.mipmap.x_qing
                "Cloudy day" -> R.mipmap.x_yin
                "Rainy day" -> R.mipmap.x_dayu
                "Snowy day" -> R.mipmap.x_xiaxue
                "Greasy day" -> R.mipmap.x_wumaishachengbao
                "Unknown" -> R.mipmap.x_qing
                else -> R.mipmap.x_qing
            }
            binding.tvWeather.setCompoundDrawablesWithIntrinsicBounds(
                ContextCompat.getDrawable(requireContext(), icon),
                null,
                null,
                null
            )
            binding.tvWeather.visibility = View.VISIBLE
            binding.tvWeather.text = "${value}℃"
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun itemKeyClick(key: String) {
        val bean = functions1.find { it.key == key }
        if (bean?.isPlaying == true) {
            bean.showGuide = false
            AppPreferences.getInstance().put("${key}_guide", false)
        }
        when (key) {
            KEY_SCAN -> {
//                startActivity(Intent(requireContext(), ScanAc::class.java))
                startActivity(Intent(requireContext(), ScanOtherActivity::class.java))
            }


            KEY_WIFI -> {
                startActivity(Intent(requireContext(), WifiActivity::class.java))
            }

            KEY_TEXT -> {
                startActivity(Intent(requireContext(), TextActivity::class.java))
            }

            KEY_EMAIL -> {
                startActivity(Intent(requireContext(), EmailActivity::class.java))
            }

            KEY_WEBSITE -> {
                startActivity(Intent(requireContext(), WebsiteActivity::class.java))
            }

            KEY_EVENT -> {
                startActivity(Intent(requireContext(), EventActivity::class.java))
            }

            KEY_TELEPHONE -> {
                startActivity(Intent(requireContext(), TelephoneActivity::class.java))
            }

            KEY_CONTACT -> {
                startActivity(Intent(requireContext(), ContractActivity::class.java))
            }

            KEY_MESSAGE -> {
                startActivity(Intent(requireContext(), MessageActivity::class.java))
            }

            KEY_WHATSAPP -> {
                val activity = requireActivity() as MainActivity?
                activity?.showWhatsappDialog(activity.launcher)
            }

            KEY_FACEBOOK -> {
                val activity = requireActivity() as MainActivity?
                activity?.showFacebookDialog()
            }

            KEY_INSTAGRAM -> {
                val activity = requireActivity() as MainActivity?
                activity?.showInstagramDialog()
            }

            KEY_X -> {
                val activity = requireActivity() as MainActivity?
                activity?.showXDialog()
            }

            KEY_PAYPAL -> {
                val activity = requireActivity() as MainActivity?
                activity?.showPaypalDialog()
            }

            KEY_SPOTIFY -> {
                val activity = requireActivity() as MainActivity?
                activity?.showSpotifyDialog()
            }

            KEY_YOUTUBE -> {
                val activity = requireActivity() as MainActivity?
                activity?.showYoutubeDialog()
            }

            KEY_ADDRESS -> {
                val activity = requireActivity() as MainActivity?
                activity?.showAddressDialog()
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        functionRvAdapter1?.functionAdapter?.changeGuide()

        binding.root.viewTreeObserver.addOnGlobalLayoutListener {
            showGuideScan()
        }
    }

    override fun onResume() {
        super.onResume()
        immersionBar {
            statusBarColor("#FFFFFFFF")
            statusBarDarkFont(true)
        }

        setWeather()
    }

    override fun initListener() {
        super.initListener()

        binding.tvZodiac.setOnClickListener {
//            startActivity(Intent(context, WebBrowserActivity::class.java).apply {
//                putExtra("url", "https://www.horoscope.com/us/index.aspx")
//            })

            startActivity(Intent(requireContext(), QrStyleActivity::class.java))
        }
        binding.tvWeather.setOnClickListener {
            startActivity(Intent(context, WeatherInterface::class.java))
        }
//        binding.rv.setOnClickListener {
//            if (isContinuousTimesClick()) {
//                val sb = StringBuilder()
//                val gson = Gson()
//                sb.append("isInBlackList:").append(ConfigBean.configBean.isInBlackList).append("\n")
//                sb.append("ut:${ConfigBean.configBean.ut}").append("\n")
//                val adLog = gson.toJson(ConfigBean.configBean.adConfigBean).replace(",", ",\n")
//                sb.append(adLog).append("\n")
//                val popupLog =
//                    gson.toJson(ConfigBean.configBean.popupConfigBean).replace(",", ",\n")
//                sb.append(popupLog).append("\n")
//                sb.append("uuid:").append(AppPreferences.getInstance().getString("uuid", "null"))
//                requireContext().showLogDialog(sb.toString())
//            }
//        }

    }

    private fun showGuideScan() {
        val isGuideScan = AppPreferences.getInstance().getBoolean("isGuideScan", false)
        if (isGuideScan) return
        val activity = requireActivity() as Activity?
        activity ?: return
        val targetView = headAdapter?.guideIv
        targetView ?: return

        val builder = GuideBuilder()
        builder.setTargetView(targetView)
            .setHighTargetGraphStyle(Component.CIRCLE)
            .setAlpha(150)
            .setHighTargetCorner(20)
            .setHighTargetPadding(5)
            .setExitAnimationId(android.R.anim.fade_out)
        builder.setOnVisibilityChangedListener(object : GuideBuilder.OnVisibilityChangedListener {
            override fun onShown() {
                AppPreferences.getInstance().put("isGuideScan", true)
            }

            override fun onDismiss() {
                activity.startActivity(Intent(activity, ScanAc::class.java))
            }
        })
        builder.addComponent(LottieComponent())
        val guide = builder.createGuide()
        guide.setShouldCheckLocInWindow(false)
        guide.show(activity)
    }


}