package com.ruoyi.project.business.controller.message;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.exception.ServiceErrorException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.business.dto.MessageDto;
import com.ruoyi.project.business.service.message.IBusinessMessageService;
import com.ruoyi.project.common.domain.MessageUser;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.ruoyi.project.business.enums.ReadStatusEnum.READ;
import static com.ruoyi.project.business.enums.ReadStatusEnum.UN_READ;

/**
 * @author jubs
 */
@RestController
@RequestMapping("/business/message")
public class MessageController extends BaseController {

    @Resource
    private IBusinessMessageService businessMessageService;


    @GetMapping("list")
    public TableDataInfo listMessage(MessageDto messageDto) {
        messageDto.setUserId(SecurityUtils.getUserId());
        startPage();
        List<MessageDto> list = businessMessageService.selectMessageUserById(messageDto);
        return getDataTable(list);
    }

    @PutMapping("/read")
    public AjaxResult readMessage(@RequestParam List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new ServiceErrorException("消息id不能为空");
        }
        businessMessageService.update(Wrappers.<MessageUser>lambdaUpdate()
                .set(MessageUser::getReadStatus, READ.getValue())
                .set(MessageUser::getReadTime, new Date())
                .in(MessageUser::getId, ids)
        );
        return AjaxResult.success();
    }

    @GetMapping("/index")
    public AjaxResult selectForIndex(MessageDto messageDto) {
        messageDto.setUserId(SecurityUtils.getUserId());
        messageDto.setIndexQuery(true);
        messageDto.setReadStatus(UN_READ.getValue());
        List<MessageDto> list = businessMessageService.selectMessageUserById(messageDto);
        return AjaxResult.success(list);
    }
}
