package com.swago.home

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.fragment.app.viewModels
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.permissionx.guolindev.PermissionX
import com.swago.baseswago.PayVm
import com.swago.baseswago.SwagoAdapter
import com.swago.baseswago.activity.BaseXActivity
import com.swago.baseswago.agora.AgoraManager
import com.swago.baseswago.constant.ARouteConstant
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.AppContext
import com.swago.baseswago.util.IMUtil
import com.swago.baseswago.util.LogUtil
import com.swago.baseswago.util.UserInfo
import com.swago.home.databinding.ActivityHomeBinding
import com.swago.home.innerhome.HomeVm
import com.swago.home.official.OfficialVm
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack

/**
 *@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 listFragment =
        arrayListOf(HomeFragment(),MessageFragment(), MineFragment())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setImmersionBar(true,false)
    }

    override fun loadData() {

    }

    override fun initOther() {
        PayManager.init()
        IMMessageManager.groupMessageParser.add(GroupMsgParser())

        binding.viewPager.offscreenPageLimit = 3
        binding.rg.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rbHome -> {
                    binding.viewPager.currentItem = 0
                }
                R.id.rbMessage -> {
                    binding.viewPager.currentItem = 1
                }
                R.id.rbMine -> {
                    binding.viewPager.currentItem = 2
                }
            }
        }

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

            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> {
                        if (binding.rbHome.isChecked) {
                            return
                        }
                        binding.rg.check(R.id.rbHome)
                    }
                    1 -> {
                        if (binding.rbMessage.isChecked) {
                            return
                        }
                        binding.rg.check(R.id.rbMessage)
                    }
                    2 -> {
                        if (binding.rbMine.isChecked) {
                            return
                        }
                        binding.rg.check(R.id.rbMine)
                    }
                }

            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })

        binding.viewPager.adapter = SwagoAdapter(listFragment, supportFragmentManager)
    }

    override fun initLiveData() {}

    override fun onResume() {
        super.onResume()
        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) {
        Toast.makeText(AppContext.getContext(), AppContext.getContext().resources.getString(R.string.pay_fail)+"-$code", Toast.LENGTH_SHORT).show()
    }

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

    override fun onUnConsumeOrder(data: List<Purchase>) {
        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()
                }

            })
        }
    }
}