package com.casic.electric.detector.retrofit

import com.casic.electric.detector.utils.LabelDataClass
import com.casic.electric.detector.utils.LocaleConstant
import com.casic.electric.detector.utils.SmallLabelDataClass
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 {

    /**
     * 登录
     */
    suspend fun login(account: String, password: String): String {
        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return api.login(account, password)
    }

    /**
     * 更新版本
     * */
    suspend fun getApplicationVersion(): String {
        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return api.getApplicationVersion()
    }

    /**
     * 获取标识器信息文件
     */
    suspend fun getMarkerFile(userId: String, companyId: String): String {
        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return api.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()
        )

        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return api.getLabelPicture(requestBody)
    }

    /**
     * 获取巡检工单
     */
    suspend fun getTask(userName: String): String {
        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return api.getTask(userName)
    }

    /**
     * 提交工单
     */
    suspend fun uploadTask(userId: String, taskId: String?, state: String): String {
        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return api.uploadTask(userId, taskId.toString(), state)
    }

    /**
     * 安装新标识器
     * Multipart上传图片，文件，带多参数上传
     */
    suspend fun installLabel(labelData: LabelDataClass): String {
        val param = JsonObject()
        param.addProperty("companyId", labelData.companyId)
        param.addProperty("recordType", labelData.recordType)
        param.addProperty("markerObjectId", labelData.markerObjectId)
        param.addProperty("objectName", labelData.objectName)
        param.addProperty("pressLevel", labelData.pressLevel)
        param.addProperty("markerObjectType", labelData.markerObjectType)
        param.addProperty("inlineName", labelData.inlineName)
        param.addProperty("wellMaterial", labelData.wellMaterial)
        param.addProperty("capacity", labelData.capacity)
        param.addProperty("transformerSpec", labelData.transformerSpec)
        param.addProperty("size", labelData.size)
        param.addProperty("inlineCount", labelData.inlineCount)
        param.addProperty("outlineCount", labelData.outlineCount)
        param.addProperty("cabinetType", labelData.cabinetType)
        param.addProperty("bottomDepth", labelData.bottomDepth)
        param.addProperty("holeCount", labelData.holeCount)
        param.addProperty("coverDepth", labelData.coverDepth)
        param.addProperty("crossPipe", labelData.crossPipe)
        param.addProperty("leftHoleCount", labelData.leftHoleCount)
        param.addProperty("tieCable1", labelData.tieCable1)
        param.addProperty("tieCable2", labelData.tieCable2)
        param.addProperty("jointCount", labelData.jointCount)
        param.addProperty("bushingMaterial", labelData.bushingMaterial)
        param.addProperty("bushingSpec", labelData.bushingSpec)
        param.addProperty("height", labelData.height)
        param.addProperty("lineNo", labelData.lineNo)
        param.addProperty("constructTime", labelData.constructTime)
        param.addProperty("operComp", labelData.operComp)
        param.addProperty("area", labelData.area)
        param.addProperty("road", labelData.road)
        param.addProperty("memo1", labelData.memo1)
        param.addProperty("memo2", labelData.memo2)
        param.addProperty("memo3", labelData.memo3)
        param.addProperty("markerId", labelData.markerId)
        param.addProperty("markerType", labelData.markerType)
        param.addProperty("owner", labelData.owner)
        param.addProperty("markerDepth", labelData.markerDepth)
        param.addProperty("createTime", labelData.createTime)
        param.addProperty("longitude", labelData.longitude)
        param.addProperty("latitude", labelData.latitude)
        param.addProperty("eleTagCount", labelData.eleTagCount)
        param.addProperty("markerMemo1", labelData.markerMemo1)
        param.addProperty("markerMemo2", labelData.markerMemo2)
        param.addProperty("markerMemo3", labelData.markerMemo3)
        val requestBody = param.toString().toRequestBody(
            "application/json;charset=UTF-8".toMediaType()
        )
        val res = HashMap<String, RequestBody>()
        res["jsonMarker"] = requestBody

        val multiParts = ArrayList<MultipartBody.Part>()
        labelData.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)
        }

        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return when (multiParts.size) {
            3 -> {
                api.installLabel(res, multiParts[0], multiParts[1], multiParts[2])
            }

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

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

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

    /**
     * 安装新电子标签
     * Multipart上传图片，文件，带多参数上传
     */
    suspend fun installSmallLabel(labelData: SmallLabelDataClass): String {
        val param = JsonObject()
        param.addProperty("companyId", labelData.companyId) // 公司ID
        param.addProperty("markerId", labelData.markerId) // 标识器ID号
        param.addProperty("locationNo", labelData.locationNo) // 位置点编号
        param.addProperty("locationName", labelData.locationName) // 位置点名称
        param.addProperty("smallMarkerId", labelData.smallMarkerId) // 电子标签ID号
        param.addProperty("cableName", labelData.cableName) // 电缆名称
        param.addProperty("cableNo", labelData.cableNo) // 电缆编号
        param.addProperty("line", labelData.line) // 所属线路
        param.addProperty("pressLevel", labelData.pressLevel) // 电压等级
        param.addProperty("cableType", labelData.cableType) // 电缆型号
        param.addProperty("cableSpec", labelData.cableSpec) // 电缆规格
        param.addProperty("cableBrand", labelData.cableBrand) // 电缆品牌
        param.addProperty("cableStart", labelData.cableStart) // 电缆起点
        param.addProperty("cableEnd", labelData.cableEnd) // 电缆终点
        param.addProperty("hasJoint", labelData.hasJoint) // 中间接头
        param.addProperty("jointCreator", labelData.jointCreator) // 中间接头制作人
        param.addProperty("memo1", labelData.memo1) // 备注1
        param.addProperty("memo2", labelData.memo2) // 备注2
        param.addProperty("memo3", labelData.memo3) // 备注3

        val requestBody = param.toString().toRequestBody(
            "application/json;charset=UTF-8".toMediaType()
        )
        val res = HashMap<String, RequestBody>()
        res["jsonMarker"] = requestBody

        val multiParts = ArrayList<MultipartBody.Part>()
        labelData.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)
        }

        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return when (multiParts.size) {
            3 -> {
                api.installSmallLabel(res, multiParts[0], multiParts[1], multiParts[2])
            }

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

            1 -> {
                api.installSmallLabel(res, multiParts[0], null, null)
            }

            else -> {
                api.installSmallLabel(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)
        }

        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return when (multiParts.size) {
            3 -> {
                api.uploadEvent(taskIdMap, eventMap, multiParts[0], multiParts[1], multiParts[2])
            }

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

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

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

    /**
     * 上传工单中标识器信息
     */
    suspend fun uploadMarker(userName: String, taskDetailId: String): String {
        val api by lazy {
            val serverIp = SaveKeyValues.getValue(LocaleConstant.SERVER_IP, "") as String
            val serverPort = SaveKeyValues.getValue(LocaleConstant.SERVER_PORT, "") as String
            val httpConfig = "http://${serverIp}:${serverPort}"
            RetrofitFactory.createRetrofit<RetrofitService>(httpConfig)
        }
        return api.uploadMarker(userName, taskDetailId)
    }
}