package com.cheng.blzb.ui.fragment.guide.item

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.LinearInterpolator
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.animation.addListener
import androidx.core.view.isVisible
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.bean.GuideTotalBidEntity
import com.cheng.blzb.bean.HotWordEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.FragmentGuideItem5Binding
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.fragment.guide.GuideFragment
import com.cheng.blzb.ui.fragment.guide.GuideViewModel
import com.cheng.blzb.ui.fragment.guide.adapter.GuideItem5CityAdapter
import com.cheng.blzb.ui.fragment.guide.adapter.GuideItem5IndustryAdapter
import com.cheng.blzb.ui.fragment.guide.vip.GuideVipFragment
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.DensityUtils
import com.google.gson.Gson
import com.yy.mobile.rollingtextview.CharOrder
import com.yy.mobile.rollingtextview.strategy.Strategy
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import org.jetbrains.anko.sdk27.listeners.onTouch
import org.libpag.PAGFile
import java.util.concurrent.TimeUnit

class GuideItem5Fragment : BaseFragment<FragmentGuideItem5Binding, GuideViewModel>() {
    private val cityAdapter by lazy { GuideItem5CityAdapter(requireContext(), cityList) }

    private val industryAdapter by lazy { GuideItem5IndustryAdapter(requireContext(), hotWordChildList) }

    private val hotWordChildList = mutableListOf<HotWordEntity.Child>()
    private val cityList = mutableListOf<AreaEntity>()

    private var totalInfo: GuideTotalBidEntity? = null

    private var industryTask: Disposable? = null

