package com.grkj.iscs_mc.util

import android.content.Context
import com.grkj.iscs_mc.model.vo.card.CardInfoRespVO

object SPUtils {

    private const val SP_NAME = "iscs_mc"

    private const val KEY_LOGIN_USER_CARD_ID = "card_id"
    private const val KEY_LOGIN_USER_CARD_CODE = "card_code"
    private const val KEY_LOGIN_USER_HARDWARE_ID = "hardware_id"
    private const val KEY_LOGIN_USER_CARD_NFC = "card_nfc"
    private const val KEY_LOGIN_USER_CARD_TYPE = "card_type"
    private const val KEY_LOGIN_USER_USER_ID = "user_id"
    private const val KEY_LOGIN_USER_USER_NAME = "user_name"
    private const val KEY_LOGIN_USER_ROLE_KEY = "role_key"

    fun getLoginUser(context: Context): CardInfoRespVO? {
        val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
        if (sp.getString(KEY_LOGIN_USER_CARD_NFC, null) == null) {
            return null
        }
        return CardInfoRespVO(
            cardId = sp.getLong(KEY_LOGIN_USER_CARD_ID, 0),
            cardCode = sp.getString(KEY_LOGIN_USER_CARD_CODE, null),
            hardwareId = sp.getLong(KEY_LOGIN_USER_HARDWARE_ID, 0),
            cardNfc = sp.getString(KEY_LOGIN_USER_CARD_NFC, null),
            cardType = sp.getInt(KEY_LOGIN_USER_CARD_TYPE, 0),
            userId = sp.getLong(KEY_LOGIN_USER_USER_ID, 0),
            userName = sp.getString(KEY_LOGIN_USER_USER_NAME, null),
            roleKeyList = sp.getString(KEY_LOGIN_USER_ROLE_KEY, null)?.split(",")?.toMutableList()
        )
    }

    fun setLoginUser(context: Context, cardInfoRespVO: CardInfoRespVO) {
        val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
        val edit = sp.edit()
        cardInfoRespVO.cardId?.let {
            edit.putLong(KEY_LOGIN_USER_CARD_ID, it)
        }
        cardInfoRespVO.cardCode?.let {
            edit.putString(KEY_LOGIN_USER_CARD_CODE, it)
        }
        cardInfoRespVO.hardwareId?.let {
            edit.putLong(KEY_LOGIN_USER_HARDWARE_ID, it)
        }
        cardInfoRespVO.cardNfc?.let {
            edit.putString(KEY_LOGIN_USER_CARD_NFC, it)
        }
        cardInfoRespVO.cardType?.let {
            edit.putInt(KEY_LOGIN_USER_CARD_TYPE, it)
        }
        cardInfoRespVO.userId?.let {
            edit.putLong(KEY_LOGIN_USER_USER_ID, it)
        }
        cardInfoRespVO.userName?.let {
            edit.putString(KEY_LOGIN_USER_USER_NAME, it)
        }
        cardInfoRespVO.roleKeyList?.let {
            edit.putString(KEY_LOGIN_USER_ROLE_KEY, it.toString().replace("[", "").replace("]", ""))
        }
        edit.commit()
    }

    fun clearLoginUser(context: Context): Boolean {
        return try {
            val sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
            val edit = sp.edit()
            edit.clear()
            edit.apply()
            true
        } catch (e: Exception) {
            false
        }
    }
}