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

import android.content.Intent
import android.graphics.Paint
import android.view.Gravity
import android.view.View
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.SureSubscribeSummaryAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.MenuTxtBean
import com.abbidot.tracker.bean.PackageBean
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.ActivitySureSubscriptionPlanBinding
import com.abbidot.tracker.ui.activity.WebViewActivity
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.GeoCoderViewModel
import com.abbidot.tracker.vm.GoogleLocationViewModel
import com.abbidot.tracker.vm.SubscriptionManageViewModel
import kotlin.math.abs

class SureSubscriptionPlanActivity :
    BaseActivity<ActivitySureSubscriptionPlanBinding>(ActivitySureSubscriptionPlanBinding::inflate) {

    private val mSubscriptionViewModel: SubscriptionManageViewModel by viewModels()
    private val mGoogleLocationViewModel: GoogleLocationViewModel by viewModels()
    private val mGeoCoderViewModel: GeoCoderViewModel by viewModels()

    private var mPackageBean: PackageBean? = null
    private var mOrderBean: SubscriptionsOrderBean? = null

    //每年的保险服务费用
//    private val mInsuranceMoney = 12.90

    //保险总费用
    private var mSumInsuranceMoney = 0.0

    //税率
    private var mTaxRate = 0.0825

    //付款的总金额(含税)
    private var mTotalWithTaxMoney = 0.0

    //付款的总金额(不含税)
    private var mTotalMoney = 0.0

    //是否是升级套餐
    private var isUpgrade = false

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

    //升级套餐还剩下多少差价
    private var mResidualMoney = 0.0

    //设备类型
    private var mType = ConstantInt.Type1

    private lateinit var mSummaryAdapter: SureSubscribeSummaryAdapter

    override fun getTopBar() = mViewBinding.sureSubscribePlan1TopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_confirm_plan)
        setLeftBackImage(R.drawable.icon_white_back_svg)

        intent.extras?.apply {
            mPackageBean =
                Util.getParcelableAdaptive(intent, ConstantString.SetMeal, PackageBean::class.java)
            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)
        }

        mSummaryAdapter = SureSubscribeSummaryAdapter(this, mutableListOf())

