package com.swago.baseswago.dialog

import android.graphics.Rect
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.billingclient.api.Purchase
import com.swago.baseswago.PayVm
import com.swago.baseswago.R
import com.swago.baseswago.databinding.DialogPayBinding
import com.swago.baseswago.libpay.IPayCallback
import com.swago.baseswago.libpay.PayManager
import com.swago.baseswago.model.pay.PayModel
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.DpPxUtil
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.baseswago.util.SwagoLoading

/**
 *@date 2021/12/18 09:14
 *description:
 */
class PayDialog : BaseXDFragment<DialogPayBinding>(), IPayCallback {

    private val payVm by viewModels<PayVm>()
    private val adapter by lazy {
        RechargeAdapter()
    }

    private var selectedPosition = 0

    init {
        setGravity(Gravity.BOTTOM)
        setDimAmount(0f)
    }


    companion object{
        fun newInstance():PayDialog{
            val dialog = PayDialog()
            val bundle = Bundle()
            dialog.arguments = bundle
            return dialog
        }
    }

    override fun initOther() {
        PayManager.listener.add(this)
        binding.recyclerView.layoutManager = GridLayoutManager(context, 3)
        binding.recyclerView.addItemDecoration(GridItemDecoration())
        binding.recyclerView.adapter = adapter

        payVm.getCoins()
        payVm.getProductList()

        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.tvRecharge.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                if(adapter.data.size>selectedPosition){
                    activity?.let {
                        SwagoLoading.showLoadingDialog(it)
                    }
                    PayManager.queryUnConsumeOrder(adapter.data[selectedPosition].id)
                }
            }

        })

    }

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

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

    override fun onConnectedServer() {
    }

    override fun onPaySuccess(data: List<Purchase>?) {
        data?.forEach {
            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(childFragmentManager, "OrderLostDialog")
        }
    }

    override fun consumeOrderSuccess() {

    }

    override fun consumeOrderFail(code: Int) {

    }

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

    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)
                }
            }
        }
    }
}