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

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.view.Gravity
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.TextView
import androidx.core.animation.addListener
import com.cheng.blzb.R
import com.cheng.blzb.bean.HotWordEntity
import com.cheng.blzb.databinding.FragmentGuideItem4Binding
import com.cheng.blzb.event.GuideEvent
import com.cheng.blzb.ui.dialog.AddKeywordDialog
import com.cheng.blzb.ui.fragment.guide.GuideFragment
import com.cheng.blzb.ui.fragment.guide.GuideViewModel
import com.cheng.blzb.ui.fragment.guide.adapter.GuideItem4Adapter
import com.cheng.blzb.ui.fragment.guide.adapter.GuideItem4SelectedAdapter
import com.example.base.common.RxBus
import com.example.base.decoration.GridSpaceItemDecoration
import com.example.base.extensions.getColor
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.DensityUtils
import com.example.base.utils.ScreenUtils
import com.example.base.utils.SpanUtils
import kotlin.math.ceil

class GuideItem4Fragment : BaseFragment<FragmentGuideItem4Binding, GuideViewModel>() {
    private val mAdapter by lazy { GuideItem4Adapter() }

    private val selectedAdapter by lazy { GuideItem4SelectedAdapter() }

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

    private var tabIndex = 0

    private var page = 0

    private var canClick = false

    override fun initView() {
        super.initView()
        binding.mRecyclerView.adapter = mAdapter
        binding.mRecyclerView.addItemDecoration(GridSpaceItemDecoration(3, DensityUtils.dp2px(10f), DensityUtils.dp2px(10f)))

        binding.rvSelectedKeywords.adapter = selectedAdapter
        binding.rvSelectedKeywords.addItemDecoration(GridSpaceItemDecoration(3, DensityUtils.dp2px(10f), DensityUtils.dp2px(10f)))
        selectedAdapter.addData(HotWordEntity.Child(id = -1, name = "自定义", isChecked = true))
        setKeywordCount()
    }

    override fun onLazyLoad() {
        super.onLazyLoad()
        hotWordChildList.addAll(GuideFragment.hotWordList)
        hotWordChildList.forEach { item ->
            binding.tabLayout.addView(createTab(item.name))
        }

        startAnim()
    }

