package com.base.locationsharewhite.location

import android.os.Build
import com.base.locationsharewhite.BuildConfig
import com.base.locationsharewhite.helper.AESHelper
import com.base.locationsharewhite.helper.ConfigHelper
import com.base.locationsharewhite.helper.ReportUtils
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.LogEx
import com.google.android.gms.maps.model.LatLng
import org.json.JSONObject

/**
 * 上报自身位置
 */
object LocationPositionUtils {

    private val TAG = "LocationPositionUtils"

    /**
     * 上传定位接口
     */
    private val uploadUrl by lazy {
        val pkg = ConfigHelper.packageName
        val url = StringBuilder(
            "${ConfigHelper.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}x"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    /**
     *上传自身位置
     */
    fun uploadMyLocation(latLng: LatLng, power: Int) {
        Thread {
            val pkg = ConfigHelper.packageName

            val data = JSONObject()
            data.put("latitude", latLng.latitude)
            data.put("longitude", latLng.longitude)
            data.put("power", power)
            LogEx.logDebug(TAG, "latitude=${latLng.latitude} longitude=${latLng.longitude} power=$power")
            val bp = JSONObject()
//            .put("${pkg}_1", "")
                .put("${pkg}_5", Build.VERSION.SDK_INT)
                .put("${pkg}_8", BuildConfig.VERSION_NAME)
                .put("${pkg}_9", AppPreferences.getInstance().getString("uuid", ""))
                .put("${pkg}_10", AppPreferences.getInstance().getString("uuid", ""))//gid
                .put("${pkg}_13", "android")
                .put("${pkg}_14", BuildConfig.VERSION_CODE)
                .put("${pkg}_15", "google")
                .put("${pkg}_24", BuildConfig.BUILD_TYPE)
            LogEx.logDebug(TAG, "uuid=${AppPreferences.getInstance().getString("uuid", "")}")
            val body = JSONObject()
                .put("data", data)
                .put("bp", bp)
                .toString()

            val paramJson = AESHelper.encrypt(body)
            LogEx.logDebug(TAG, "uploadUrl=${uploadUrl}")

            val result = ReportUtils.doPost(uploadUrl, HashMap(), paramJson)
            LogEx.logDebug(TAG, "result=$result")
        }.start()
    }
}