package com.gingersoft.gsa.delivery_pick_mode.data.network

import com.gingersoft.gsa.delivery_pick_mode.data.network.api.AppService
import com.gingersoft.gsa.delivery_pick_mode.data.network.api.WeatherService
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.http.Query
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

class CoolWeatherNetwork {

    private val ricepon_WechatService = ServiceCreator.create(WeatherService::class.java)

    private val service = ServiceCreator.create2(WeatherService::class.java)

    private val appService = ServiceCreator.create2(AppService::class.java)

    private val gsposService = ServiceCreator.create3(WeatherService::class.java)

    private val cloudService = ServiceCreator.create4(WeatherService::class.java)

    private val orderPayService = ServiceCreator.create5(WeatherService::class.java)

    private val systemService = ServiceCreator.createSystem(WeatherService::class.java)

    private val activitiesService = ServiceCreator.createActivities(WeatherService::class.java)

    private val gsaService = ServiceCreator.createGSA(WeatherService::class.java)

    private val rootGsaService = ServiceCreator.createRootGSA(WeatherService::class.java)

    //獲取訂單列表
    suspend fun fetchOrderList(requestBody: RequestBody) = ricepon_WechatService.getOrderList(requestBody).await()

    //修改餐廳營業狀態
    suspend fun updateRestOpenStatus(requestBody: RequestBody) = service.updateRestOpenStatus(requestBody).await()

    //獲取訂單分組數量，例：待確認訂單數量，製作中訂單數量。。。
    suspend fun getOrderGroupNum(requestBody: RequestBody) = ricepon_WechatService.getOrderGroupNum(requestBody).await()

    //獲取訂單信息
    suspend fun getOrderInfo(requestBody: RequestBody) = ricepon_WechatService.getOrderDesc(requestBody).await()

    //獲取第三方物流信息
    suspend fun getShipanyOrderTime(requestBody: RequestBody) = gsposService.getShipanyOrderTime(requestBody).await()

    //修改訂單狀態
    suspend fun updateOrderStatus(requestBody: RequestBody) = ricepon_WechatService.updateOrderStatus(requestBody).await()

    //gspost修改訂單狀態
    suspend fun gsUpdateOrderStatus(requestBody: RequestBody) = service.gsUpdateOrderStatus(requestBody).await()

    //支付
    suspend fun updateOrderPay(requestBody: RequestBody) = orderPayService.updateOrderPay(requestBody).await()

    //第三方配送接口
    suspend fun thirdDelivery(requestBody: RequestBody) = gsposService.thirdDelivery(requestBody).await()

    suspend fun updateIsRead(requestBody: RequestBody) = service.updateIsRead(requestBody).await()

    //修改自取訂單狀態
    suspend fun updateSelfOrderStatus(requestBody: RequestBody) = ricepon_WechatService.updateSelfOrderStatus(requestBody).await()

    // 獲取餐廳配送人員信息
    suspend fun getDeliveryInfo(requestBody: RequestBody) = ricepon_WechatService.getDeliveryInfo(requestBody).await()

    //獲取物流配置
    suspend fun getDeliveryConfigDTO(requestBody: RequestBody) = gsposService.getDeliveryConfigDTO(requestBody).await()

    //獲取歷史訂單
    suspend fun getHistoryOrderList(restaurantId: String, startTime: String, endTime: String, param: String,
                                    status: String, orderType: String, orderFrom:Int, pageIndex: String, pageSize: String) = orderPayService.getHistoryOrderList(restaurantId,startTime, endTime, param, status, orderType,orderFrom, pageIndex, pageSize).await()

    //取消物流
    suspend fun cancelLogistics(requestBody: RequestBody) = gsposService.cancelLogistics(requestBody).await()

    //取消訂單，有物流需要提示先取消物流
    suspend fun cancelOrder(requestBody: RequestBody) = service.cancelOrder(requestBody).await()

    //獲取商家配置的取消訂單的原因
    suspend fun getCancelReason(brandId: Int, restaurantId: Int, type: Int) = cloudService.getCancelReason(brandId, restaurantId, type).await()

    //獲取商家配置的支付方式
    suspend fun getPayMethod(brandId: Int, restaurantId: Int, payType: Int) = cloudService.getPayMethod(brandId, restaurantId, payType).await()

    suspend fun addPrj(requestBody: RequestBody) = cloudService.addPrj(requestBody).await()

    suspend fun noticePersonnel(requestBody: RequestBody) = appService.noticePersonnel(requestBody).await()

    suspend fun getTransportationConfig(restaurantId: String) = systemService.getTransportationConfig(restaurantId).await()

    suspend fun additionalServiceCharge(requestBody: RequestBody) = rootGsaService.additionalServiceCharge(requestBody).await()

    suspend fun getBanlance(brandId: String) = activitiesService.getBanlance(brandId).await()

    suspend fun getActualAmount(orderId: String, uid: String, restaurantId: String) = gsaService.getShipanyTransportAmount(orderId, uid, restaurantId).await()

    suspend fun getAdditionalByOrderId(orderId: String, deletes: String) = rootGsaService.getAdditionalByOrderId(orderId, deletes).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onFailure(call: Call<T>, t: Throwable) {
//                    val request = orderService.getOrderList(FormBody.Builder().build()).request()
//                    if(call.request().url().toString().contains(request.url().toString())){
//                        //訂單列表接口報錯，推送相關人員
//                    }
                    t.printStackTrace()
                    continuation.resumeWithException(t)
                }

                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) {
                        continuation.resume(body)
                    } else
                        continuation.resumeWithException(RuntimeException("response body is null") as Throwable)
                }
            })
        }
    }

    companion object {

        private var network: CoolWeatherNetwork? = null

        fun getInstance(): CoolWeatherNetwork {
            if (network == null) {
                synchronized(CoolWeatherNetwork::class.java) {
                    if (network == null) {
                        network = CoolWeatherNetwork()
                    }
                }
            }
            return network!!
        }

    }

}