package com.abbidot.tracker.ui.activity.subscribe

import android.content.Intent
import android.view.View
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.ChoosePlanAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.SubscriptionsOrderBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityChoosePlanBinding
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.SubscriptionManageViewModel

class ChoosePlanActivity :
    BaseActivity<ActivityChoosePlanBinding>(ActivityChoosePlanBinding::inflate) {

    private val mSubscriptionViewModel: SubscriptionManageViewModel by viewModels()

    private lateinit var mChoosePlanAdapter: ChoosePlanAdapter

    private var mSelectPlanIndex = 0
    private var mOrderBean: SubscriptionsOrderBean? = null

    //是否是升级套餐
    private var isUpgrade = false
    //设备类型
    private var mType = ConstantInt.Type1

    //设备充值类型，0=首次设备充值激活，1=已添加设备再次添加设备充值，2=给当前的设备续费或者升级套餐
    private var mRechargeType = ConstantInt.Type1

    override fun getTopBar() = mViewBinding.ilChoosePlanTopBar.titleTopBar

    override fun initData() {
        super.initData()
        var packageTypeName = ""
        intent.extras?.apply {
            packageTypeName = getString(ConstantString.Title, "")
            mOrderBean = Util.getParcelableAdaptive(
                intent, ConstantString.LkSetMeal, SubscriptionsOrderBean::class.java
            )
            mType = getInt(ConstantString.Type, ConstantInt.Type1)
            isUpgrade = getBoolean(ConstantString.Upgrade, false)
            mRechargeType = getInt(ConstantString.RechargeType, ConstantInt.Type1)
        }

        if (isUpgrade) {
            mRechargeType = ConstantInt.Type2
            setTopBarTitle(R.string.txt_upgrade_plan)
        } else {
            if (packageTypeName == "Basic") {
                setTopBarTitle(R.string.txt_basic_plan)
            } else {
                setTopBarTitle(R.string.txt_choose_your_plan)
            }
        }
        setLeftBackImage(R.drawable.icon_white_back_svg)

        mViewBinding.apply {

            mChoosePlanAdapter = ChoosePlanAdapter(mContext, null).apply {
                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        val list = getData()
                        if (pos > list.size - 1) return
                        val dataBean = list[pos]
                        if (dataBean.selected) return
                        for (i in 0 until list.size) {
                            val data = list[i]
                            if (data.selected) {
                                data.selected = false
                                notifyItemChanged(i)
                                break
                            }
                        }
                        dataBean.selected = true
                        mSelectPlanIndex = pos
                        notifyItemChanged(pos)
                    }
                })
            }

            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext, rvChoosePlanList, mChoosePlanAdapter, bottom = AppUtils.dpToPx(5)
            )

            setOnClickListenerViews(btnSelectChoosePlanContinue)
        }

        mSubscriptionViewModel.getPackageList(packageTypeName)
    }

    override fun liveDataObserve() {
        XEventBus.observe(this, EventName.PayBack) {
            finish()
        }
        mSubscriptionViewModel.mPackageListLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.let { list ->
                        mOrderBean?.let { o ->
                            if (isUpgrade) {
                                val iterator = list.iterator()
                                while (iterator.hasNext()) {
                                    val l = iterator.next()
                                    //根据套餐时间往上升级
                                    if (o.mealUnit == ConstantString.PackageUnitMonth) {
                                        if (l.mealUnit == ConstantString.PackageUnitMonth && o.mealPeriod > l.period) {
                                            iterator.remove()
                                        }
                                    } else if (o.mealUnit == ConstantString.PackageUnitYear) {
                                        if (l.mealUnit == ConstantString.PackageUnitMonth) {
                                            iterator.remove()
                                        } else if (l.mealUnit == ConstantString.PackageUnitYear && o.mealPeriod > l.period) {
                                            iterator.remove()
                                        }
                                    }
//                                    val price =
//                                        if (l.discountedPrice > 0.0) l.discountedPrice else l.planPrice
//                                    val oPrice =
//                                        if (o.mealDiscountPrice > 0.0) o.mealDiscountPrice else o.mealPrice
//                                    if (oPrice >= price) iterator.remove()
//                                    else if (l.mealUnit != ConstantString.PackageUnitYear) iterator.remove()
                                }
                            }
                            if (list.size > 0) {
                                list[0].selected = true
                                mChoosePlanAdapter.setData(list, true)
                            }
                        }
                    }
                }
            })
        }
    }

    private fun goSureSubscriptionPlan() {
        Util.checkLocationPermissionsGpsEnabled(this, {
            Intent(
                mContext, SureSubscriptionPlanActivity::class.java
            ).let {
                if (mChoosePlanAdapter.getData().isNotEmpty()) {
                    val cPlan = mChoosePlanAdapter.getData()[mSelectPlanIndex]
                    it.putExtra(ConstantString.SetMeal, cPlan)
                    it.putExtra(ConstantString.Upgrade, isUpgrade)
                    it.putExtra(ConstantString.LkSetMeal, mOrderBean)
                    it.putExtra(ConstantString.Type, mType)
                    it.putExtra(ConstantString.RechargeType, mRechargeType)
                    startActivity(it)
                }
            }
        })
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnSelectChoosePlanContinue -> goSureSubscriptionPlan()
            }
        }
    }
}