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 WeChatAlipayPayMent @Inject constructor() : DefultPayMentStrategy() {
    private val TAG = "WeChatAlipayPayMent"

    @Inject
    lateinit var mApi: HomeApiService
    /**
     * 发起支付
     */
    override suspend fun pay(params: Map<String, String>)= request<String> {
        twoPayCode(params["name"]!!)
            .catch {
                throw it //传递给下一个catch
            }
            .collect {
                Log.d(TAG, "twoPayCode: $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 {
                    val twoPayCodeBean =
                        gson.fromJson(baseResponse.data, TwoPayCodeBean::class.java)
                    Log.d(TAG, "twoPayCode collect: $twoPayCodeBean")
                    this@request.emit(twoPayCodeBean.rd_Pic)
                }
            }

    }



    //请求支付二维码 二码合一
    private suspend fun twoPayCode(productName: String) = request<String> {
        var map = HashMap<String, String>()
        map["clientId"] = Heartbeat.deviceId!!
        map["productName"] = productName
        mApi.twoPayCode(map).run {
            emit(this)
        }
    }

    private suspend fun carsPay(productName: String)= request<String> {
        val body: RequestBody =
            RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), productName)
        val url:String ="/PAY-SERVER/tOrder/carsPay?="+Heartbeat.deviceId!!
        mApi.carsPay(url,body).run {
            emit(this)
        }
    }


}