package com.base.locationsharewhite.location

import android.os.Build
import com.base.locationsharewhite.BuildConfig
import com.base.locationsharewhite.bean.Viewer
import com.base.locationsharewhite.bean.ViewingBean
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 org.json.JSONObject

/**
 * 获取分享关系列表
 */
object LocationShareListUtils {

    private val TAG = "LocationListUtils"

    /**
     * 分享关系列表
     */
    private val url by lazy {
        val pkg = ConfigHelper.packageName
        val url = StringBuilder(
            "${ConfigHelper.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}ac"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    fun getShareList(
        viewerListCallBack: ((viewerList: List<Viewer>) -> Unit)? = null,
        viewingListCallBack: ((viewingList: List<ViewingBean>) -> Unit)? = null
    ) {
        Thread {
            val pkg = ConfigHelper.packageName

            val data = JSONObject()
            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)
            val body = JSONObject()
                .put("data", data)
                .put("bp", bp)
                .toString()

            val paramJson = AESHelper.encrypt(body)
            val result = ReportUtils.doPost(url, HashMap(), paramJson)
            val responseData = LocationLoginUtils.extractData(result)
            if (responseData != null) {
                val decryptedData = AESHelper.decrypt(responseData)
                parseShareListData(decryptedData, viewerListCallBack, viewingListCallBack)
            }
        }.start()
    }

    private fun parseShareListData(
        decryptedData: String,
        viewerListCallBack: ((viewerList: List<Viewer>) -> Unit)? = null,
        viewingListCallBack: ((viewingList: List<ViewingBean>) -> Unit)? = null
    ) {
        val jsonObject = JSONObject(decryptedData)

        val viewerListJson = jsonObject.getJSONArray("viewerList").toString()
        LogEx.logDebug(TAG, "viewerListJson=$viewerListJson")
        val viewingListJson = jsonObject.getJSONArray("viewingList").toString()
        LogEx.logDebug(TAG, "viewingListJson=$viewingListJson")
    }
}