package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.edu.common.enums.ErrorCode;
import com.lesingle.edu.common.enums.NotificationRecipientType;
import com.lesingle.edu.common.exception.BusinessException;
import com.lesingle.edu.entity.Notification;
import com.lesingle.edu.mapper.NotificationMapper;
import com.lesingle.edu.service.NotificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification>
    implements NotificationService {

    private final NotificationMapper notificationMapper;

    @Override
    @Transactional
    public Notification createNotification(Long tenantId, Long senderId, String senderRole, String title,
                                            String content, String type, String recipientType, Long recipientId) {
        Notification notification = new Notification();
        notification.setTenantId(tenantId);
        notification.setTitle(title);
        notification.setContent(content);
        notification.setType(type);
        notification.setSenderId(senderId);
        notification.setSenderRole(senderRole);
        notification.setRecipientType(recipientType);
        notification.setRecipientId(recipientId);
        notification.setIsRead(0);

        notificationMapper.insert(notification);
        log.info("通知创建成功：id={}, title={}", notification.getId(), notification.getTitle());
        return notification;
    }

    @Override
    public Notification getNotificationById(Long id) {
        Notification notification = notificationMapper.selectById(id);
        if (notification == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "通知不存在");
        }
        return notification;
    }

    @Override
    public Page<Notification> getNotificationPage(Long tenantId, Integer pageNum, Integer pageSize, String type, Integer isRead) {
        Page<Notification> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Notification> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Notification::getTenantId, tenantId);

        if (type != null && !type.isEmpty()) {
            wrapper.eq(Notification::getType, type);
        }
        if (isRead != null) {
            wrapper.eq(Notification::getIsRead, isRead);
        }
        wrapper.orderByDesc(Notification::getCreatedAt);

        return notificationMapper.selectPage(page, wrapper);
    }

    @Override
    public Page<Notification> getMyNotifications(Long recipientId, String recipientType, Integer pageNum, Integer pageSize, Integer isRead) {
        return getMyNotifications(recipientId, recipientType, pageNum, pageSize, isRead, null);
    }

    @Override
    public Page<Notification> getMyNotifications(Long recipientId, String recipientType, Integer pageNum, Integer pageSize, Integer isRead, String notificationType) {
        Page<Notification> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Notification> wrapper = new LambdaQueryWrapper<>();

        wrapper.and(w -> w
                .eq(Notification::getRecipientType, NotificationRecipientType.ALL.getCode())
                .or()
                .eq(Notification::getRecipientId, recipientId)
        );

        if (isRead != null) {
            wrapper.eq(Notification::getIsRead, isRead);
        }
        if (notificationType != null && !notificationType.isEmpty()) {
            wrapper.eq(Notification::getType, notificationType);
        }
        wrapper.orderByDesc(Notification::getCreatedAt);

        return notificationMapper.selectPage(page, wrapper);
    }

    @Override
    @Transactional
    public void markAsRead(Long id) {
        Notification notification = getNotificationById(id);
        notification.setIsRead(1);
        notification.setReadAt(LocalDateTime.now());
        notificationMapper.updateById(notification);
        log.info("通知已标记为已读：id={}", id);
    }

    @Override
    @Transactional
    public void markAllAsRead(Long recipientId, String recipientType) {
        notificationMapper.update(null,
                new LambdaUpdateWrapper<Notification>()
                        .set(Notification::getIsRead, 1)
                        .set(Notification::getReadAt, LocalDateTime.now())
                        .eq(Notification::getIsRead, 0)
                        .and(w -> w
                                .eq(Notification::getRecipientType, NotificationRecipientType.ALL.getCode())
                                .or()
                                .eq(Notification::getRecipientId, recipientId)
                        )
        );
    }

    @Override
    @Transactional
    public void deleteNotification(Long id) {
        getNotificationById(id);
        notificationMapper.deleteById(id);
        log.info("通知删除成功：id={}", id);
    }

    @Override
    public Long getUnreadCount(Long recipientId, String recipientType) {
        return notificationMapper.selectCount(
                new LambdaQueryWrapper<Notification>()
                        .eq(Notification::getIsRead, 0)
                        .and(w -> w
                                .eq(Notification::getRecipientType, NotificationRecipientType.ALL.getCode())
                                .or()
                                .eq(Notification::getRecipientId, recipientId)
                        )
        );
    }

}
