package com.swago.home

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.android.billingclient.api.Purchase
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.swago.baseswago.GradientIndicator
import com.swago.baseswago.PayVm
import com.swago.baseswago.SwagoAdapter
import com.swago.baseswago.UserVm
import com.swago.baseswago.activity.BaseXActivity
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.constant.UrlConstant
import com.swago.baseswago.dialog.BenefitBagDialog
import com.swago.baseswago.dialog.OrderLostDialog
import com.swago.baseswago.im.GroupMsgParser
import com.swago.baseswago.im.IMMessageManager
import com.swago.baseswago.libpay.IPayCallback
import com.swago.baseswago.libpay.PayManager
import com.swago.baseswago.model.pay.PayModel
import com.swago.baseswago.util.*
import com.swago.home.databinding.ActivityHomeBinding
import com.swago.home.innerhome.HomeVm
import com.swago.home.innerhome.HotFragment
import com.swago.home.innerhome.NewFragment
import com.swago.home.official.OfficialVm
import com.swago.home.update.UpdateDialog
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.config.TUIKitConfigs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
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.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView

/**
 *@date 2021/8/17 22:39
 *description:
 */
@Route(path = ARouteConstant.Home.home)
class HomeActivity : BaseXActivity<ActivityHomeBinding>(),  IPayCallback{

    private val officialVm by viewModels<OfficialVm>()
    private val homeVm by viewModels<HomeVm>()
    private val payVm by viewModels<PayVm>()
    private val userVm by viewModels<UserVm>()

    private val listFragments = arrayListOf(HotFragment(), NewFragment())
    private val listTitles = arrayListOf(
        AppContext.getContext().resources.getString(R.string.home_hot),
        AppContext.getContext().resources.getString(R.string.home_new)
    )


    override fun loadData() {
//        payVm.getBenefit()
    }

    override fun initOther() {
        TUIKit.init(this, UrlConstant.getImId(), TUIKitConfigs.getConfigs())
        PayManager.init()
        IMMessageManager.groupMessageParser.add(GroupMsgParser())

        //检查版本更新
        checkVersionForUpdate()

        binding.viewPager.offscreenPageLimit = 3
        val viewPagerAdapter = SwagoAdapter(listFragments, supportFragmentManager, listTitles)
        binding.viewPager.adapter = viewPagerAdapter

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

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val simplePagerTitleView = SimplePagerTitleView(context)
                simplePagerTitleView.text = listTitles[index]
                val padding = DpPxUtil.dip2px(15f).toFloat()
                simplePagerTitleView.textSize = 16f
                simplePagerTitleView.typeface = Typeface.createFromAsset(AppContext.getContext().assets,"bold.otf")
                simplePagerTitleView.setPadding(padding.toInt(), 0, padding.toInt(), 0)
                simplePagerTitleView.normalColor = Color.parseColor("#828C9D")
                simplePagerTitleView.selectedColor = Color.parseColor("#131B23")
                simplePagerTitleView.setOnClickListener {
                    binding.viewPager.currentItem = index
                }
                return simplePagerTitleView
            }

