package com.swago.user.recharge

import android.graphics.Rect
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.billingclient.api.Purchase
import com.swago.baseswago.PayVm
import com.swago.baseswago.activity.BaseXActivity
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.dialog.OrderLostDialog
import com.swago.baseswago.dialog.RechargeAdapter
import com.swago.baseswago.libpay.IPayCallback
import com.swago.baseswago.libpay.PayManager
import com.swago.baseswago.model.pay.PayModel
import com.swago.baseswago.util.*
import com.swago.user.R
import com.swago.user.databinding.ActivityRechargeBinding

/**
 *@date 2021/11/24 21:06
 *description:
 */
@Route(path = ARouteConstant.User.recharge)
class RechargeActivity : BaseXActivity<ActivityRechargeBinding>(), IPayCallback {


    private val payVm by viewModels<PayVm>()

    private val adapter by lazy {
        RechargeAdapter()
    }

    private var selectedPosition = 0

    override fun loadData() {
        SwagoLoading.showLoadingDialog(this)
        payVm.getProductList()
    }

    override fun initOther() {
        PayManager.listener.add(this)
        setBackView(binding.toolbar.ivBack)
        binding.toolbar.tvTitle.text =
            AppContext.getContext().resources.getString(R.string.recharge)

        UserInfo.getUserInfo()?.let {
            binding.tvBalanceCount.text = it.user_coins
        }

        binding.rv.layoutManager = GridLayoutManager(this, 3)
        binding.rv.addItemDecoration(GridItemDecoration())
        binding.rv.adapter = adapter

        adapter.setOnItemClickListener { _, _, position ->
            if (selectedPosition != position) {
                adapter.data[selectedPosition].isSelected = false
                adapter.data[position].isSelected = true
                adapter.notifyItemChanged(selectedPosition)
                adapter.notifyItemChanged(position)
                selectedPosition = position
            }
        }

        binding.btRecharge.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                //先去查询是否有未消费的订单
                if (adapter.data.size>selectedPosition){
                    SwagoLoading.showLoadingDialog(this@RechargeActivity)
                    PayManager.queryUnConsumeOrder(adapter.data[selectedPosition].id)
                }
            }
        })

    }


    override fun initLiveData() {
        payVm.coinLiveData.observe(this) {
            binding.tvBalanceCount.text = it.user_coins
        }
    }

    inner class GridItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val itemPosition = (view.layoutParams as RecyclerView.LayoutParams).viewLayoutPosition
            val column = itemPosition % 3
            val margin = DpPxUtil.dip2px(20f)
            val middle = DpPxUtil.dip2px(5f)
            val bottom = DpPxUtil.dip2px(15f)
            when (column) {
                0 -> {
                    outRect.set(margin, 0, middle, bottom)
                }

                1 -> {
                    outRect.set(middle, 0, middle, bottom)
                }

                2 -> {
                    outRect.set(middle, 0, margin, bottom)
                }
            }
        }
    }

    override fun onDestroy() {
        PayManager.listener.remove(this)
        super.onDestroy()
    }

    override fun onConnectedServer() {
    }

    override fun onPaySuccess(data: List<Purchase>?) {
        data?.forEach {
            SwagoLoading.showLoadingDialog(this)
            payVm.payOrderToServer(it, 1)
        }
    }

    override fun onQueryProductPrice(data: List<PayModel>) {
        SwagoLoading.cancelLoadingDialog()
        adapter.setNewData(data)
        PayManager.queryUnConsumeOrder("")
    }

    override fun onPayError(code: Int) {
        SwagoLoading.cancelLoadingDialog()
        Toast.makeText(AppContext.getContext(), AppContext.getContext().resources.getString(R.string.pay_fail)+"-$code", Toast.LENGTH_SHORT).show()
        payVm.payOrderToServer(null, 2)
    }

    override fun onPayCancel() {
        Toast.makeText(AppContext.getContext(), AppContext.getContext().resources.getString(R.string.pay_cancel), Toast.LENGTH_SHORT).show()
        payVm.payOrderToServer(null, 3)
    }

    override fun onUnConsumeOrder(data: List<Purchase>) {
        data.forEach {
            val orderLostDialog = OrderLostDialog.newInstance(it.orderId)
            orderLostDialog.commitLostOrderFun = {
                payVm.payOrderToServer(it,4)
            }
            orderLostDialog.show(supportFragmentManager, "OrderLostDialog")
        }
    }

    override fun consumeOrderSuccess() {

    }

    override fun consumeOrderFail(code: Int) {

    }

    override fun toCreateNewOrder(productId: String) {
        payVm.createOrder(productId)
    }
}