package com.quyunshuo.module.home.fragment.vm

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.quyunshuo.androidbaseframemvvm.base.mvvm.vm.BaseViewModel
import com.quyunshuo.androidbaseframemvvm.common.bean.ShoppingCartBean
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import com.quyunshuo.module.home.fragment.repo.QrCodeFragmentRepo
import com.quyunshuo.module.home.pay.PaymentService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * HomeFragment 的 VM 层
 *
 * @author Qu Yunshuo
 * @since 2021/8/5 11:11 下午
 */
@HiltViewModel//@HiltViewModel 注解的作用是将 ViewModel 标记为可以由 Hilt 管理的依赖项。当你将 @HiltViewModel 注解添加到 ViewModel 类上时，Hilt 会自动处理 ViewModel 的创建和注入过程。这样，你就不需要手动调用 ViewModelProvider 来获取 ViewModel 实例了。
class QrCodeFragmentVM @Inject constructor(private val mRepo: QrCodeFragmentRepo) :
    BaseViewModel() {
    private val TAG = "BuyFragmentVM"

    //position
    private var _qrCode = MutableLiveData<String>()//
    val qrCode: LiveData<String> get() = _qrCode


    @Inject
    lateinit var paymentService: PaymentService

    /**
     * 微信支付宝 获取二维码
     */
    fun twoPayCode(selectPro: String?) {
        viewModelScope.launch(Dispatchers.IO) {
            val paymentStrategy = paymentService.getPaymentStrategy("weChatAlipayPayMent")
            val map = HashMap<String, String>()
            map["name"] = selectPro!!
            paymentStrategy.pay(map).catch {
                Log.d(TAG, "twoPayCode1 catch: " + it.message)
                withContext(Dispatchers.Main) { _qrCode.value = "" }
            }.collect {
                Log.d(TAG, "twoPayCode1: $it")
                withContext(Dispatchers.Main) { _qrCode.value = it }
            }

        }

    }

    /**
     * 微信支付宝 购物车版本
     * {"美梦成真-1":"[\"0\"]","一见钟情-1":"[\"0\"]"}
     */
    @Deprecated("使用新的方法，有优惠码的：promotionCode")
    fun twoPayCodeShoppingCart(shoppingCartBean: ArrayList<ShoppingCartBean>){
        viewModelScope.launch(Dispatchers.IO) {
            val paymentStrategy = paymentService.getPaymentStrategy("WeChatAlipayPayShoppingCartMent")
            val map = HashMap<String, String>() // 组合：{"美梦成真-1":"[\"0\"]","一见钟情-1":"[\"0\"]"}
            val codes = ArrayList<String>() //优惠码的数据

            shoppingCartBean.forEach {
                codes.clear()
                for (i in 0 until it.count) {
                    codes.add("0")
                }
                map[""+it.nameChinese+"-"+it.count] = Gson().toJson(codes)
            }
            Log.d(TAG, "twoPayCodeShoppingCart: "+Gson().toJson(map))
            paymentStrategy.pay(map).catch {
                Log.d(TAG, "twoPayCodeShoppingCart catch: " + it.message)
                withContext(Dispatchers.Main) { _qrCode.value = "" }
            }.collect {
                Log.d(TAG, "twoPayCodeShoppingCart1: $it")
                withContext(Dispatchers.Main) { _qrCode.value = it }
            }
        }
    }

    /**
     * 微信支付宝 购物车版本
     * {"美梦成真-1":"[\"0\"]","一见钟情-1":"[\"0\"]"}
     */
    fun twoPayCodeShoppingCart(
        shoppingCartBean: java.util.ArrayList<ShoppingCartBean>,
        promotionCode: String?,
    ) {
        viewModelScope.launch(Dispatchers.IO) {
            val paymentStrategy = paymentService.getPaymentStrategy("WeChatAlipayPayShoppingCartMent")
            val map = HashMap<String, String>() // 组合：{"美梦成真-1":"[\"0\"]","一见钟情-1":"[\"0\"]"}
            val codes = ArrayList<String>() //优惠码的数据
            val proCodes = promotionCode?.split(".")
            //作为优惠码的索引
            var shoppingCartNumber = 0
            shoppingCartBean.forEach {
                codes.clear()
                for (i in 0 until it.count) {
                    //是否存在优惠码 如果存在则使用，如果不存在则添加0
                    if (proCodes?.size!!>0 && shoppingCartNumber<proCodes.size){
                        var proCode =proCodes[shoppingCartNumber].toString()
                        if (proCode==""){
                            codes.add("0")
                        }else{
                            codes.add(proCodes[shoppingCartNumber].toString())
                        }
                    }else{
                        codes.add("0")
                    }
                    shoppingCartNumber++
                }
                map[""+it.productNo+"-"+it.count] = Gson().toJson(codes)
            }
            Log.d(TAG, "twoPayCodeShoppingCart: "+Gson().toJson(map))
            paymentStrategy.pay(map).catch {
                Log.d(TAG, "twoPayCodeShoppingCart catch: " + it.message)
                withContext(Dispatchers.Main) { _qrCode.value = "" }
            }.collect {
                Log.d(TAG, "twoPayCodeShoppingCart collect: $it")

                withContext(Dispatchers.Main) {
                    when (it) {
                        "0"-> {_qrCode.value = it}
                        "1"-> {_qrCode.value = "优惠码不存在哦"}
                        "2"-> {_qrCode.value = "优惠码已使用了哦"}
                        "3"-> {_qrCode.value = "此优惠码不是这个商家的哦"}
                        "4"-> {_qrCode.value = "优惠码过期了哦"}
                        else -> {
                            _qrCode.value = it
                        }                        }


                }
            }
        }
    }


}