package org.dromara.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.web.utils.SecurityUtils;
import org.dromara.work.domain.bo.TpMessageBo;
import org.dromara.work.domain.vo.TpMessageVo;
import org.dromara.work.service.ITpMessageService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 消息接口
 * @Author: Maosw
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/msg")
@Tag(name = "消息接口")
public class ApiMsgController {

    private final ITpMessageService tpMessageService;

    /**
     * 分页获取我的消息列表
     * @param bo 消息对象
     * @return 消息列表
     */
    @GetMapping("/messageList")
    public R<IPage<TpMessageVo>> messageList(TpMessageBo bo, PageQuery pageQuery) {
        Long userId = SecurityUtils.getUserId();
        bo.setToUserId(userId);
        return R.ok(tpMessageService.selectPageList(bo, pageQuery));
    }

    /**
     * 获取我的未读消息数量
     * @return 消息数量
     */
    @GetMapping("/messageCount")
    public R<Long> messageCount(TpMessageBo bo) {
        Long userId = SecurityUtils.getUserId();
        bo.setToUserId(userId);
        return R.ok(tpMessageService.count(bo));
    }

    /**
     * 设置消息已读
     */
    @GetMapping("/messageRead/{id}")
    public R<Boolean> messageRead(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        TpMessageBo bo = new TpMessageBo();
        bo.setId(id);
        bo.setStatus(2);
        return R.ok(tpMessageService.updateByBo(bo));
    }

    /**
     * 根据ID获取消息详情
     */
    @GetMapping("/messageDetail/{id}")
    public R<TpMessageVo> messageDetail(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        return R.ok(tpMessageService.queryById(id));
    }

    /**
     * 发送消息
     */
    @RepeatSubmit()
    @PostMapping("/sendMessage")
    public R<Boolean> sendMessage(TpMessageBo bo) {
        Long userId = SecurityUtils.getUserId();
        return R.ok(tpMessageService.insertByBo(bo));
    }

}
