package com.adealink.weparty.order.refund

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.doOnPreDraw
import androidx.core.view.updateLayoutParams
import androidx.core.view.updatePadding
import com.adealink.frame.aab.util.getCompatDimension
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.BindExtra
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.fitSystemWindows
import com.adealink.weparty.commonui.ext.onWindowInsets
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.module.order.Order
import com.adealink.weparty.module.order.data.OrderDetailData
import com.adealink.weparty.module.order.data.OrderDetailInfo
import com.adealink.weparty.order.databinding.ActivityOrderPlaymateRefundBinding
import com.adealink.weparty.order.refund.comp.PlaymateRefundCustomerComp
import com.adealink.weparty.order.refund.comp.PlaymateRefundPlaymateComp
import com.adealink.weparty.order.viewmodel.OrderViewModel
import com.adealink.weparty.order.viewmodel.OrderViewModelFactory
import com.adealink.weparty.order.viewmodel.PlaymateRefundViewModel
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.R as APP_R

@RouterUri(path = [Order.PlaymateRefund.PATH], desc = "陪玩提交凭证")
class PlaymateEvidenceActivity : BaseActivity() {

    companion object {
        const val PICTURE_SPAN = 3
    }


    @BindExtra(Order.PlaymateRefund.EXTRA_ORDER_ID)
    var orderId: String? = null

    @BindExtra(Order.PlaymateRefund.EXTRA_ORDER_DETAIL)
    var orderInfo: OrderDetailInfo? = null

    private var orderDetail: OrderDetailData? = null

    private val binding by viewBinding(ActivityOrderPlaymateRefundBinding::inflate)
    private val orderViewModel by viewModels<OrderViewModel> { OrderViewModelFactory() }
    private val playmateRefundViewModel by viewModels<PlaymateRefundViewModel> { OrderViewModelFactory() }

    private lateinit var playmateComp: PlaymateRefundPlaymateComp
    override fun onBeforeCreate() {
        super.onBeforeCreate()
        Router.bind(this)
    }

    override fun initViews() {
        super.initViews()
        setContentView(binding.root)
        applyImmersive { top ->
            binding.topBar.setPadding(0, top, 0, 0)
            binding.topBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
                height = top + getCompatDimension(APP_R.dimen.common_top_bar_height).toInt()
            }
        }

        binding.btnRefund.updateLayoutParams<ConstraintLayout.LayoutParams> {
            bottomMargin = getCompatDimension(APP_R.dimen.main_bottom_bar_margin_bottom).toInt()
        }
        binding.clContent.setPadding(
            0, 0, 0,
            getCompatDimension(APP_R.dimen.common_button_height).toInt() + getCompatDimension(APP_R.dimen.main_bottom_bar_margin_bottom).toInt() + 24.dp()
        )
        fitWindow()

        binding.vPlaymate.etInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(
                s: CharSequence?,
                start: Int,
                before: Int,
                count: Int
            ) {
            }

            @SuppressLint("SetTextI18n")
            override fun afterTextChanged(s: Editable?) {
                val input = s?.trim()?.toString()
                binding.btnRefund.isEnabled = !input.isNullOrEmpty()
            }
        })
        binding.btnRefund.isEnabled = false

        binding.btnRefund.onClick {
            refundApply()
        }
    }

    private fun fitWindow() {
        // 关键：只在需要的时候设置
        window?.fitSystemWindows(false)
        // 内容布局处理键盘
        val nsvContent = binding.nsvContent
        binding.nsvContent.onWindowInsets { view, insets ->
            val ime = insets.getInsets(WindowInsetsCompat.Type.ime())
            val nav = insets.getInsets(WindowInsetsCompat.Type.navigationBars())

            // 键盘显示时使用键盘高度，否则使用导航栏高度
            val bottomInset = if (ime.bottom > 0) ime.bottom else nav.bottom
            view.updatePadding(bottom = bottomInset)
            nsvContent.doOnPreDraw {
                nsvContent.smoothScrollTo(0, bottomInset)
            }
            insets
        }
    }

    override fun loadData() {
        super.loadData()
        val orderData = this@PlaymateEvidenceActivity.orderInfo
        if (orderData != null) {
            playmateRefundViewModel.updateOrderDetail(
                OrderDetailData(
                    orderData,
                    null,
                    null,
                    null,
                    null
                )
            )
        }
        val orderId = orderData?.orderId ?: this@PlaymateEvidenceActivity.orderId
        if (!orderId.isNullOrEmpty()) {
            orderViewModel.loadOrderDetail(orderId).observe(this) { rlt ->
                when (rlt) {
                    is Rlt.Failed -> {
                        showFailedToast(rlt)
                    }

                    is Rlt.Success -> {
                        playmateRefundViewModel.updateOrderDetail(rlt.data)
                    }
                }
            }
        }
    }


    override fun initComponents() {
        super.initComponents()
        PlaymateRefundCustomerComp(this, binding.vCustomer).attach()
        PlaymateRefundPlaymateComp(this, binding.vPlaymate).also {
            playmateComp = it
        }.attach()
    }

    private fun refundApply() {
        val orderData = orderInfo ?: return
        showLoading()
        playmateRefundViewModel.playmateRefundEvidence(orderData, playmateComp.getPlaymateReason())
            .observe(this) { rlt ->
                dismissLoading()
                when (rlt) {
                    is Rlt.Failed -> {
                        showFailedToast(rlt)
                    }

                    is Rlt.Success -> {
                        finish()
                    }
                }
            }
    }

}