package com.swago.room.gift

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.viewpager.widget.ViewPager
import com.facebook.internal.AppCall
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.swago.baseswago.GradientIndicator
import com.swago.baseswago.SwagoAdapter
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.dialog.BaseXDFragment
import com.swago.baseswago.dialog.PayDialog
import com.swago.baseswago.model.live.gift.GiftAllModel
import com.swago.baseswago.model.live.gift.GiftModel
import com.swago.baseswago.util.*
import com.swago.room.R
import com.swago.room.databinding.DialogGiftBinding
import com.swago.room.gift.GiftConfig.giftSelectedWhichType
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView

/**
 *@date 2021/12/12 14:59
 *description:
 */
class GiftDialog : BaseXDFragment<DialogGiftBinding>() {

    private val giftVm by activityViewModels<GiftVm>()
    private var giftBatch = 0
    private var returnGiftBatch = 0
    private var receiveId = ""
    private var receiveName = ""

    private val gson by lazy {
        Gson()
    }

    private val titleList = arrayListOf(
        AppContext.getContext().resources.getString(R.string.lucky),
        AppContext.getContext().resources.getString(R.string.hot),
        AppContext.getContext().resources.getString(R.string.luxury)
    )
    private val giftFragmentList = ArrayList<GiftFragment>()

    private var luckyFragment: GiftFragment? = null
    private var hotFragment: GiftFragment? = null
    private var luxuryFragment: GiftFragment? = null
    private var luckyData = ArrayList<GiftModel>()
    private var hotData = ArrayList<GiftModel>()
    private var luxuryData = ArrayList<GiftModel>()
    private var viewPagerAdapter:SwagoAdapter? = null

    private var type = 1

    private var json:String? = ""

    init {
        setGravity(Gravity.BOTTOM)
        setDimAmount(0f)
    }

    companion object {
        fun newInstance(
            receiveName: String,
            receiveId: String
        ): GiftDialog {
            val giftDialog = GiftDialog()
            val bundle = Bundle()
            bundle.putString("receiveId", receiveId)
            bundle.putString("receiveName", receiveName)
            giftDialog.arguments = bundle
            return giftDialog
        }
    }

