package com.gingersoft.gsa.delivery_pick_mode.data

import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils
import com.gingersoft.gsa.delivery_pick_mode.data.model.bean.DeliveryConfig
import com.gingersoft.gsa.delivery_pick_mode.data.network.DeliveryNetwork
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.FormBody
import okhttp3.MediaType
import okhttp3.RequestBody

class DeliveryRepository private constructor(private val network: DeliveryNetwork) {

    suspend fun queryDeliveryList(restaurantId: String) = withContext(Dispatchers.IO) {
        val requestBody = FormBody.Builder()
                .add("restaurantId", restaurantId)
                .build()
        network.queryDeliveryList(requestBody)
    }

    suspend fun addDeliveryConfig(data: DeliveryConfig.Data.DeliveryInfo) = withContext(Dispatchers.IO) {
        val requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(data)!!)
        network.addDeliveryList(requestBody)
    }

    suspend fun updateDelivery(distributionFeeMin: String, distributionFeeMax: String,
                               distributionFee: String, deliveryCost: String,
                               distributionType: String, type: String,
                               desc: String, id: String,
                               createBy: String, deletes: Int, lackPrice: String) = withContext(Dispatchers.IO) {
        val requestBody = FormBody.Builder()
                .add("id", id)//id
                .add("distributionFeeMin", distributionFeeMin)//運費下限
                .add("distributionFeeMax", distributionFeeMax)//運費上限
                .add("distributionFee", distributionFee)//配送费
                .add("deliveryCost", deliveryCost)//起送费
                .add("distributionType", distributionType)//配送類型   SHORT_RANGE (短途送） STANDARD (中途送） LONG_DISTANCE(長途送)
                .add("type", type)//是否本店配送，0，是，1，第三方
                .add("desc", desc)//描述
                .add("updateBy", createBy)//用戶id
                .add("lackPrice", lackPrice)//差價
                .add("deletes", deletes.toString())
                .build()
        network.updateDelivery(requestBody)
    }


    companion object {
        private lateinit var instance: DeliveryRepository

        fun getInstance(network: DeliveryNetwork): DeliveryRepository {
            if (!Companion::instance.isInitialized) {
                synchronized(DeliveryRepository::class.java) {
                    if (!Companion::instance.isInitialized) {
                        instance = DeliveryRepository(network)
                    }
                }
            }
            return instance
        }

    }
}