            override fun getIndicator(context: Context?): IPagerIndicator {
                val indicator = LinePagerIndicator(context)
                indicator.setColors(Color.parseColor("#131B23"))
                indicator.mode = GradientIndicator.MODE_WRAP_CONTENT
                indicator.lineWidth = DpPxUtil.dip2px(12f).toFloat()
                indicator.xOffset = DpPxUtil.dip2px(5f).toFloat()
                indicator.yOffset = DpPxUtil.dip2px(14f).toFloat()
                indicator.lineHeight = DpPxUtil.dip2px(2f).toFloat()
                return indicator
            }

        }

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

        binding.ivMsg.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                startActivity(Intent(this@HomeActivity,MessageActivity::class.java))
            }
        })

        binding.drawerLayout.setScrimColor(Color.TRANSPARENT)
        binding.ivMine.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
               binding.drawerLayout.openDrawer(binding.clMine)
            }
        })

        binding.viewPager.addOnPageChangeListener(object:ViewPager.OnPageChangeListener{
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                when(position){
                    0 -> {
                        (listFragments[position] as HotFragment).loadData()
                    }
                    1 -> {
                        (listFragments[position] as NewFragment).loadData()
                    }
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })

        setMine()
    }

    private fun setMine() {
        if (SwagoInfo.isGooglePackage()){
            binding.tvXWithdrawal.visibility = View.GONE
        }else{
            binding.tvXWithdrawal.visibility = View.VISIBLE
        }

        binding.llFans.setOnClickListener(object: NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance()
                    .build(ARouteConstant.User.followFan)
                    .withInt("type", 1)
                    .navigation()
            }

        })
        binding.llFollow.setOnClickListener(object: NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance()
                    .build(ARouteConstant.User.followFan)
                    .withInt("type", 0)
                    .navigation()
            }

        })

        binding.llCoin.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                if (SwagoInfo.isGooglePackage()){
                    ARouter.getInstance().build(ARouteConstant.User.recharge).navigation()
                }else{
                    ARouter.getInstance().build(ARouteConstant.Base.webView)
                        .withString("url", UrlConstant.TOP_UP)
                        .navigation()
                }
            }
        })

        binding.tvEdit.setOnClickListener(object: NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.User.editInfo).navigation()
            }

        })
        binding.tvSetting.setOnClickListener(object: NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.User.setting).navigation()
            }

        })

        binding.tvXLevel.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.User.level).navigation()
            }
        })

        binding.tvXTopUp.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                if (SwagoInfo.isGooglePackage()){
                    ARouter.getInstance().build(ARouteConstant.User.recharge).navigation()
                }else{
                    ARouter.getInstance().build(ARouteConstant.Base.webView)
                        .withString("url", UrlConstant.TOP_UP)
                        .navigation()
                }
            }
        })

        binding.tvXTaskCenter.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.User.taskCenter).navigation()
            }
        })

        binding.tvCustomService.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.User.customService).navigation()
            }
        })

        binding.tvXWithdrawal.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.Base.webView)
                    .withString("url", UrlConstant.WITHDRAW)
                    .navigation()
            }
        })

        binding.tvBlackList.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.User.blacklist).navigation()
            }
        })
    }

    /**
     * 检查版本更新
     */
    private fun checkVersionForUpdate() {
        UrlConstant.getConfigModel()?.let {
            if (it.app_version>SwagoInfo.getVersionCode().toInt()){
                UpdateDialog.newInstance().show(supportFragmentManager,"UpdateDialog")
            }
        }
    }

    override fun initLiveData() {
        userVm.userInfoLiveData.observe(this) {
            UserInfo.setUserInfo(it)
            SpUtil.putString("user_info", Gson().toJson(it))

            Glide.with(this).load(it.user_head_img_url).placeholder(com.swago.baseswago.R.mipmap.default_avatar).error(
                com.swago.baseswago.R.mipmap.default_avatar).into(binding.ivAvatar)
            binding.tvName.text = it.user_name
            binding.tvID.text =
                AppContext.getContext().resources.getString(com.swago.baseswago.R.string.id_x).format(it.user_account)
            binding.tvFansNum.text = it.user_fans_num
            binding.tvFollowNum.text = it.user_follow_num
            binding.tvCoin.text = it.user_coins
            binding.tvDiamonds.text = it.user_diamonds
            binding.tvLevelView.setUserLevel(it.user_wealth_level.toInt())

            if (it.is_benefit == 1){
                binding.ivVip.visibility = View.VISIBLE
            }else{
                binding.ivVip.visibility = View.GONE
            }

            if (it.is_service == 1){
                binding.tvAgent.visibility = View.VISIBLE
            }else{
                binding.tvAgent.visibility = View.GONE
            }

            if (it.is_official== 1){
                binding.tvOfficial.visibility = View.VISIBLE
            }else{
                binding.tvOfficial.visibility = View.GONE
            }



        }

        payVm.benefitLiveData.observe(this){
            if (it.is_benefit==0&&it.is_pop_discount_package==0){
                BenefitBagDialog.newInstance().show(supportFragmentManager, "BenefitBagDialog")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        userVm.getUserInfo()
        PayManager.listener.add(this)
        if (!IMUtil.checkIsLogin()){
            IMUtil.joinGroup(loginFun)
        }
    }

    override fun onPause() {
        super.onPause()
        PayManager.listener.remove(this)
    }

    override fun onConnectedServer() {
    }

    override fun onPaySuccess(data: List<Purchase>?) {
        //调用谷歌支付回调支付成功
    }

    override fun onQueryProductPrice(data: List<PayModel>) {
    }

    override fun onPayError(code: Int) {
        lifecycleScope.launch(Dispatchers.Main) {
            Toast.makeText(
                AppContext.getContext(),
                AppContext.getContext().resources.getString(R.string.pay_fail) + "-$code",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    override fun onPayCancel() {
        lifecycleScope.launch(Dispatchers.Main) {
            Toast.makeText(
                AppContext.getContext(),
                AppContext.getContext().resources.getString(R.string.pay_cancel),
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    override fun onUnConsumeOrder(data: List<Purchase>) {
        lifecycleScope.launch(Dispatchers.Main) {
            data.forEach {
                val orderLostDialog = OrderLostDialog.newInstance(it.orderId)
                orderLostDialog.commitLostOrderFun = {
                    payVm.payOrderToServer(it, 4)
                }
                orderLostDialog.show(supportFragmentManager, "OrderLostDialog")
            }
        }
    }

    override fun consumeOrderSuccess() {
    }

    override fun consumeOrderFail(code: Int) {
    }

    override fun toCreateNewOrder(productId: String) {}

    override fun onBackPressed() {
        moveTaskToBack(true)
    }


    var loginFun:(()->Unit) = {
        UserInfo.getLoginModel()?.let {
            TUIKit.login(it.user_account,it.user_sig,object:
                IUIKitCallBack {
                override fun onSuccess(data: Any?) {
                    IMUtil.joinGroup(null)
                }

                override fun onError(module: String?, errCode: Int, errMsg: String?) {
                    Toast.makeText(AppContext.getContext(), "IM Login error-$errCode", Toast.LENGTH_SHORT).show()
                }

            })
        }
    }
}