package com.ypsx.yppos.utils

import android.text.TextUtils
import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import com.ypsx.yppos.BuildConfig
import com.ypsx.yppos.http.data.bean.LoginResponse

const val dfs_aliyunDomain = "dfs_aliyunDomain"//阿里云绑定的域名
const val dfs_aliyunPrefix = "dfs_aliyunPrefix"//阿里云路径前缀
const val dfs_aliyunEndPoint = "dfs_aliyunEndPoint"//阿里云EndPoint
const val dfs_aliyunAccessKeyId = "dfs_aliyunAccessKeyId"//阿里云AccessKeyId
const val dfs_aliyunAccessKeySecret = "dfs_aliyunAccessKeySecret"//阿里云AccessKeySecret
const val dfs_aliyunBucketName = "dfs_aliyunBucketName"//阿里云BucketName

object CacheUtil {
    const val user = "user"

    /**
     * 获取保存的账户信息
     */
    fun getLoginResponse(): LoginResponse? {
        val kv = MMKV.mmkvWithID("app")
        val userStr = kv.decodeString(user)
        return if (TextUtils.isEmpty(userStr)) {
            null
        } else {
            Gson().fromJson(userStr, LoginResponse::class.java)
        }
    }

    /**
     * 设置账户信息
     */
    fun setLoginResponse(userResponse: LoginResponse?) {
        val kv = MMKV.mmkvWithID("app")
        if (userResponse == null) {
            kv.encode(user, "")
        } else {
            kv.encode(user, Gson().toJson(userResponse))
        }
    }


    /**
     * 设置首页是否开启获取指定文章
     */
    fun setUpdateTimeBigger(time: String): Boolean {
        val kv = MMKV.mmkvWithID("app")
        return kv.encode("updateTimeBigger", time)
    }

    fun clearAll() {
        val kv = MMKV.mmkvWithID("app")
        kv.removeValueForKey("updateTimeBigger")
        kv.removeValueForKey(user)
    }

    /**
     * 首页是否开启获取指定文章
     */
    fun getUpdateTimeBigger(): String? {
        val kv = MMKV.mmkvWithID("app")
        return kv.decodeString("updateTimeBigger", "")
    }


    fun getAliYunKey(): String {
        return arrayOf(
            dfs_aliyunAccessKeyId, dfs_aliyunAccessKeySecret, dfs_aliyunBucketName,
            dfs_aliyunDomain, dfs_aliyunEndPoint, dfs_aliyunPrefix
        ).joinToString(",")
    }

    fun setAliYunKey(key: String, value: String): Boolean {
        val kv = MMKV.mmkvWithID("app")
        return kv.encode(key, value)
    }

    fun getAliYunKey(key: String): String? {
        val kv = MMKV.mmkvWithID("app")
        return kv.decodeString(key, "")
    }


    fun getRealName(): String {
        return "操作人：${getLoginResponse()?.loginUser?.realName.toString()}"
    }

    fun setHost(host: String): Boolean {
        val kv = MMKV.mmkvWithID("app")
        return kv.encode("host", host)
    }

    fun getHost(): String {
        return if (BuildConfig.DEBUG) {
            val kv = MMKV.mmkvWithID("app")
            kv.decodeString("host", "https://sit-cpos.ypshengxian.com/").toString()
        } else {
            val kv = MMKV.mmkvWithID("app")
            kv.decodeString("host", "https://cpos.ypshengxian.com/").toString()
        }
    }
}