package com.quyunshuo.module.home.pay

import android.util.Log
import com.google.gson.Gson
import com.module.pay.service.HomeApiService
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.module.home.bean.TwoPayCodeBean
import com.quyunshuo.wanandroid.common.bean.BaseResponse
import kotlinx.coroutines.flow.catch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import javax.inject.Inject

/**
 * 微信支付宝 购物车支付 类
 */
class WeChatAlipayPayShoppingCartMent @Inject constructor() : DefultPayMentStrategy() {
    private val TAG = "WeChatAlipayPayMent"

    @Inject
    lateinit var mApi: HomeApiService
    /**
     * 发起支付
     */
    override suspend fun pay(params: Map<String, String>)= request<String> {
        carsPay(Gson().toJson(params))
            .catch {
                throw it //传递给下一个catch
            }
            .collect {
                Log.d(TAG, "twoPayCodeShoppingCart2: $it")
                val gson = Gson()
                val baseResponse: BaseResponse<String> =
                    gson.fromJson(it, BaseResponse::class.java) as BaseResponse<String>
                if (baseResponse.data == null) {
                    this@request.emit(baseResponse.errmsg)
                    ToastUtil.switchToastStyleToError(baseResponse.errmsg)
                } else {
                    //todo 优惠码这里解析不了。因为是1 2 3这些数字，而不是一个json，所以需要做额外的处理
                    when (it) {
                        "0","1","2","3","4" -> {
                            this@request.emit(baseResponse.data)
                        }
                        else -> {
                            val twoPayCodeBean =
                                gson.fromJson(baseResponse.data, TwoPayCodeBean::class.java)
                            Log.d(TAG, "twoPayCodeShoppingCart collect: $twoPayCodeBean")
                            this@request.emit(twoPayCodeBean.rd_Pic)
                        }
                    }

                }
            }

    }



    private suspend fun carsPay(productName: String)= request<String> {
        Log.d("backinfo","设备id"+Heartbeat.deviceId)
        val body: RequestBody =
            RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), productName)
        val url:String ="/PAY-SERVER/tOrder/newCarsPay?clientId="+Heartbeat.deviceId!!

        Log.d(TAG, "carsPay: $url")
        mApi.carsPay(url,body).run {
            emit(this)
        }
    }


}