package com.doverfuelingsolutions.issp.api

import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.basic.RetrofitUtil
import com.doverfuelingsolutions.issp.api.dto.DFSResult
import com.doverfuelingsolutions.issp.api.dto.ResultAccumulationInfo
import com.doverfuelingsolutions.issp.api.dto.ResultBarcode
import com.doverfuelingsolutions.issp.api.dto.ResultPumpInfo
import com.doverfuelingsolutions.issp.api.entity.DefaultParams
import com.doverfuelingsolutions.issp.api.entity.NozzleInfo
import com.doverfuelingsolutions.issp.api.entity.ParametersBean
import com.doverfuelingsolutions.issp.api.entity.PumpInfo
import com.doverfuelingsolutions.issp.api.service.ServiceStation
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.utils.sp.SPKeys
import com.doverfuelingsolutions.issp.utils.sp.SPUtil
import com.wayne.www.waynelib.fdc.message.DeviceClass
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

object FuelInfoApi {

    private var serviceStation: ServiceStation = serviceMaker()

    /**
     * 获取泵+枪信息，并且其中的补全残缺信息
     */
    suspend fun requestPumpInfo() = suspendCoroutine<DFSResult<List<PumpInfo>>> {
        GlobalScope.launch(Dispatchers.IO) {
            val resultPumpList = requestPumpList()
            if (!resultPumpList.success || resultPumpList.data == null) {
                it.resume(DFSResult.fail(resultPumpList.message))
                return@launch
            } else if (resultPumpList.data.isEmpty()) {
                it.resume(DFSResult.success(emptyList()))
                return@launch
            }

            val pumpList = arrayListOf<PumpInfo>()
            for (item in resultPumpList.data) {
                if (item.Nozzles.isEmpty()) return@launch
                // 当前油泵的油品名称
                val firstNozzle = item.Nozzles[0]

                val local = SPUtil.getBarcodeInfo(firstNozzle.ProductBarcode)
                val name: String = if (local != null) {
                    local.ItemName
                } else {
                    val resultBarcodeInfo = SystemApi.barcodeName(firstNozzle.ProductBarcode)
                    if (resultBarcodeInfo.success && resultBarcodeInfo.data != null && resultBarcodeInfo.data.IsFuelItem) {
                        SPUtil.setBarcodeInfo(firstNozzle.ProductBarcode, resultBarcodeInfo.data)
                        resultBarcodeInfo.data.ItemName
                    } else {
                        ""
                    }
                }
                val pump = PumpInfo(item.PumpId, name, item.Nozzles.map { resultNozzleInfo ->
                    NozzleInfo(item.PumpId, resultNozzleInfo.LogicalId, resultNozzleInfo.SiteLevelNozzleId, resultNozzleInfo.ProductBarcode, name)
                })
                pumpList.add(pump)
            }

            it.resume(DFSResult.success(pumpList))
        }
    }

    /**
     * 获取累计数信息
     */
    suspend fun accumulationInfo(dc: DeviceClass) = suspendCoroutine<DFSResult<ResultAccumulationInfo>> {
        val bean = ParametersBean().apply {
            Value = dc.releaseTokenElement
        }
        serviceStation.accumulationInfo(DefaultParams(listOf(bean))).enqueue(object : Callback<List<ResultAccumulationInfo>> {
            override fun onResponse(call: Call<List<ResultAccumulationInfo>>, response: Response<List<ResultAccumulationInfo>>) {
                val code = response.code()
                val body = response.body()
                if (code == 200 && body != null && body.isNotEmpty()) {
                    it.resume(DFSResult.success(body[0]))
                    return
                }

                it.resume(DFSResult.fail(R.string.fail_get_accumulation))
            }

            override fun onFailure(call: Call<List<ResultAccumulationInfo>>, t: Throwable) {
                DFSLog.e(t)
                it.resume(DFSResult.fail(R.string.fail_get_accumulation))
            }
        })
    }

    /**
     * 获取泵+枪信息
     */
    private suspend fun requestPumpList() = suspendCoroutine<DFSResult<Array<ResultPumpInfo>>> {
        serviceStation.getNozzleInfo().enqueue(object : Callback<Array<ResultPumpInfo>> {
            override fun onResponse(call: Call<Array<ResultPumpInfo>>, response: Response<Array<ResultPumpInfo>>) {
                val code = response.code()
                val body = response.body()
                if (code == 200 && body != null) {
                    it.resume(DFSResult.success(body))
                    return
                }
                it.resume(DFSResult.fail(R.string.return_data_error))
            }

            override fun onFailure(call: Call<Array<ResultPumpInfo>>, t: Throwable) {
                DFSLog.e("FuelInfoApi.getNozzleData.onFailure", t)
                it.resume(DFSResult.fail(t.message.toString()))
            }
        })
    }

    private fun serviceMaker(): ServiceStation {
        val ip = SPUtil.getString(SPKeys.FUEL_IP)
        val port = SPUtil.getString(SPKeys.FUEL_PORT)
        val url = "http://$ip:$port"
        return RetrofitUtil.getGsonBuilder().baseUrl(url).build().create(ServiceStation::class.java)
    }

    fun generateService() {
        serviceStation = serviceMaker()
    }
}