package com.persagy.server.messagecenter.services

import com.persagy.server.messagecenter.models.entities.Message
import com.persagy.server.messagecenter.models.request.MessageRequest
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.messagecenter.services.base.RService
import com.persagy.service.SPageContext
import com.persagy.service.models.requests.SCreateRequest
import com.persagy.service.models.requests.SUpdateRequest
import com.persagy.service.models.responses.SBaseResponse
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RequestBody
import java.util.*

/**
 * 消息表
 *
 * @author  邓婷婷
 */
object MessageService : RService<Message>(SMybatisDao(Message::class.java)){
    // 日志
    private val logger = LoggerFactory.getLogger(MessageService::class.java)

    fun createBefore(@RequestBody messageRequest: MessageRequest): SCreateRequest<Message> {
        val projectId = SPageContext.getHeader("ProjectId")
        val returnObj = SCreateRequest<Message>()
        var returnList = arrayListOf<Message>()

//        if(messageRequest.userList == null){//接收人列表为空时，表示所有用户都要接收到信息
//
//        }
        for(userId in messageRequest.userList!!){
            var message = Message()
            if(!projectId.isNullOrEmpty()){
                message.projectId = projectId
            }else{
                message.projectId = messageRequest.projectId
            }
            message.id = UUID.randomUUID().toString()
            message.title = messageRequest.title
            message.module = messageRequest.module
            message.type = messageRequest.type
            message.content = messageRequest.content
            message.read = false
            message.userId = userId
            (returnList as ArrayList<Message>).add(message)
        }
        returnObj.content = returnList
        return returnObj
    } // Fun createBefore

    /**
     * 更新状态为已读
     */
    fun updateMessageState(message : Message): SBaseResponse {
        val request = SUpdateRequest<Message>()

        val list = MessageService.select("userId" to message.userId!!,"read" to false).exec()
        for(m in list){
            m.read = true
        }
        request.content = list
        return MessageService.updateList(request)
    } // Fun updateMessageState

}