package com.cheng.blzb.ui.fragment.main

import android.text.TextUtils
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
import com.cheng.blzb.R
import com.cheng.blzb.bean.PushPayloadEntity
import com.cheng.blzb.common.AppUpdate
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentMainBinding
import com.cheng.blzb.event.HomeRefreshEvent
import com.cheng.blzb.event.LoginSuccessEvent
import com.cheng.blzb.event.MineRefreshEvent
import com.cheng.blzb.event.PushMessageEvent
import com.cheng.blzb.event.VipPaySuccessEvent
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.activity.LoginActivity
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.base.BasePageAdapter
import com.cheng.blzb.ui.dialog.PublishBidDialog
import com.cheng.blzb.ui.dialog.VipLoginTipDialog
import com.cheng.blzb.ui.fragment.bid.detail.BidDetailFragment
import com.cheng.blzb.ui.fragment.home.HomeFragment
import com.cheng.blzb.ui.fragment.merchant.MerchantFragment
import com.cheng.blzb.ui.fragment.merchant.detail.MerchantGoodsDetailFragment
import com.cheng.blzb.ui.fragment.mine.MineFragment
import com.cheng.blzb.ui.fragment.mine.coupon.CouponFragment
import com.cheng.blzb.ui.fragment.mine.vip.VipFragment
import com.cheng.blzb.ui.fragment.push.PushFragment
import com.example.base.common.RxBus
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.ui.BaseFragment
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.huantansheng.easyphotos.EasyPhotos


class MainFragment : BaseFragment<FragmentMainBinding, MainViewModel>() {
    private val tabText = listOf("首页", "推送", "合作商", "我的")
    private val fragmentList by lazy { mutableListOf<Fragment>() }
    private val pageAdapter by lazy { BasePageAdapter(childFragmentManager, tabText, fragmentList, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) }

    private var userInfo: com.cheng.blzb.bean.UserEntity? = null

    private val intervalTime: Int = 3000
    private var lastCheckTime = System.currentTimeMillis()

    private var currentPosition = 0

    override fun initView() {
        super.initView()
        ImmersionBar.with(this).navigationBarColor(R.color.white).init()
        EasyPhotos.preLoad(requireContext())

        initFragment()
        binding.viewPager.adapter = pageAdapter
        binding.viewPager.offscreenPageLimit = fragmentList.size
    }

    private fun initFragment() {
        fragmentList.add(HomeFragment())
        fragmentList.add(PushFragment())
        fragmentList.add(MerchantFragment())
        fragmentList.add(MineFragment())
    }

    override fun initListener() {
        super.initListener()
        binding.rgNavigation.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb_home -> currentPosition = 0
                R.id.rb_push -> currentPosition = 1
                R.id.rb_merchant -> currentPosition = 2
                R.id.rb_mine -> currentPosition = 3
            }
            binding.viewPager.setCurrentItem(currentPosition, false)

            if (userInfo != null && userInfo!!.temp && (userInfo?.vip == "2" || userInfo?.vip == "3")) {
                val vipLoginTipDialog = VipLoginTipDialog(this@MainFragment)
                vipLoginTipDialog.setOnSelectListener {
                    LoginActivity.start(requireActivity())
                    requireActivity().finish()
                }
                vipLoginTipDialog.show()
            }

            when (currentPosition) {
//                0 -> RxBus.defaultInstance.post(HomeRefreshEvent())
            }
            lastCheckTime = System.currentTimeMillis()

            EventReportManager.eventReport(EventConstants.HOME_BOTTOM_TAB_CHECK, tabText[currentPosition], "")
        }

        binding.ivPublish.onClick {
            PublishBidDialog().show(childFragmentManager, "")
        }
    }

    override fun initData() {
        super.initData()
        UserConfigManager.userConfig {
            checkVersion()
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel.userInfo()
        if (UserConfigManager.getAreaList().isEmpty()) {
            mViewModel.getAreaList()
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.userInfoLiveData.observe(this) {
            userInfo = it
            UserConfigManager.userInfoLiveData.postValue(it)

            if (it.temp && (it.vip == "2" || it.vip == "3")) {
                val vipLoginTipDialog = VipLoginTipDialog(this)
                vipLoginTipDialog.setOnSelectListener {
                    LoginActivity.start(requireActivity())
                    requireActivity().finish()
                }
                vipLoginTipDialog.show()
            }
            if (!TextUtils.isEmpty(UserConfigManager.getGTCid())) {
                if (UserConfigManager.getGTCid() != it.client_cid) {
                    mViewModel.updateGTCid(UserConfigManager.getGTCid())
                }
            }
        }

        mViewModel.areaLiveData.observe(this) {
            UserConfigManager.saveAreaList(it)
        }

        mViewModel.getCouponLiveData.observe(this) {
            toast("领取成功")
            PublicActivity.start(requireContext(), CouponFragment::class.java)
        }

        val loginSuccessEvent = RxBus.defaultInstance.toObservable(LoginSuccessEvent::class.java).subscribe {
            RxBus.defaultInstance.post(HomeRefreshEvent())
            RxBus.defaultInstance.post(MineRefreshEvent())
        }
        addDisposable(loginSuccessEvent)

        val paySuccessEvent = RxBus.defaultInstance.toObservable(VipPaySuccessEvent::class.java).subscribe {
            UserConfigManager.userConfig {}
        }
        addDisposable(paySuccessEvent)

        val pushMessageEvent = RxBus.defaultInstance.toObservable(PushMessageEvent::class.java).subscribe {
            if (!TextUtils.isEmpty(it.payload)) {
                val payload = Gson().fromJson(it.payload, PushPayloadEntity::class.java)
                if (it.type == 3) handlePushMessage(payload)
                mViewModel.reportPushReceipt(payload.msgId, "${it.type}")
            }
        }
        addDisposable(pushMessageEvent)
    }

    private fun handlePushMessage(payloadEntity: PushPayloadEntity) {
        if (TextUtils.isEmpty(payloadEntity.page)) return
        when (payloadEntity.page) {
            "member_recharge" -> {
                PublicActivity.start(
                    requireContext(),
                    VipFragment::class.java,
                    Pair("origin", parseData("source", payloadEntity.params)),
                    Pair("goodsType", parseData("type", payloadEntity.params))
                )
            }

            "bid_info" -> {
                val bidId = parseData("bid_info_id", payloadEntity.params)
                if (TextUtils.isEmpty(bidId)) {
                    toast("标讯id为空")
                    return
                }
                PublicActivity.start(requireActivity(),
                    BidDetailFragment::class.java,
                    Pair("source", parseData("source", payloadEntity.params)),
                    Pair("goodsType", parseData("type", payloadEntity.params)),
                    Pair("info_source", parseData("info_source", payloadEntity.params)),
                    Pair("id", bidId),
                    Pair("origin", "push")
                )
            }

            "goods_details" -> {
                PublicActivity.start(requireActivity(),
                    MerchantGoodsDetailFragment::class.java,
                    Pair("id", parseData("goods_id", payloadEntity.params))
                )
            }
        }
    }

    private fun parseData(key: String, paramStr: String): String {
        if (!TextUtils.isEmpty(paramStr)) {
            val param = paramStr.split(",")
            for (i in param.indices) {
                val keyValue = param[i].split("=")
                if (keyValue.size > 1) {
                    if (keyValue[0] == key) {
                        return keyValue[1]
                    }
                }
            }
        }
        return ""
    }

    private fun checkVersion() {
        AppUpdate.checkUpdate(this, false) {}
    }
}