    override fun initOther() {
        arguments?.let {
            receiveId = it.getString("receiveId", "")
            receiveName = it.getString("receiveName", "")

            //先走缓存
            json = SpUtil.readString("giftList")
            if (json.isNullOrEmpty()){

            }else{
                val list:ArrayList<GiftAllModel> = gson.fromJson(json, object : TypeToken<ArrayList<GiftAllModel>>() {}.type)
                list.forEach { giftAllModel ->
                    when (giftAllModel.gift_type) {
                        1 -> {
                            //热门礼物
                            hotData.clear()
                            hotData.addAll(giftAllModel.data)
                        }

                        2 -> {
                            //奢华礼物
                            luxuryData.clear()
                            luxuryData.addAll(giftAllModel.data)
                        }

                        3 -> {
                            //幸运礼物
                            luckyData.clear()
                            luckyData.addAll(giftAllModel.data)
                            GiftConfig.list.clear()
                            GiftConfig.list.addAll(giftAllModel.position)
                        }
                    }
                }
                binding.tvToSend.visibility = View.VISIBLE
            }
            giftVm.getGiftList()
            binding.tvCoins.text = UserInfo.getUserInfo()?.user_coins ?: "0"
            binding.tvSender.text =
                AppContext.getContext().resources.getString(R.string.send_to).format(receiveName)

            luckyFragment = GiftFragment.newInstance(3, luckyData)
            hotFragment = GiftFragment.newInstance(1, hotData)
            luxuryFragment = GiftFragment.newInstance(2, luxuryData)

            giftFragmentList.add(luckyFragment!!)
            giftFragmentList.add(hotFragment!!)
            giftFragmentList.add(luxuryFragment!!)


            /**
             * 重置选中的礼物
             */
            luckyFragment?.listener = {
                resetSendState()
                hotFragment?.reset()
                luxuryFragment?.reset()
            }
            hotFragment?.listener = {
                resetSendState()
                luckyFragment?.reset()
                luxuryFragment?.reset()
            }
            luxuryFragment?.listener = {
                resetSendState()
                luckyFragment?.reset()
                hotFragment?.reset()
            }

            binding.viewPager.offscreenPageLimit = 3
            viewPagerAdapter = SwagoAdapter(giftFragmentList, childFragmentManager, titleList)
            binding.viewPager.adapter = viewPagerAdapter

            val commonNavigator = CommonNavigator(context)
            commonNavigator.adapter = object : CommonNavigatorAdapter() {
                override fun getCount(): Int {
                    return titleList.size
                }

                override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                    val simplePagerTitleView = SimplePagerTitleView(context)
                    simplePagerTitleView.text = titleList[index]
                    val padding = DpPxUtil.dip2px(15f).toFloat()
                    simplePagerTitleView.textSize = 16f
                    simplePagerTitleView.setPadding(padding.toInt(), 0, padding.toInt(), 0)
                    simplePagerTitleView.normalColor = Color.parseColor("#868686")
                    simplePagerTitleView.selectedColor = Color.parseColor("#ffffff")
                    simplePagerTitleView.setOnClickListener {
                        binding.viewPager.currentItem = index
                    }
                    return simplePagerTitleView
                }

                override fun getIndicator(context: Context?): IPagerIndicator {
                    val indicator = GradientIndicator(context)
                    indicator.mode = GradientIndicator.MODE_WRAP_CONTENT
                    indicator.lineWidth = DpPxUtil.dip2px(72f).toFloat()
                    indicator.xOffset = DpPxUtil.dip2px(5f).toFloat()
                    indicator.yOffset = DpPxUtil.dip2px(3f).toFloat()
                    indicator.lineHeight = DpPxUtil.dip2px(4f).toFloat()
                    indicator.roundRadius = DpPxUtil.dip2px(2f).toFloat()
                    return indicator
                }

            }

            binding.magicIndicator.navigator = commonNavigator
            ViewPagerHelper.bind(binding.magicIndicator, binding.viewPager)

            //打开礼物弹窗时默认显示到上次选中的礼物
            binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrollStateChanged(state: Int) {}

                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                    type = position + 1
                    binding.combo.visibility = View.GONE
                }
            })

            binding.tvCoins.setOnClickListener(object : NoDoubleClickListener() {
                override fun onClick() {
                    val dialog = PayDialog.newInstance()
                    dialog.show(parentFragmentManager, "PayDialog")
                    dismissAllowingStateLoss()
                }
            })

            when (GiftConfig.giftSelectedWhichType) {
                1 -> {
                    binding.viewPager.currentItem = 1
                }
                2 -> {
                    binding.viewPager.currentItem = 2
                }
                3 -> {
                    binding.viewPager.currentItem = 0
                }
            }

            binding.combo.setOnClick(object : ComboView.OnClick {
                override fun click() {
                    val gifModel =
                        luckyData[GiftConfig.giftSelectedPageIndex * 8 + GiftConfig.giftSelectedPageSelectedPosition]
                    LogUtil.d("礼物id", "${gifModel.gift_name}")
                    sendGift(gifModel, 1, GiftConfig.list[GiftConfig.clickCount])

                }

                override fun countFinish() {
                    binding.tvToSend.visibility = View.VISIBLE
                    binding.combo.visibility = View.GONE
                }

            })

            //点击送礼
            binding.tvToSend.setOnClickListener {
                when (type) {
                    1 -> {
                        //幸运
                        binding.combo.visibility = View.VISIBLE
                        binding.tvToSend.visibility = View.GONE
                        binding.combo.start()
                        val gifModel =
                            luckyData[GiftConfig.giftSelectedPageIndex * 8 + GiftConfig.giftSelectedPageSelectedPosition]
                        LogUtil.d("礼物id", "${gifModel.gift_name}")
                        sendGift(gifModel, 0, GiftConfig.list[GiftConfig.clickCount])

                    }

                    2 -> {
                        //热门
                        val gifModel =
                            hotData[GiftConfig.giftSelectedPageIndex * 8 + GiftConfig.giftSelectedPageSelectedPosition]
                        LogUtil.d("礼物id", "${gifModel.gift_name}")
                        sendGift(gifModel, 0)
                        dismissAllowingStateLoss()

                    }

                    3 -> {
                        //高级
                        val gifModel =
                            luxuryData[GiftConfig.giftSelectedPageIndex * 8 + GiftConfig.giftSelectedPageSelectedPosition]
                        LogUtil.d("礼物id", "${gifModel.gift_name}")
                        sendGift(gifModel, 0)
                        dismissAllowingStateLoss()
                    }
                }


            }
        }
    }

    private fun resetSendState() {
        binding.combo.cancel()
        binding.combo.visibility = View.GONE
        binding.tvToSend.visibility = View.VISIBLE
    }


    private fun sendGift(giftModel: GiftModel, isCombo: Int = 0, giftNum: Int = 1) {
        giftBatch++
        if (receiveId.isNotEmpty()) {
            SwagoRoomManager.iRoomInfo?.let {
                giftVm.sendGift(
                    it.getRoomId(),
                    giftModel.id,
                    giftBatch,
                    receiveId,
                    isCombo,
                    giftNum
                )
            }
        }
    }

    override fun initLiveData() {
        giftVm.allGiftLiveData.observe(this) {
            val netJson = gson.toJson(it)
            if (json != netJson || json.isNullOrEmpty()){
                SpUtil.putString("giftList", netJson)

                it.forEach { giftAllModel ->
                    when (giftAllModel.gift_type) {
                        1 -> {
                            //热门礼物
                            hotData.clear()
                            hotData.addAll(giftAllModel.data)
                        }

                        2 -> {
                            //奢华礼物
                            luxuryData.clear()
                            luxuryData.addAll(giftAllModel.data)
                        }

                        3 -> {
                            //幸运礼物
                            luckyData.clear()
                            luckyData.addAll(giftAllModel.data)
                            GiftConfig.list.clear()
                            GiftConfig.list.addAll(giftAllModel.position)
                        }
                    }
                }
                viewPagerAdapter?.notifyDataSetChanged()
                binding.tvToSend.visibility = View.VISIBLE
            }
        }

        giftVm.sendResultLiveData.observe(this) {
            if (it != null) {
                if (returnGiftBatch < it.gift_batch) {
                    UserInfo.getUserInfo()?.user_coins = it.user_coins
                    binding.tvCoins.text = it.user_coins ?: "0"
                    returnGiftBatch = it.gift_batch
                }
            } else {
                val payDialog = PayDialog.newInstance()
                payDialog.show(parentFragmentManager, "PayDialog")
                dismissAllowingStateLoss()
            }
        }
    }
}