package com.casic.br.utils

import com.casic.br.base.BaseApplication
import com.casic.br.greendao.LocaleMessageBeanDao
import com.casic.br.model.LocaleMessageBean

class DataBaseManager private constructor() {

    companion object {
        //Kotlin委托模式双重锁单例
        val instance: DataBaseManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            DataBaseManager()
        }
    }

    private val beanDao = BaseApplication.obtainInstance().obtainDaoSession().localeMessageBeanDao

    fun insertLocaleMessage(
        messageId: String, userId: String, title: String,
        content: String, isRead: String, messageTime: String
    ) {
        val messageBean = LocaleMessageBean()
        messageBean.messageId = messageId
        messageBean.userId = userId
        messageBean.title = title
        messageBean.content = content
        messageBean.isRead = isRead
        messageBean.messageTime = messageTime
        beanDao.insert(messageBean)
        //角标设置
        BadeHelper.setBadgeNum(BaseApplication.obtainInstance(), queryUnReadMessage())
    }

    fun deleteLocaleMessageById(userId: String, messageId: String) {
        val result = beanDao.queryBuilder().where(
            LocaleMessageBeanDao.Properties.MessageId.eq(messageId)
        ).list()
        beanDao.deleteInTx(result)
        //角标设置
        BadeHelper.setBadgeNum(BaseApplication.obtainInstance(), queryUnReadMessage())
    }

    fun updateLocaleMessageById(userId: String, messageId: String) {
        val noticeLocaleBean = beanDao.queryBuilder().where(
            LocaleMessageBeanDao.Properties.MessageId.eq(messageId)
        ).unique() ?: return
        noticeLocaleBean.isRead = "1"
        beanDao.update(noticeLocaleBean)
        //角标设置
        BadeHelper.setBadgeNum(BaseApplication.obtainInstance(), queryUnReadMessage())
    }


    fun queryMessageByPage(userId: String, offset: Int): MutableList<LocaleMessageBean> {
        return BaseApplication.obtainInstance().obtainDaoSession()
            .queryBuilder(LocaleMessageBean::class.java)
            .where(LocaleMessageBeanDao.Properties.UserId.eq(userId))
            .offset(offset * LocaleConstant.PAGE_LIMIT)
            .orderDesc(LocaleMessageBeanDao.Properties.MessageTime)
            .limit(LocaleConstant.PAGE_LIMIT)
            .list()
    }

    private fun queryUnReadMessage(): Int {
        return beanDao.queryBuilder().where(
            LocaleMessageBeanDao.Properties.IsRead.eq("0")
        ).list().size
    }
}