package com.storlead.message.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.message.enums.MessageTypeEnum;
import com.storlead.message.pojo.dto.MessageDTO;
import com.storlead.message.pojo.dto.MessageSendDTO;
import com.storlead.message.pojo.entity.InsideMessageSendLogEntity;
import com.storlead.message.pojo.vo.MessageAppNoReadVO;
import com.storlead.message.pojo.vo.MessageDetailVO;
import com.storlead.message.pojo.vo.MessageNoReadTotalVO;
import com.storlead.message.pojo.vo.MessageTypeReadStateVO;
import com.storlead.message.service.InsideMessageRecordService;
import com.storlead.message.service.InsideMessageSendLogService;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-04-19 16:36
 */
@RestController
@RequestMapping("/sys/inside/message")
@Api(tags = "消息: 站内消息相关接口")
public class MessageApiController {

    @Resource
    private InsideMessageSendLogService messageSendLogService;

    @Resource
    private InsideMessageRecordService messageRecordService;

    @PostMapping(value = "/testSend")
    @ApiOperation(value = "发送站内消息（ApiPost：POST + application/json，Header 带 token）")
    public Result<?> sendMessage(@RequestBody MessageSendDTO dto) {
        return messageRecordService.sendDirectMessage(dto);
    }

    @PostMapping(value = "/pageList")
    @ApiOperation(value = "获取当前用户的站内消息（可选 messageType / appId / isRead）")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = MessageDetailVO.class)
    })
    public Result<?> getMessage(MessageDTO dto) {
        if (dto == null) {
            dto = new MessageDTO();
        }
        IPage<MessageDetailVO> pageList = messageSendLogService.queryListMessageLog(dto);
        return Result.result(pageList);
    }

    @PostMapping(value = "/read")
    @ApiOperation(value = "更新为已读" )
    public Result<?> updateStatus(Long [] messageLogIds) {
        if (Objects.isNull(messageLogIds) || messageLogIds.length == 0) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<InsideMessageSendLogEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.in(InsideMessageSendLogEntity::getId,messageLogIds);
        updateWrapper.eq(InsideMessageSendLogEntity::getIsDelete,Integer.valueOf(0));
        updateWrapper.set(InsideMessageSendLogEntity::getIsRead,1);
        return Result.result(messageSendLogService.update(updateWrapper));
    }

    @PostMapping(value = "/readAll")
    @ApiOperation(value = "全部标记已读（可选 messageType / appId）")
    public Result<?> readAll(MessageDTO dto) {
        if (dto == null) {
            dto = new MessageDTO();
        }
        LambdaUpdateWrapper<InsideMessageSendLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(InsideMessageSendLogEntity::getReceiverUserId, LoginUserUtil.getCurrentUserId());
        updateWrapper.eq(InsideMessageSendLogEntity::getIsDelete, 0);
        updateWrapper.eq(InsideMessageSendLogEntity::getIsRead, 0);
        applySendLogMessageTypeFilter(updateWrapper, dto.getMessageType());
        applyAppIdUpdateFilter(updateWrapper, dto.getAppId());
        updateWrapper.set(InsideMessageSendLogEntity::getIsRead, 1);
        return Result.result(messageSendLogService.update(updateWrapper));
    }

    @PostMapping(value = "/cleanAll")
    @ApiOperation(value = "清除消息（可选 messageType / appId / isRead）")
    public Result<?> cleanAll(MessageDTO dto) {
        if (dto == null) {
            dto = new MessageDTO();
        }
        LambdaUpdateWrapper<InsideMessageSendLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(InsideMessageSendLogEntity::getReceiverUserId, LoginUserUtil.getCurrentUserId());
        applySendLogMessageTypeFilter(updateWrapper, dto.getMessageType());
        if (Objects.nonNull(dto.getIsRead())) {
            updateWrapper.eq(InsideMessageSendLogEntity::getIsRead, dto.getIsRead());
        }
        applyAppIdUpdateFilter(updateWrapper, dto.getAppId());
        updateWrapper.eq(InsideMessageSendLogEntity::getIsDelete, 0);
        updateWrapper.set(InsideMessageSendLogEntity::getIsDelete, 1);
        return Result.result(messageSendLogService.update(updateWrapper));
    }

    @PostMapping(value = "/getMessageCount")
    @ApiOperation(value = "获取未读消息数（可选 messageType / appId）")
    public Result<?> getMessageCount(MessageDTO dto) {
        if (dto == null) {
            dto = new MessageDTO();
        }
        MessageNoReadTotalVO countMap = messageSendLogService.countNoReadtotal(buildUnreadQueryWrapper(dto));
        return Result.result(countMap);
    }

    @PostMapping(value = "/getNoReadCount")
    @ApiOperation(value = "按消息类型统计未读数（可按应用过滤）")
    public Result<?> getNoReadCount(MessageDTO dto) {
        if (dto == null) {
            dto = new MessageDTO();
        }
        List<String> types = new ArrayList<>();
        if (Objects.nonNull(dto.getMessageType())) {
            types.add(dto.getMessageType());
        }
        List<MessageTypeReadStateVO> statuVOS = messageSendLogService.getCountNoReadCount(buildUnreadQueryWrapper(dto));

        List<MessageTypeReadStateVO> readStatels = MessageTypeEnum.getMessageTypeReadStatels(types);
        Map<Integer, Integer> statuMap = statuVOS.stream()
                .collect(Collectors.toMap(MessageTypeReadStateVO::getMessageType, MessageTypeReadStateVO::getStateNumber));
        for (MessageTypeReadStateVO readState : readStatels) {
            readState.setStateNumber(statuMap.getOrDefault(readState.getMessageType(), 0));
            readState.setAppId(dto.getAppId());
        }
        return Result.result(readStatels);
    }

    @PostMapping(value = "/getNoReadCountByApp")
    @ApiOperation(value = "按应用统计未读消息数")
    public Result<?> getNoReadCountByApp(MessageDTO dto) {
        if (dto == null) {
            dto = new MessageDTO();
        }
        QueryWrapper<InsideMessageSendLogEntity> queryWrapper = buildUnreadQueryWrapper(dto);
        queryWrapper.isNotNull("mr.app_id");
        List<MessageAppNoReadVO> list = messageSendLogService.getCountNoReadCountByApp(queryWrapper);
        return Result.result(list);
    }

    /**
     * 未读统计通用条件：当前用户、未读、未删除；可选 messageType / appId（关联 inside_message_record）。
     */
    private QueryWrapper<InsideMessageSendLogEntity> buildUnreadQueryWrapper(MessageDTO dto) {
        QueryWrapper<InsideMessageSendLogEntity> queryWrapper = buildBaseUserQueryWrapper();
        queryWrapper.eq("mlog.is_read", 0);
        applyRecordScopeFilter(queryWrapper, dto);
        return queryWrapper;
    }

    /**
     * 当前用户未删除消息的基础条件（关联 inside_message_record）。
     */
    private QueryWrapper<InsideMessageSendLogEntity> buildBaseUserQueryWrapper() {
        QueryWrapper<InsideMessageSendLogEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mlog.receiver_user_id", LoginUserUtil.getCurrentUserId());
        queryWrapper.eq("mlog.is_delete", 0);
        return queryWrapper;
    }

    /**
     * 按 inside_message_record 上的 messageType / appId 过滤。
     */
    private void applyRecordScopeFilter(QueryWrapper<InsideMessageSendLogEntity> queryWrapper, MessageDTO dto) {
        if (dto == null) {
            return;
        }
        if (Objects.nonNull(dto.getMessageType())) {
            queryWrapper.eq("mr.message_type", dto.getMessageType());
        }
        if (Objects.nonNull(dto.getAppId())) {
            queryWrapper.eq("mr.app_id", dto.getAppId());
        }
    }

    /**
     * 更新类接口按 send_log.message_type 过滤（与历史 readAll 行为一致）。
     */
    private void applySendLogMessageTypeFilter(LambdaUpdateWrapper<InsideMessageSendLogEntity> updateWrapper, String messageType) {
        if (Objects.nonNull(messageType)) {
            updateWrapper.eq(InsideMessageSendLogEntity::getMessageType, messageType);
        }
    }

    /**
     * appId 在 inside_message_record 上，更新 send_log 时通过 message_id 子查询关联。
     */
    private void applyAppIdUpdateFilter(LambdaUpdateWrapper<InsideMessageSendLogEntity> updateWrapper, Long appId) {
        if (Objects.nonNull(appId)) {
            updateWrapper.inSql(InsideMessageSendLogEntity::getMessageId,
                    "SELECT id FROM inside_message_record WHERE app_id = " + appId);
        }
    }

}