    override fun initListener() {
        super.initListener()
        binding.tabLayout.observeIndexChange { fromIndex, toIndex, _, _ ->
            page = 0
            tabIndex = toIndex

            if (fromIndex >= 0) {
                val textView = binding.tabLayout.getChildAt(fromIndex)
                textView.setBackgroundResource(0)
            }
            if (toIndex >= 0) {
                val textView = binding.tabLayout.getChildAt(toIndex)
                textView.setBackgroundResource(R.drawable.shape_f5f8ff_top_cor16)
            }

            val hotWordChild = hotWordChildList[toIndex]
            binding.tvAmount.text = "${hotWordChild.amount}亿元"

            val keywordList = mutableListOf<HotWordEntity.Child>()
            for (i in 0 until 15) {
                keywordList.add(hotWordChild.children[i])
            }
            mAdapter.setList(keywordList)
        }

        binding.ivRefresh.onClick {
            startRotate()
            val hotWordChild = hotWordChildList[tabIndex]
            if (ceil(hotWordChild.children.size / 15.0) > page + 1) {
                page++
            } else {
                page = 0
            }
            val keywordList = mutableListOf<HotWordEntity.Child>()
            for (i in page * 15 until ((page + 1) * 15).coerceAtMost(hotWordChild.children.size)) {
                keywordList.add(hotWordChild.children[i])
            }
            mAdapter.setList(keywordList)
        }

        binding.ivBtn.onClick {
            if (!canClick) return@onClick
            if (selectedAdapter.data.size == 1) {
                toast("请添加关键词")
                return@onClick
            }
            val keywords = selectedAdapter.data.filter { it.id != -1 }.map { it.name }
            val cityIds = GuideFragment.cityList.map { it.id }
            mViewModel.getTotalBidInfo(keywords.joinToString(","), cityIds.joinToString(","), "${hotWordChildList.size}")
        }

        mAdapter.setOnItemClickListener { _, _, i ->
            if (!canClick) return@setOnItemClickListener
            val item = mAdapter.getItem(i)
            if (!item.isChecked && selectedAdapter.data.size == 6) {
                toast("最多添加5个关键词")
                return@setOnItemClickListener
            }

            item.isChecked = !item.isChecked
            mAdapter.notifyDataSetChanged()
            if (item.isChecked) {
                selectedAdapter.addData(item)
            } else {
                selectedAdapter.remove(item)
            }
            setKeywordCount()
        }

        selectedAdapter.setOnItemClickListener { _, _, i ->
            val item = selectedAdapter.getItem(i)
            if (item.id == -1) {
                if (selectedAdapter.data.size == 6) {
                    toast("最多添加5个关键词")
                    return@setOnItemClickListener
                }
                val f = AddKeywordDialog.newInstance()
                f.setOnBackListener {
                    selectedAdapter.addData(HotWordEntity.Child(name = it, isChecked = true))
                    setKeywordCount()
                }
                f.show(childFragmentManager, "")
            }
        }

        selectedAdapter.setOnItemChildClickListener { _, view, i ->
            val item = selectedAdapter.getItem(i)
            if (!canClick || item.id == -1) return@setOnItemChildClickListener
            if (view.id == R.id.iv_delete) {
                selectedAdapter.remove(item)
                item.isChecked = false
                mAdapter.notifyDataSetChanged()
                setKeywordCount()
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.totalLiveData.observe(this) {
            GuideFragment.totalInfo = it
            RxBus.defaultInstance.post(GuideEvent(4))
        }
    }

    private fun setKeywordCount() {
        SpanUtils.with(binding.tvKeywordsCount)
            .append("已添加关键词(")
            .append("${selectedAdapter.data.size - 1}")
            .setForegroundColor(getColor(R.color.color_ff493c))
            .append("/5)")
            .create()
    }

    private fun createTab(title: String): TextView {
        val textView = TextView(requireContext())
        textView.text = title
        textView.gravity = Gravity.CENTER
        textView.setPadding(DensityUtils.dp2px(14f) , 0, DensityUtils.dp2px(14f), 0)
        return textView
    }

    private fun startRotate() {
        if (binding.ivRefresh.animation != null) {
            binding.ivRefresh.animation.cancel()
        }
        val anim = RotateAnimation(0f, 360f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f)
        anim.duration = 1000
        binding.ivRefresh.startAnimation(anim)
    }

    private fun startAnim() {
        val keyword1TransAnim = ObjectAnimator.ofFloat(binding.layoutKeywords, "translationY", ScreenUtils.getScreenWidth().toFloat(), 0f)
        keyword1TransAnim.duration = 1000
        keyword1TransAnim.startDelay = 200
        keyword1TransAnim.addListener(onStart = {
            binding.layoutKeywords.visible()
        })

        val keyword2TransAnim = ObjectAnimator.ofFloat(binding.layoutSelectedKeywords, "translationY", ScreenUtils.getScreenWidth().toFloat(), 0f)
        keyword2TransAnim.duration = 1000
        keyword2TransAnim.startDelay = 600
        keyword2TransAnim.addListener(onStart = {
            binding.layoutSelectedKeywords.visible()
        })

        val titleTransAnim = ObjectAnimator.ofFloat(binding.ivTitle, "translationY", -DensityUtils.dp2px(200f).toFloat(), 0f)
        titleTransAnim.duration = 1000
        titleTransAnim.startDelay = 200
        titleTransAnim.addListener(onStart = {
            binding.ivTitle.visible()
        })

        val descTransAnim = ObjectAnimator.ofFloat(binding.ivDesc, "translationY", -DensityUtils.dp2px(200f).toFloat(), 0f)
        descTransAnim.duration = 1000
        titleTransAnim.startDelay = 200
        descTransAnim.addListener(onStart = {
            binding.ivDesc.visible()
        })

        val btnTransAnim = ObjectAnimator.ofFloat(binding.ivBtn, "translationY", DensityUtils.dp2px(100f).toFloat(), 0f)
        btnTransAnim.duration = 1000
        btnTransAnim.startDelay = 800
        btnTransAnim.interpolator = LinearInterpolator()
        btnTransAnim.addListener(onStart = {
            binding.ivBtn.visible()
        }, onEnd = {
            canClick = true
        })

        val animSet = AnimatorSet()
        animSet.playTogether(
            keyword1TransAnim,
            keyword2TransAnim,
            titleTransAnim,
            descTransAnim,
            btnTransAnim
        )
        animSet.start()
    }
}