//        mOrderBean?.let {
//            if (isUpgrade) {
//                it.isUpdateOrder = ConstantInt.Type1
//                //套餐总天数
//                val totalDay = if (it.mealUnit == ConstantString.PackageUnitYear) {
//                    it.mealPeriod * 365
//                } else {
//                    30 * it.planTimeMonthsCount
//                }
//                mResidualMoney =
//                    ((it.totalAmountWithTax - it.tax - it.reactivatePrice) / totalDay) * it.surplusDays
//            } else {
//                it.isUpdateOrder = ConstantInt.Type0
//            }
//        }

        mViewBinding.apply {
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext,
                ilSubscribePlanSummary.rvSureSubscribePlanSummary,
                mSummaryAdapter,
                bottom = AppUtils.dpToPx(4)
            )

            //添加下划线
            ilSubscribePlanDetail.tvSureSubscribePlanTermsConditions.paint.flags =
                Paint.UNDERLINE_TEXT_FLAG

            ilSubscribePlanInsurance.cbSureSubscribeInsureSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
                mOrderBean?.let { order ->
                    if (isUpgrade && order.annualCareType == ConstantInt.Type1) {
                        ilSubscribePlanInsurance.cbSureSubscribeInsureSwitch.isChecked = !isChecked
                        showToast(R.string.txt_annual_care_included, gravity = Gravity.CENTER)
                        return@setOnCheckedChangeListener
                    }
                    val list = mSummaryAdapter.getData()
                    if (isChecked) {
                        MenuTxtBean(
                            getString(R.string.txt_annual_care_text), "$mSumInsuranceMoney"
                        ).let {
                            it.colorRedId = R.color.data_black_color
                            list.add(1, it)
                        }
                        mTotalMoney += mSumInsuranceMoney
                    } else {
                        list.removeAt(1)
                        mTotalMoney -= mSumInsuranceMoney
                        mSummaryAdapter.notifyItemRemoved(1)
                    }
                    updateMoney()
                }
            }
            setOnClickListenerViews(
                btnSureSubscribePlan1Continue,
                ilSubscribePlanDetail.tvSureSubscribePlanTermsConditions,
                ilSubscribePlanInsurance.ivSureSubscribePlanInsurance
            )

            if (AppUtils.isChina(AppUtils.SWITCH_MAP_TYPE)) {
                sureSubscriptionDetail()
            } else {
                showNoCancelableLoading(true)
                setButtonEnabled(btnSureSubscribePlan1Continue, ConstantInt.Type0)
                mGoogleLocationViewModel.getLastLocation(mContext)
            }
        }
    }

    private fun sureSubscriptionDetail() {
        mViewBinding.apply {
            showNoCancelableLoading(false)
            ViewUtil.instance.viewShow(svSubscribePlanLayout)
            ViewUtil.instance.viewShow(btnSureSubscribePlan1Continue)
            setButtonEnabled(btnSureSubscribePlan1Continue, ConstantInt.Type1)
            mOrderBean?.let {
                if (isUpgrade) {
                    it.isUpdateOrder = ConstantInt.Type1
                    //套餐总天数
                    val totalDay = if (it.mealUnit == ConstantString.PackageUnitYear) {
                        it.mealPeriod * 365
                    } else {
                        30 * it.planTimeMonthsCount
                    }
                    mResidualMoney = (it.autoRenewPrice / totalDay) * it.surplusDays
                } else {
                    it.isUpdateOrder = ConstantInt.Type0
                }


                ilSubscribePlanDetail.tvSureSubscribePlanDeviceId.text = it.deviceOutId
                val nowTimestamp = System.currentTimeMillis()

                mPackageBean?.let { p ->
                    val autoRenewPrice = Utils.formatDecimal(p.autoRenewPrice, 2)
                    ilSubscribePlanDetail.tvSureSubscribePlanPer.text =
                        if (p.mealUnit == ConstantString.PackageUnitDay) String.format(
                            getString(R.string.txt_day_unit), "${p.planTimeMonthsCount}"
                        )
                        else String.format(
                            getString(R.string.txt_month_unit), "${p.planTimeMonthsCount}"
                        )
                    val renewalString = if (p.mealUnit == ConstantString.PackageUnitYear) {
                        val renewalTimestamp = Utils.timestampAddHowTimestamp(
                            nowTimestamp, p.period, ConstantString.PackageUnitYear
                        )
                        val renewalDate =
                            Utils.formatTime(renewalTimestamp, Utils.DATE_FORMAT_PATTERN_CN)
                        if (p.planTimeMonthsCount > 12) {
                            String.format(
                                getString(R.string.txt_renewal_years),
                                autoRenewPrice,
                                "${p.period}",
                                renewalDate
                            )
                        } else {
                            String.format(
                                getString(R.string.txt_renewal_year), autoRenewPrice, renewalDate
                            )
                        }
                    } else if (p.mealUnit == ConstantString.PackageUnitDay) {
                        val renewalTimestamp =
                            Utils.getAfterHowTimestamp(nowTimestamp, p.period.toLong())
                        val renewalDate =
                            Utils.formatTime(renewalTimestamp, Utils.DATE_FORMAT_PATTERN_CN)
                        String.format(
                            getString(R.string.txt_renewal_day),
                            autoRenewPrice,
                            "${p.period}",
                            renewalDate
                        )
                    } else {
                        val renewalTimestamp = Utils.timestampAddHowTimestamp(
                            nowTimestamp, p.planTimeMonthsCount, ConstantString.PackageUnitMonth
                        )
                        val renewalDate =
                            Utils.formatTime(renewalTimestamp, Utils.DATE_FORMAT_PATTERN_CN)
                        if (p.planTimeMonthsCount > 1) {
                            String.format(
                                getString(R.string.txt_renewal_months),
                                autoRenewPrice,
                                "${p.planTimeMonthsCount}",
                                renewalDate
                            )
                        } else {
                            String.format(
                                getString(R.string.txt_renewal_month), autoRenewPrice, renewalDate
                            )
                        }
                    }
                    ilSubscribePlanDetail.tvSureSubscribePlanUnderused.text = renewalString
                    ilSubscribePlanDetail.tvSureSubscribePlanMoneySum.text =
                        String.format(getString(R.string.txt_money_unit), autoRenewPrice)

//                    val packageName = "${p.planName}(${p.planCategory})"
                    ilSubscribePlanDetail.tvSureSubscribePlanName.text = p.planName
                    val price = p.planPrice
//                    val price = if (p.discountedPrice > 0.0) p.discountedPrice else p.planPrice
                    val priceString = String.format(
                        getString(R.string.txt_money_unit),
                        Utils.formatDecimal(price / p.planTimeMonthsCount, 2)
                    )
                    ilSubscribePlanDetail.tvSureSubscribePlanMoney.text = priceString

                    ViewUtil.instance.addMenuBean(
                        mSummaryAdapter.getData(),
                        p.planName,
                        Utils.formatDecimal(p.planPrice, 2),
                        colorRedId = R.color.data_black_color
                    )
                    mTotalMoney += price
                    //保险时长，不足一年按12个月算
                    val insuranceTime =
                        if (p.planTimeMonthsCount > 12) p.planTimeMonthsCount else 12
                    mSumInsuranceMoney =
                        Utils.formatDecimal(p.everyMonthSafeFee * insuranceTime, 2).toDouble()
                    ViewUtil.instance.addMenuBean(
                        mSummaryAdapter.getData(),
                        getString(R.string.txt_annual_care_text),
                        "$mSumInsuranceMoney",
                        colorRedId = R.color.data_black_color
                    )
                    mTotalMoney += mSumInsuranceMoney

                    val insuranceMoneyString =
                        String.format(getString(R.string.txt_month_unit), "$insuranceTime")
                    ilSubscribePlanInsurance.tvSureSubscribePlanInsurancePer.text =
                        insuranceMoneyString
                    ilSubscribePlanInsurance.tvSureSubscribePlanInsurancePerMoney.text =
                        String.format(getString(R.string.txt_money_unit), "${p.everyMonthSafeFee}")
                    ilSubscribePlanInsurance.tvSureSubscribePlanInsuranceMoney.text =
                        String.format(getString(R.string.txt_money_unit), "$mSumInsuranceMoney")

                    if (isUpgrade) {
                        mTotalMoney -= mResidualMoney
                        ViewUtil.instance.addMenuBean(
                            mSummaryAdapter.getData(),
                            getString(R.string.txt_residual_value),
                            Utils.formatDecimal(mResidualMoney, 2),
                            colorRedId = R.color.red_color5,
                            isSwitch = true
                        )
                    }
//                    ViewUtil.instance.addMenuBean(
//                        mSummaryAdapter.getData(),
//                        getString(R.string.txt_sales_tax),
//                        "0",
//                        colorRedId = R.color.data_black_color
//                    )
                }

                //判断套餐是否过期 或者套餐没退款
//                if (!TextUtils.isEmpty(it.orderNum) && it.orderStatus != 6 && it.surplusDays == 0L && it.subscriptionStatus == ConstantInt.Close) {
////                    mOrderBean?.reactivation = 1
//                    mSubscriptionViewModel.getReactivationFee(it.orderNum)
//                } else {
//                    if (isUpgrade) mSubscriptionViewModel.getReactivationFee(it.orderNum)
//                    else {
//                        mOrderBean?.reactivation = 0
//                        mOrderBean?.reactivatePrice = 0.0
//                        updateMoney()
//                    }
//                }

                mOrderBean?.reactivation = 0
                mOrderBean?.reactivatePrice = 0.0
                updateMoney()
                //隐藏保险
                mViewBinding.ilSubscribePlanInsurance.cbSureSubscribeInsureSwitch.isChecked = false

            }
        }
    }

    override fun liveDataObserve() {
        XEventBus.observe(this, EventName.PayBack) {
            if (isUpgrade) {
                //升级套餐成功
                MMKVUtil.putInt(MMKVKey.MealType, ConstantInt.PremiumPackage)
            }
            //通知首页刷新宠物信息，防止没有加载,显示Fragment使用老的套餐数据,升级套餐和套餐过期充值使用
            XEventBus.post(EventName.RefreshPackage)
            finish()
        }
        mSubscriptionViewModel.apply {
            mReactivationFeeLiveData.observe(this@SureSubscriptionPlanActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            mPackageBean?.let { p ->
                                mTotalMoney -= mSumInsuranceMoney
                                if (isUpgrade) {
                                    //升级套餐，把之前剩余保险费退还，再重新买1年的保险
                                    mTotalMoney -= surplusSafeValidFee
                                    mResidualMoney = Utils.formatDecimal(
                                        mResidualMoney + surplusSafeValidFee, 2
                                    ).toDouble()
                                    val insuranceTime =
                                        if (p.planTimeMonthsCount > 12) p.planTimeMonthsCount else 12
                                    val insuranceMoneyString = String.format(
                                        getString(R.string.txt_month_unit), "$insuranceTime"
                                    )
                                    mViewBinding.ilSubscribePlanInsurance.tvSureSubscribePlanInsurancePer.text =
                                        insuranceMoneyString
                                    mSumInsuranceMoney =
                                        Utils.formatDecimal(p.everyMonthSafeFee * insuranceTime, 2)
                                            .toDouble()
                                    mTotalMoney += mSumInsuranceMoney
                                    mViewBinding.ilSubscribePlanInsurance.tvSureSubscribePlanInsuranceMoney.text =
                                        String.format(
                                            getString(R.string.txt_money_unit),
                                            "$mSumInsuranceMoney"
                                        )
                                    mSummaryAdapter.getData()[2].menuValue = "$mResidualMoney"
                                } else {
                                    val howSafeValidMonths =
                                        p.planTimeMonthsCount - surplusSafeValidMonths
                                    if (howSafeValidMonths > 0) {
                                        val insuranceMoneyString = String.format(
                                            getString(R.string.txt_month_unit),
                                            "$howSafeValidMonths"
                                        )
                                        mViewBinding.ilSubscribePlanInsurance.tvSureSubscribePlanInsurancePer.text =
                                            insuranceMoneyString
                                        mSumInsuranceMoney = Utils.formatDecimal(
                                            howSafeValidMonths * p.everyMonthSafeFee, 2
                                        ).toDouble()
                                        mTotalMoney += mSumInsuranceMoney
                                        mViewBinding.ilSubscribePlanInsurance.tvSureSubscribePlanInsuranceMoney.text =
                                            String.format(
                                                getString(R.string.txt_money_unit),
                                                "$mSumInsuranceMoney"
                                            )
                                    } else {
                                        mSumInsuranceMoney = 0.0
                                        mViewBinding.ilSubscribePlanInsurance.root.visibility =
                                            View.GONE
                                    }
                                }
                                mSummaryAdapter.getData()[1].menuValue = "$mSumInsuranceMoney"
                            }
                        }
                        updateMoney()
                    }
                })
            }

            mRegionalTaxRateLiveData.observe(this@SureSubscriptionPlanActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            mTaxRate = taxRate
                            sureSubscriptionDetail()
                        }
                    }
                })
            }
        }
        mGoogleLocationViewModel.mGoogleLocationLiveData.observe(this) {
            mGeoCoderViewModel.getLatLonAddress(it.latitude, it.longitude)
        }
        mGeoCoderViewModel.mLatLonAddressLiveData.observe(this) {
            mSubscriptionViewModel.getTaxRateByRegionName(
                mGeoCoderViewModel.mCountryCode, mGeoCoderViewModel.mRegion
            )
        }
    }

    private fun updateMoney() {
        mViewBinding.apply {
            val list = mSummaryAdapter.getData()
//            val taxMoney = abs(Utils.formatDecimal(mTaxRate * mTotalMoney, 2).toDouble())
            val taxMoney = 0.0
            mOrderBean?.tax = taxMoney
//            list[list.size - 1].menuValue = taxMoney.toString()
            mTotalWithTaxMoney = taxMoney + mTotalMoney
            mTotalWithTaxMoney = abs(mTotalWithTaxMoney)
            ilSubscribePlanSummary.ilSureSubscribePlanTotalLayout.tvSubscribeSummaryItemMoney.text =
                String.format(
                    getString(R.string.txt_money_unit), Utils.formatDecimal(mTotalWithTaxMoney, 2)
                )
            mSummaryAdapter.notifyItemRangeChanged(0, list.size)

            //NestedScrollView缓慢自动滑倒底部
            svSubscribePlanLayout.post {
                svSubscribePlanLayout.smoothScrollTo(0, svSubscribePlanLayout.bottom)
            }
//           svSubscribePlanLayout.post { svSubscribePlanLayout.pageScroll(View.FOCUS_DOWN) }
        }
    }

    private fun createOrder() {
        mOrderBean?.apply {
            username = MMKVUtil.getString(MMKVKey.UserName)
            annualCareType =
                if (mViewBinding.ilSubscribePlanInsurance.cbSureSubscribeInsureSwitch.isChecked) {
                    annualCarePrice = mSumInsuranceMoney
                    1
                } else {
                    annualCarePrice = 0.0
                    0
                }
            //是否使用优惠码 1:是 0:否
            useCoupon = 0
            couponCode = ""
            couponPrice = 0.0
            mPackageBean?.let { cPlan ->
                mealPrice = cPlan.planPrice
                mealDiscountPrice = cPlan.discountedPrice
                mealName = cPlan.planName
                mealId = cPlan.mealId
                mealPeriod = cPlan.period
                planTimeMonthsCount = cPlan.planTimeMonthsCount
                mealUnit = cPlan.mealUnit
                planCategory = cPlan.planCategory
                autoRenewPrice =
                    Utils.formatDecimal(cPlan.autoRenewPrice + cPlan.autoRenewPrice * mTaxRate, 2)
                        .toDouble()
//                autoRenewPrice = cPlan.autoRenewPrice
                mealDesc =
                    mViewBinding.ilSubscribePlanDetail.tvSureSubscribePlanMoney.text.toString() + mViewBinding.ilSubscribePlanDetail.tvSureSubscribePlanPer.text.toString()
            }
            totalAmountWithTax = Utils.formatDecimal(mTotalWithTaxMoney, 2).toDouble()
            Intent(mContext, PaymentMethodActivity::class.java).let {
                it.putExtra(ConstantString.LkSetMeal, this)
                it.putExtra(ConstantString.Type, mType)
                it.putExtra(ConstantString.RechargeType, mRechargeType)
                startActivity(it)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnSureSubscribePlan1Continue -> createOrder()
                ilSubscribePlanDetail.tvSureSubscribePlanTermsConditions -> {
                    val url = if (AppUtils.isChina()) {
                        "file:///android_asset/subscription_terms_conditions_en.html"
                    } else {
                        "file:///android_asset/subscription_terms_conditions_en.html"
                    }
                    WebViewActivity.startWebViewActivity(
                        mActivity, getString(R.string.txt_service_contract), url
                    )
                }

                ilSubscribePlanInsurance.ivSureSubscribePlanInsurance -> {
                    val url = if (AppUtils.isChina()) {
                        "file:///android_asset/annual_protection_plan_en.html"
                    } else {
                        "file:///android_asset/annual_protection_plan_en.html"
                    }
                    WebViewActivity.startWebViewActivity(
                        mActivity, getString(R.string.txt_service_contract), url
                    )
                }
            }
        }
    }
}