package com.casic.detector.retrofit

import com.casic.detector.extensions.reformat
import com.casic.detector.utils.LocaleConstant
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.pengxh.kt.lite.utils.RetrofitFactory
import com.pengxh.kt.lite.utils.SaveKeyValues
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File

object RetrofitServiceManager {

    private val gson by lazy { Gson() }

    private fun createApi(): RetrofitService {
        val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
        val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
        val httpConfig = "http://${serverIp}:${serverPort}"
        return RetrofitFactory.createRetrofit(httpConfig)
    }

    /**
     * 登录
     */
    suspend fun login(account: String, password: String): String {
        return createApi().login(account, password)
    }

    /**
     * 更新版本
     * */
    suspend fun getApplicationVersion(): String {
        return createApi().getApplicationVersion()
    }

    /**
     * 获取标识器信息文件
     */
    suspend fun getMarkerFile(userId: String, companyId: String): String {
        return createApi().getMarkerFile(userId, companyId)
    }

    /**
     * 获取标识器图片
     */
    suspend fun getLabelPicture(markerId: String): String {
        val param = JsonObject()
        param.addProperty("markerId", markerId)
        val requestBody = param.toString().toRequestBody(
            "application/json;charset=UTF-8".toMediaType()
        )

        return createApi().getLabelPicture(requestBody)
    }

    /**
     * 获取巡检工单
     */
    suspend fun getTask(userName: String): String {
        return createApi().getTask(userName)
    }

    /**
     * 提交工单
     */
    suspend fun uploadTask(userId: String, taskId: String?, state: String): String {
        return createApi().uploadTask(userId, taskId.toString(), state)
    }

    /**
     * 安装新标识器
     * Multipart上传图片，文件，带多参数上传
     */
    suspend fun installLabel(
        companyId: String,
        recordType: String,
        markerObjectType: String,
        pipeMaterial: String,
        pipeDiameter: String,
        depth: String,
        belowType: String,
        belowMaterial: String,
        belowDiameter: String,
        belowDepth: String,
        layStyle: String,
        area: String,
        line: String,
        road: String,
        constructTime: String,
        ownerComp: String,
        markerObjectId: String,
        markerId: String,
        markerType: String,
        markerDepth: String,
        creator: String,
        createTime: String,
        longitude: String,
        latitude: String,
        colorType: String,
        memo: String,
        realPaths: ArrayList<String>
    ): String {
        val param = JsonObject()
        param.addProperty("companyId", companyId)
        param.addProperty("recordType", recordType)
        param.addProperty("markerObjectType", markerObjectType)
        param.addProperty("pipeMaterial", pipeMaterial)
        param.addProperty("pipeDiameter", pipeDiameter)
        param.addProperty("depth", depth)
        param.addProperty("belowType", belowType)
        param.addProperty("belowMaterial", belowMaterial)
        param.addProperty("belowDiameter", belowDiameter)
        param.addProperty("belowDepth", belowDepth)
        param.addProperty("layStyle", layStyle)
        param.addProperty("area", area)
        param.addProperty("line", line)
        param.addProperty("road", road)
        param.addProperty("constructTime", constructTime)
        param.addProperty("ownerComp", ownerComp)
        param.addProperty("markerObjectId", markerObjectId)
        param.addProperty("markerId", markerId)
        param.addProperty("markerType", markerType)
        param.addProperty("markerDepth", markerDepth)
        param.addProperty("creator", creator)
        param.addProperty("createTime", createTime)
        param.addProperty("longitude", longitude)
        param.addProperty("latitude", latitude)
        param.addProperty("colorType", colorType)
        param.addProperty("memo", memo)
        val requestBody = param.toString().toRequestBody(
            "application/json;charset=UTF-8".toMediaType()
        )
        val res = HashMap<String, RequestBody>()
        res["jsonMarker"] = requestBody

        val multiParts = ArrayList<MultipartBody.Part>()
        realPaths.forEachIndexed { index, s ->
            val file = File(s)
            val fileMultipart = MultipartBody.Part.createFormData(
                "fileBuffer${index + 1}", file.name, file.asRequestBody("image/png".toMediaType())
            )
            multiParts.add(fileMultipart)
        }

        return when (multiParts.size) {
            3 -> {
                createApi().installLabel(res, multiParts[0], multiParts[1], multiParts[2])
            }

            2 -> {
                createApi().installLabel(res, multiParts[0], multiParts[1], null)
            }

            1 -> {
                createApi().installLabel(res, multiParts[0], null, null)
            }

            else -> {
                createApi().installLabel(res, null, null, null)
            }
        }
    }

    /**
     * 上报事件
     * Multipart上传图片，文件，带多参数上传
     */
    suspend fun uploadEvent(taskId: String, event: String, realPaths: ArrayList<String>): String {
        val taskIdMap = HashMap<String, RequestBody>()
        taskIdMap["taskId"] = taskId.toRequestBody(
            "application/json;charset=UTF-8".toMediaType()
        )

        val eventMap = HashMap<String, RequestBody>()
        eventMap["data"] = event.toRequestBody(
            "application/json;charset=UTF-8".toMediaType()
        )

        val multiParts = ArrayList<MultipartBody.Part>()
        realPaths.forEachIndexed { index, s ->
            val file = File(s)
            val fileMultipart = MultipartBody.Part.createFormData(
                "fileBuffer${index + 1}", file.name, file.asRequestBody("image/png".toMediaType())
            )
            multiParts.add(fileMultipart)
        }

        return when (multiParts.size) {
            3 -> {
                createApi().uploadEvent(
                    taskIdMap,
                    eventMap,
                    multiParts[0],
                    multiParts[1],
                    multiParts[2]
                )
            }

            2 -> {
                createApi().uploadEvent(taskIdMap, eventMap, multiParts[0], multiParts[1], null)
            }

            1 -> {
                createApi().uploadEvent(taskIdMap, eventMap, multiParts[0], null, null)
            }

            else -> {
                createApi().uploadEvent(taskIdMap, eventMap, null, null, null)
            }
        }
    }

    /**
     * 上传工单中标识器信息
     */
    suspend fun uploadMarker(taskDetailId: String): String {
        return createApi().uploadMarker(taskDetailId)
    }

    /**
     * 上传工单中标识器信息
     */
    suspend fun createFreeTask(patrollerId: String, description: String): String {
        return createApi().createFreeTask(patrollerId, description)
    }

    /**
     * 上传自由巡检过程中发现的标识器
     */
    suspend fun uploadTaskMarker(taskId: String?, models: ArrayList<String>): String {
        val param = JsonObject()
        param.addProperty("taskId", taskId)
        param.addProperty("ids", models.reformat())
        val requestBody = param.toString().toRequestBody(
            "application/json;charset=UTF-8".toMediaType()
        )
        return createApi().uploadTaskMarker(requestBody)
    }
}