package com.abbidot.tracker.adapter

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.list.RecyclerViewHolder
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.bean.SubscriptionsOrderBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.ui.activity.subscribe.ChoosePlanActivity
import com.abbidot.tracker.ui.activity.subscribe.MySubscriptionActivity
import com.abbidot.tracker.ui.activity.subscribe.SubscriptionHistoryActivity
import com.abbidot.tracker.ui.activity.subscribe.SubscriptionPlanActivity
import com.abbidot.tracker.widget.TypefaceTextView
import com.qmuiteam.qmui.skin.QMUISkinManager
import com.qmuiteam.qmui.widget.popup.QMUIPopup
import com.qmuiteam.qmui.widget.popup.QMUIPopups


/**
 *Created  by .yzq on 2024/3/29/029.
 * @link
 * @description:
 */
class MySubscriptionAdapter(
    ctx: Context, list: MutableList<SubscriptionsOrderBean>?
) : BaseRecyclerAdapter<SubscriptionsOrderBean>(ctx, list) {

    private val mMySubscriptionActivity = ctx as MySubscriptionActivity

    override fun getEmptyLayoutId(viewType: Int) = 0

    override fun getItemLayoutId(viewType: Int) = R.layout.item_my_subscription_layout

    override fun bindData(
        holder: RecyclerViewHolder?, position: Int, item: SubscriptionsOrderBean
    ) {
        holder!!.setText(R.id.tv_my_subscription_device_out_id, item.deviceOutId)
//        holder.setText(R.id.tv_my_subscription_plan_name, "${item.mealName}(${item.planCategory})")
        holder.setText(R.id.tv_my_subscription_plan_name, item.mealName)
        holder.getTextView(R.id.tv_my_subscription_auto_subscription_tips).apply {
            visibility = if (item.subscriptionStatus == ConstantInt.Open) {
                text = when (item.mealUnit) {
                    ConstantString.PackageUnitYear -> if (item.mealPeriod > 1) String.format(
                        mContext.getString(R.string.txt_auto_subscription_years),
                        "${item.autoRenewPrice}",
                        "${item.mealPeriod}"
                    ) else String.format(
                        mContext.getString(R.string.txt_auto_subscription_year),
                        "${item.autoRenewPrice}"
                    )

                    ConstantString.PackageUnitDay -> if (item.mealPeriod > 1) String.format(
                        mContext.getString(R.string.txt_auto_subscription_days),
                        "${item.autoRenewPrice}",
                        "${item.mealPeriod}"
                    ) else String.format(
                        mContext.getString(R.string.txt_auto_subscription_day),
                        "${item.autoRenewPrice}"
                    )

                    else -> if (item.mealPeriod > 1) String.format(
                        mContext.getString(R.string.txt_auto_subscription_months),
                        "${item.autoRenewPrice}",
                        "${item.mealPeriod}"
                    ) else String.format(
                        mContext.getString(R.string.txt_auto_subscription_month),
                        "${item.autoRenewPrice}"
                    )
                }
                View.VISIBLE
            } else View.GONE
        }
        holder.setText(
            R.id.tv_my_subscription_active_time,
            Utils.formatTime(item.payTime, Utils.DATE_FORMAT_PATTERN_CN4)
        )

        holder.getTextView(R.id.tv_my_subscription_annual_care).apply {
            text =
                if (item.annualCareType == ConstantInt.Type1) mContext.getString(R.string.start_txt_yes)
                else mContext.getString(R.string.txt_no)
        }

        holder.getTextView(R.id.tv_my_subscription_expires_on).apply {
            text = if (item.orderStatus == 6 && item.refundTime > 0L) {
                Utils.formatTime(item.refundTime, Utils.DATE_FORMAT_PATTERN_CN4)
            } else {
                Utils.formatTime(
                    Utils.timestampAddHowTimestamp(
                        item.payTime, item.mealPeriod, item.mealUnit
                    ), Utils.DATE_FORMAT_PATTERN_CN
                )
            }
        }

        if (item.subscriptionStatus == ConstantInt.Close) {
            holder.setText(
                R.id.tv_my_subscription_auto_renew,
                mContext.getString(R.string.tracker_manage_set_led_off)
            )
        } else {
            holder.setText(
                R.id.tv_my_subscription_auto_renew,
                mContext.getString(R.string.tracker_manage_set_led_on)
            )
        }
        val cTimeMillis = System.currentTimeMillis()
        val endTime = if (item.refundTime == 0L) item.endTime else item.refundTime
        val expiredTime = endTime * 1000 - cTimeMillis
        //是否过期套餐
        val isExpired =
            item.orderStatus == 6 || (item.subscriptionStatus == ConstantInt.Close && expiredTime <= 0)
        val userId = MMKVUtil.getString(MMKVKey.UserId)
        val expiresTitle = holder.getTextView(R.id.tv_my_subscription_expires_title)
        holder.getButton(R.id.btn_my_subscription_recharge).apply {
            visibility = if (isExpired) {
                setText(R.string.txt_card_recharge)
                expiresTitle.setText(R.string.txt_expires_on2)
                View.VISIBLE
            } else if (item.subscriptionStatus == ConstantInt.Close) {
                setText(R.string.txt_enable_auto_renew)
                expiresTitle.setText(R.string.txt_expires_on1)
                View.VISIBLE
            } else {
                expiresTitle.setText(R.string.txt_expires_on1)
                View.GONE
            }

            //UserId不一样就是共享设备的订单
            visibility = if (item.userId == userId) visibility else View.GONE
        }

        holder.getView(R.id.il_my_subscription_count_down).apply {
            visibility = if (isExpired) {
                View.GONE
            } else {
                View.VISIBLE
            }
        }

        val times = Utils.differYear(cTimeMillis, item.endTime)
        holder.getTextView(R.id.tv_add_success_device_expires_days).apply {
            visibility = if (item.subscriptionStatus == ConstantInt.Close) {
                text = times[0]
                View.VISIBLE
            } else View.GONE
            holder.getTextView(R.id.tv_add_device_expires_year_title).visibility = visibility
        }
        holder.getTextView(R.id.tv_add_success_device_expires_hours).apply {
            visibility = if (item.subscriptionStatus == ConstantInt.Close) {
                text = times[1]
                View.VISIBLE
            } else View.GONE
            holder.getTextView(R.id.tv_add_device_expires_month_title).visibility = visibility
        }
        holder.getTextView(R.id.tv_add_success_device_expires_min).apply {
            visibility = if (item.subscriptionStatus == ConstantInt.Close) {
                text = times[2]
                View.VISIBLE
            } else View.GONE
            holder.getTextView(R.id.tv_add_device_expires_day_title).visibility = visibility
        }

        holder.getView(R.id.fl_my_subscription_btn_layout).apply {
            //UserId不一样就是共享设备的订单
            visibility = if (item.userId == userId) {
                setOnClickListener {
                    showPop(holder.getView(R.id.iv_my_subscription_btn), item, position)
                }
                View.VISIBLE
            } else View.GONE
        }
        //充值
        holder.setClickListener(R.id.btn_my_subscription_recharge) {
            if (item.subscriptionStatus == ConstantInt.Close && expiredTime <= 0) {
                Intent(mContext, SubscriptionPlanActivity::class.java).let {
                    it.putExtra(ConstantString.LkSetMeal, item)
                    it.putExtra(ConstantString.RechargeType, ConstantInt.Type2)
                    mMySubscriptionActivity.startActivity(it)
                }
            } else {
                mMySubscriptionActivity.updateSubscriptionStatus(item.subscriptionId, 1, position)
            }
        }
    }

    private fun showPop(v: View, item: SubscriptionsOrderBean, position: Int) {
        val view = LayoutInflater.from(mContext).inflate(R.layout.pop_subscription_item, null)
        val qMUIPopups =
            QMUIPopups.popup(mContext).preferredDirection(QMUIPopup.DIRECTION_BOTTOM).view(view)
//            .edgeProtection(QMUIDisplayHelper.dp2px(mContext, 20))
                .dimAmount(0.6f).arrowSize(AppUtils.dpToPx(6), AppUtils.dpToPx(4))
                .radius(AppUtils.dpToPx(16)).animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                .skinManager(QMUISkinManager.defaultInstance(mContext)).show(v)

        view.findViewById<TypefaceTextView>(R.id.tv_pop_my_subscription_history).apply {
            setOnClickListener {
                qMUIPopups.dismiss()
                Intent(mContext, SubscriptionHistoryActivity::class.java).let {
                    it.putExtra(ConstantString.Id, item.subscriptionId)
                    mMySubscriptionActivity.startActivity(it)
                }
            }
        }
        //升级套餐
        view.findViewById<TypefaceTextView>(R.id.tv_pop_my_subscription_auto_renew).apply {
            val cTimeMillis = System.currentTimeMillis()
            val endTime = if (item.refundTime == 0L) item.endTime else item.refundTime
            val expiredTime = endTime * 1000 - cTimeMillis
            visibility =
                if (item.planCategory == "Premium" || (item.subscriptionStatus == ConstantInt.Close && expiredTime <= 0)) {
                    View.GONE
                } else {
                    View.VISIBLE
                }
            setOnClickListener {
                qMUIPopups.dismiss()
                val intent = Intent(mContext, ChoosePlanActivity::class.java)
                intent.putExtra(ConstantString.Title, "Premium")
                intent.putExtra(ConstantString.Upgrade, true)
                intent.putExtra(ConstantString.RechargeType, ConstantInt.Type2)
                intent.putExtra(ConstantString.LkSetMeal, item)
                mMySubscriptionActivity.startActivity(intent)
            }
        }
        view.findViewById<TypefaceTextView>(R.id.tv_pop_my_subscription_cancel).apply {
            visibility = if (item.subscriptionStatus == ConstantInt.Open) {
                View.VISIBLE
            } else {
                View.GONE
            }
            setOnClickListener {
                qMUIPopups.dismiss()
                mMySubscriptionActivity.updateSubscriptionStatus(item.subscriptionId, 0, position)
            }
        }
    }
}