    override fun initView() {
        super.initView()
        binding.tvBidCount.typeface = Constants.ysbth
        binding.tvUnit.typeface = Constants.ysbth

        binding.rvIndustry.adapter = industryAdapter
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onLazyLoad() {
        super.onLazyLoad()
        totalInfo = GuideFragment.totalInfo

        cityList.addAll(GuideFragment.cityList)
        binding.viewFlipper.adapter = cityAdapter

        hotWordChildList.addAll(GuideFragment.hotWordList)
        industryAdapter.notifyDataSetChanged()
        startIndustryTask()

        startAnim()
    }

    override fun initListener() {
        super.initListener()
        binding.rvIndustry.onTouch { _, _ -> true }
    }

    private fun startAnim() {
        val bgTransAnim = ObjectAnimator.ofFloat(binding.ivBg, "translationY", 0f, -DensityUtils.dp2px(75f).toFloat())
        bgTransAnim.duration = 2000
        bgTransAnim.startDelay = 200

        val star1TranAnim = ObjectAnimator.ofFloat(binding.ivStar1, "translationY", DensityUtils.dp2px(125f).toFloat(), 0f)
        star1TranAnim.duration = 2000
        star1TranAnim.startDelay = 200

        val star2TranAnim = ObjectAnimator.ofFloat(binding.ivStar2, "translationY", 0f, -DensityUtils.dp2px(125f).toFloat())
        star2TranAnim.duration = 2000
        star2TranAnim.startDelay = 200

        val earthTransAnim = ObjectAnimator.ofFloat(binding.ivEarth, "translationY", 0f, -DensityUtils.dp2px(150f).toFloat())
        earthTransAnim.duration = 2000
        earthTransAnim.startDelay = 200

        val earthRotateAnim = ObjectAnimator.ofFloat(binding.ivEarth, "rotation", 0f, 360f)
        earthRotateAnim.duration = 100000
        earthRotateAnim.startDelay = 2400
        earthRotateAnim.repeatCount = -1
        earthRotateAnim.interpolator = LinearInterpolator()

        val infoAlphaAnim = ObjectAnimator.ofFloat(binding.layoutInfo, "alpha", 0f, 1f)
        infoAlphaAnim.duration = 1000
        infoAlphaAnim.startDelay = 2400
        infoAlphaAnim.addListener(onStart = {
            binding.layoutInfo.visible()
        }, onEnd = {
            startNumAnim()
        })

        val progressMaskAnim = ValueAnimator.ofFloat(0f, 1f)
        progressMaskAnim.duration = 1000
        progressMaskAnim.startDelay = 2400
        val maskHeight = binding.ivProgressMask.height
        progressMaskAnim.addUpdateListener { animator ->
            val value = animator.animatedValue as Float
            val lp = binding.ivProgressMask.layoutParams as ConstraintLayout.LayoutParams
            lp.height = (value * maskHeight).toInt()

            binding.ivProgressMask.layoutParams = lp
            if (!binding.ivProgressMask.isVisible) {
                binding.ivProgressMask.visible()
            }
        }
        progressMaskAnim.addListener(onStart = {
            startProgressAnim()

            val pagFile = PAGFile.Load(requireContext().assets, "effects/guide_bubble.pag")
            binding.pagView.composition = pagFile
            binding.pagView.setRepeatCount(0)
            binding.pagView.play()
            binding.pagView.visible()
        })

        val animSet = AnimatorSet()
        animSet.playTogether(bgTransAnim, star1TranAnim, star2TranAnim, earthTransAnim, earthRotateAnim, infoAlphaAnim, progressMaskAnim)
        animSet.start()
    }

    private fun startNumAnim() {
        binding.tvBidCount.animationDuration = 2000
        binding.tvBidCount.charStrategy = Strategy.CarryBitAnimation()
        binding.tvBidCount.addCharOrder(CharOrder.Number)
        binding.tvBidCount.animationInterpolator = AccelerateDecelerateInterpolator()
        binding.tvBidCount.setText("${totalInfo?.bidCount}")
    }

    private fun startProgressAnim() {
        binding.progressBar.post {
            if (activity != null) {
                binding.progressBar.progress = 1
                binding.tvProgressStatus.text = "采集引擎启动中...."
            }
        }
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 10
                binding.tvProgressStatus.text = "筛选区域标讯..."
            }
        }, 1500)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 20
                binding.tvProgressStatus.text = "筛选行业标讯..."
            }
        }, 2000)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 30
                binding.tvProgressStatus.text = "关键词标讯标注中..."
            }
        }, 2500)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 40
                binding.tvProgressStatus.text = "筛选最新优质标讯..."
            }
        }, 3000)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 50
                binding.tvProgressStatus.text = "正在整理数据..."
            }
        }, 3500)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 60
                binding.tvProgressStatus.text = "正在整理数据..."
            }
        }, 5500)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 70
                binding.tvProgressStatus.text = "正在整理数据..."
            }
        }, 7500)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 80
                binding.tvProgressStatus.text = "正在整理数据..."
            }
        }, 7600)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 90
                binding.tvProgressStatus.text = "正在整理数据..."
            }
        }, 7700)
        binding.progressBar.postDelayed({
            if (activity != null) {
                binding.progressBar.progress = 100
                binding.tvProgressStatus.text = "打开标讯采集报告..."
                binding.progressBar.postDelayed({
                    if (activity != null) {
                        PublicActivity.start(
                            requireContext(),
                            GuideVipFragment::class.java,
                            Pair("hotWords", Gson().toJson(hotWordChildList)),
                            Pair("total", totalInfo)
                        )
                        requireActivity().finish()
                    }
                }, 1000)
            }
        }, 8700)
    }

    private fun startIndustryTask() {
        if (industryAdapter.data.isEmpty() || industryTask != null) return
        industryTask = Observable.interval(300, 9, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (activity != null) {
                    binding.rvIndustry.scrollBy(3, 0)
                }
            }
    }

    private fun stopIndustryTask() {
        industryTask?.dispose()
        industryTask = null
    }

    override fun onStart() {
        super.onStart()
        startIndustryTask()
    }

    override fun onStop() {
        super.onStop()
        stopIndustryTask()
    }
}