package com.abbidot.tracker.adapter

import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
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.constant.MultipleEntity
import com.abbidot.tracker.ui.activity.subscribe.RequestRefundActivity
import com.abbidot.tracker.ui.activity.subscribe.SubscriptionHistoryActivity
import com.abbidot.tracker.widget.TypefaceRoundButton
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.hjq.toast.Toaster
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButtonDrawable

/**
 *Created  by .yzq on 2024/8/19/019.
 * @link
 * @description:
 */
class SubscriptionHistoryAdapter(
    list: MutableList<SubscriptionsOrderBean>?
) : BaseMultiItemQuickAdapter<SubscriptionsOrderBean, BaseViewHolder>(list) {

    private lateinit var mHistoryActivity: SubscriptionHistoryActivity

    init {
        addItemType(MultipleEntity.TEXT, R.layout.item_subscription_history_layout)
        addItemType(MultipleEntity.IMG, R.layout.item_annual_care_history_layout)
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        mHistoryActivity = context as SubscriptionHistoryActivity
    }

    override fun convert(holder: BaseViewHolder, item: SubscriptionsOrderBean) {
//        val position = getItemPosition(item)
        when (item.itemType) {
            MultipleEntity.TEXT -> bindOrderData(holder, item)
            MultipleEntity.IMG -> bindAnnualCareData(holder, item)
        }
    }

    /**
     * 保险订单
     */
    private fun bindAnnualCareData(holder: BaseViewHolder, item: SubscriptionsOrderBean) {
        holder.setText(
            R.id.tv_subscription_annual_care_order_id,
            context.getString(R.string.txt_order_id) + item.orderNum
        )
        val cTimeMillis = System.currentTimeMillis()
        val endTime = if (item.refundTime == 0L) item.endTime else item.refundTime
        val expiredTime = endTime * 1000 - cTimeMillis
        val state =
            if (item.enabled == ConstantInt.Type0 || (item.subscriptionStatus == ConstantInt.Close && expiredTime <= 0)) {
                context.getString(R.string.txt_expired)
            } else {
                context.getString(R.string.txt_active)
            }
        holder.setText(R.id.tv_subscription_annual_care_state, state)
        holder.setText(
            R.id.tv_subscription_annual_care_active_time, Utils.formatTime(
                item.payTime, Utils.DATE_FORMAT_PATTERN_CN
            )
        )
        //保险时长，不足一年按12个月算
        val insuranceTime =
            if (item.mealUnit == ConstantString.PackageUnitYear) item.mealPeriod else 1
        holder.setText(
            R.id.tv_subscription_annual_care_expiry_time, Utils.formatTime(
                Utils.timestampAddHowTimestamp(
                    item.payTime, insuranceTime, ConstantString.PackageUnitYear
                ), Utils.DATE_FORMAT_PATTERN_CN
            )
        )
        holder.setText(
            R.id.tv_subscription_annual_care_package,
            String.format(context.getString(R.string.txt_year_care), "$insuranceTime")
        )
        holder.setText(
            R.id.tv_subscription_annual_care_price,
            String.format(context.getString(R.string.txt_money_unit), "${item.annualCarePrice}")
        )
    }

    private fun bindOrderData(holder: BaseViewHolder, item: SubscriptionsOrderBean) {
        holder.setText(
            R.id.tv_subscription_history_order_id,
            context.getString(R.string.txt_order_id) + item.orderNum
        )
        holder.setText(
            R.id.tv_subscription_history_order_time,
            Utils.formatTime(item.payTime, Utils.DATE_FORMAT_PATTERN_CN2)
        )
        holder.setText(R.id.tv_subscription_history_package_name, item.mealName)
        holder.setText(
            R.id.tv_subscription_history_package_price,
            String.format(context.getString(R.string.txt_money_unit), "${item.totalAmountWithTax}")
        )


        (holder.getView(R.id.btn_subscription_history_operate) as TypefaceRoundButton).apply {

            setTextColor(ContextCompat.getColor(context, R.color.line_color1))

            if (item.enabled == ConstantInt.Type0) visibility = View.GONE
            else {
                visibility = View.VISIBLE
                when (item.orderStatus) {
                    1 -> {
                        if (item.isAutoRenewal == ConstantInt.Type1) {
                            visibility = View.GONE
                        } else {
                            setRefundState(context, item.isRefundable, this)
                        }

//                        val updateTimestamp = Utils.stringToTimestamp(item.updateTime, isUtc = true)
//                        val nowTimestamp = System.currentTimeMillis()
//                        if (item.enabled == ConstantInt.Type0 || (item.surplusDays == 0L && item.subscriptionStatus == ConstantInt.Close)) {
//                            visibility = View.GONE
//                        } else if (item.mealUnit == ConstantString.PackageUnitDay) {
//                            visibility = View.VISIBLE
//                            setText(R.string.txt_refund)
//                        } else if (item.mealUnit == ConstantString.PackageUnitMonth) {
//                            val day7Timestamp = 7 * 24 * 60 * 60 * 1000L
//                            //套餐超出7天不能退款
//                            if (nowTimestamp - updateTimestamp <= day7Timestamp) {
//                                visibility = View.VISIBLE
//                                setText(R.string.txt_refund)
//                            } else {
//                                visibility = View.GONE
//                            }
//                        } else {
//                            val day30Timestamp = 30 * 24 * 60 * 60 * 1000L
//                            //套餐超出30天不能退款
//                            if (nowTimestamp - updateTimestamp <= day30Timestamp) {
//                                visibility = View.VISIBLE
//                                setText(R.string.txt_refund)
//                            } else {
//                                visibility = View.GONE
//                            }
//                        }
//                        setTextColor(ContextCompat.getColor(context, R.color.select_color))
                    }

                    4 -> setText(R.string.txt_waiting)
                    5 -> setText(R.string.txt_refunding)
                    6 -> setText(R.string.txt_refunded)
                    7, 8 -> {
                        setTextColor(ContextCompat.getColor(context, R.color.orange_red_color))
                        setText(R.string.txt_rejected)
                    }

                    else -> visibility = View.GONE
                }
            }

            setChangeAlphaWhenPress(true)
            setOnClickListener {
                if (item.orderStatus == ConstantInt.Type1) {
                    if (item.isRefundable == ConstantInt.Type0) {
                        Toaster.show(R.string.txt_refund_expired)
                        return@setOnClickListener
                    }
                    Intent(context, RequestRefundActivity::class.java).apply {
                        putExtra(ConstantString.SetMeal, item)
                        mHistoryActivity.startActivity(this)
                    }
                }
            }
        }

        val cTimeMillis = System.currentTimeMillis()
        val endTime = if (item.refundTime == 0L) item.endTime else item.refundTime
        val expiredTime = endTime * 1000 - cTimeMillis
        val state = if (item.enabled == ConstantInt.Type0 || (expiredTime <= 0)) {
            context.getString(R.string.txt_expired)
        } else {
            context.getString(R.string.txt_active)
        }
        holder.setText(R.id.tv_subscription_history_subscription_state, state)

        holder.getView<TextView>(R.id.tv_subscription_history_annual_care).apply {
            text =
                if (item.annualCareType == ConstantInt.Type1) context.getString(R.string.start_txt_yes)
                else context.getString(R.string.txt_no)
        }
    }

    private fun setRefundState(
        context: Context, isRefundable: Int, roundButton: TypefaceRoundButton
    ) {
        roundButton.apply {
            var textColor = R.color.select_color
            val strokeColor = if (isRefundable == ConstantInt.Type1) {
                R.color.block_color
            } else {
                textColor = R.color.line_color1
                R.color.permission_no_check_color
            }
            (background as QMUIRoundButtonDrawable).let {
                it.setStroke(
                    it.strokeWidth, ContextCompat.getColor(context, strokeColor)
                )
            }
            setTextColor(ContextCompat.getColor(context, textColor))
        }
    }

}