package com.img.rabbit.provider.storage

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.img.rabbit.bean.response.UserConfigEntity
import com.img.rabbit.bean.response.LoginInfoEntity
import com.img.rabbit.bean.response.UserInfoEntity
import com.img.rabbit.provider.utils.HeadParamUtils.applicationContext
import com.img.rabbit.utils.MMKVUtils
import com.img.rabbit.utils.MMKVUtils.mmkv
import com.img.rabbit.utils.appwalle.ChannelReader
import org.json.JSONObject

/**
 * SharedPreferences工具类，用于简化数据持久化操作
 */
object PreferenceUtil {
    private const val KEY_ACCESS_TOKEN = "access_token"
    private const val KEY_X_TOKEN = "x_token"
    private const val KEY_LOGIN_INFO = "login_info"
    private const val KEY_DB_VID = "bd_vid"
    private const val KEY_USER_CONFIG = "user_config"
    private const val KEY_WX_CODE = "wx_code"
    private const val KEY_USER_INFO = "user_info"




    //服务器时间和本地时间的偏移量
    private var timeDiff = 0L


    // Gson实例
    private val gson: Gson = GsonBuilder().create()


    /**
     * 保存AccessToken
     */
    fun saveAccessToken(token: String?) {
        mmkv.encode(KEY_ACCESS_TOKEN, token)
        mmkv.encode(KEY_X_TOKEN, token)
    }

    /**
     * 获取保存的AccessToken
     */
    fun getAccessToken(): String? {
        return mmkv.decodeString(KEY_ACCESS_TOKEN, null)
    }

    fun saveXToken(token: String?) {
        mmkv.encode(KEY_X_TOKEN, token)
    }

     fun getXToken(): String? {
        return mmkv.decodeString(KEY_X_TOKEN, null)
    }

    fun saveUserConfig(config: UserConfigEntity) {
        val resultJson = Gson().toJson(config)
        mmkv.encode(KEY_USER_CONFIG, resultJson)
    }

     fun getUserConfig(): UserConfigEntity? {
        return gson.fromJson(mmkv.decodeString(KEY_USER_CONFIG, "{}"), UserConfigEntity::class.java)
    }


    fun loginInfo(): LoginInfoEntity?{
        return getLoginInfos()?.find { it.isLogin }
    }

    fun saveLoginInfo(loginInfoEntity: LoginInfoEntity) {
        val loginInfos = getLoginInfos()?: mutableListOf()
        val isContain = loginInfos.find { it.user_id == loginInfoEntity.user_id } != null
        if(!isContain){
            loginInfos.add(loginInfoEntity)
        }

        mmkv.encode(KEY_LOGIN_INFO, gson.toJson(loginInfos))
    }

    fun removeLoginInfo(loginInfoEntity: LoginInfoEntity) {
        val loginInfos = getLoginInfos()?: mutableListOf()
        loginInfos.removeIf { it.user_id == loginInfoEntity.user_id }
        mmkv.encode(KEY_LOGIN_INFO, gson.toJson(loginInfos))
    }

    fun getLoginInfos(): MutableList<LoginInfoEntity>? {
        /**
         *[{"user_id":"25","name":"手机用户0253","avater":"https://cdn.batiao8.com/jietutu/logo.png","token":"45731e27-d101-4ec3-975c-e665cf86a579"},{"user_id":"25","name":"手机用户0253","avater":"https://cdn.batiao8.com/jietutu/logo.png","token":"45731e27-d101-4ec3-975c-e665cf86a579"}]
         */
        return gson.fromJson(mmkv.decodeString(KEY_LOGIN_INFO, "[]"), Array<LoginInfoEntity>::class.java)?.toMutableList()
    }

    fun saveUserInfo(userInfoEntity: UserInfoEntity) {
        mmkv.encode(KEY_USER_INFO, gson.toJson(userInfoEntity))
    }

    fun getUserInfo(): UserInfoEntity? {
        return gson.fromJson(mmkv.decodeString(KEY_USER_INFO, "{}"), UserInfoEntity::class.java)
    }


    fun saveWxCode(code: String) {
        mmkv.encode(KEY_WX_CODE, code)
    }

    fun getWxCode(): String? {
        return mmkv.decodeString(KEY_WX_CODE, null)
    }

    //真实的服务器时间
    fun serverTimeMillis(): Long {
        return System.currentTimeMillis() + timeDiff * 1000
    }
    fun setTimeDiff(timeDiff: Long) {
        this.timeDiff = timeDiff
    }

    /**
     * 保存百度归因bd_vid
     */
    fun saveBDVID() {
        try {
            val str = applicationContext?.let { ChannelReader.get(it) }
            if (!TextUtils.isEmpty(str)) {
                @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
                val jsonObj = JSONObject(str)
                jsonObj.getString("bd_vid").let {
                    MMKVUtils.put("bd_vid", it)
                }
            } else {
                MMKVUtils.put("bd_vid", "")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取百度归因bd_vid
     */
    fun getBDVID(): String {
        return MMKVUtils.getString(KEY_DB_VID) ?: ""
    }

    /**
     * 退出登录时，清除用户信息
     */
    fun clearLogin(){
        mmkv.remove(KEY_ACCESS_TOKEN)
        mmkv.remove(KEY_X_TOKEN)
        mmkv.remove(KEY_LOGIN_INFO)
        mmkv.remove(KEY_USER_INFO)
        mmkv.remove(KEY_WX_CODE)
    }


    /**
     * 清除所有数据
     */
    fun clearAll() {
        mmkv.clearAll()
    }
}