package com.yushu.system.service.impl;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yushu.common.utils.SecurityUtils;
import com.yushu.system.mapper.SysNotificationMapper;
import com.yushu.system.mapper.SysUserMapper;
import com.yushu.system.domain.SysNotification;
import com.yushu.common.core.domain.entity.SysUser;
import com.yushu.system.service.ISysNotificationService;
import com.alibaba.fastjson2.JSON;

/**
 * 系统通知Service业务层处理
 * 
 * @author yushu
 * @date 2025-11-12
 */
@Service
public class SysNotificationServiceImpl implements ISysNotificationService 
{
    @Autowired
    private SysNotificationMapper sysNotificationMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询系统通知
     * 
     * @param notificationId 系统通知主键
     * @return 系统通知
     */
    @Override
    public SysNotification selectSysNotificationByNotificationId(Long notificationId)
    {
        return sysNotificationMapper.selectSysNotificationByNotificationId(notificationId);
    }

    /**
     * 查询系统通知列表
     * 
     * @param sysNotification 系统通知
     * @return 系统通知
     */
    @Override
    public List<SysNotification> selectSysNotificationList(SysNotification sysNotification)
    {
        return sysNotificationMapper.selectSysNotificationList(sysNotification);
    }

    /**
     * 查询用户的通知列表
     * 
     * @param userId 用户ID
     * @return 通知列表
     */
    @Override
    public List<Map<String, Object>> selectUserNotificationList(Long userId)
    {
        return sysNotificationMapper.selectUserNotificationList(userId);
    }

    /**
     * 统计用户未读通知数
     * 
     * @param userId 用户ID
     * @return 未读通知数
     */
    @Override
    public int countUnreadNotifications(Long userId)
    {
        return sysNotificationMapper.countUnreadNotifications(userId);
    }

    /**
     * 新增系统通知
     * 
     * @param sysNotification 系统通知
     * @return 结果
     */
    @Override
    public int insertSysNotification(SysNotification sysNotification)
    {
        return sysNotificationMapper.insertSysNotification(sysNotification);
    }

    /**
     * 修改系统通知
     * 
     * @param sysNotification 系统通知
     * @return 结果
     */
    @Override
    public int updateSysNotification(SysNotification sysNotification)
    {
        return sysNotificationMapper.updateSysNotification(sysNotification);
    }

    /**
     * 批量删除系统通知
     * 
     * @param notificationIds 需要删除的系统通知主键
     * @return 结果
     */
    @Override
    public int deleteSysNotificationByNotificationIds(Long[] notificationIds)
    {
        return sysNotificationMapper.deleteSysNotificationByNotificationIds(notificationIds);
    }

    /**
     * 删除系统通知信息
     * 
     * @param notificationId 系统通知主键
     * @return 结果
     */
    @Override
    public int deleteSysNotificationByNotificationId(Long notificationId)
    {
        return sysNotificationMapper.deleteSysNotificationByNotificationId(notificationId);
    }

    /**
     * 发布通知
     * 
     * @param notificationId 通知ID
     * @return 结果
     */
    @Override
    @Transactional
    public int publishNotification(Long notificationId)
    {
        SysNotification notification = sysNotificationMapper.selectSysNotificationByNotificationId(notificationId);
        if (notification == null) {
            return 0;
        }

        List<Long> userIds = new ArrayList<>();
        
        // 根据目标类型确定接收用户
        if ("1".equals(notification.getTargetType())) {
            // 全部用户
            List<SysUser> allUsers = sysUserMapper.selectUserList(new SysUser());
            for (SysUser user : allUsers) {
                userIds.add(user.getUserId());
            }
        } else if ("2".equals(notification.getTargetType())) {
            // 指定用户
            if (notification.getTargetUsers() != null) {
                Long[] targetUserIds = JSON.parseObject(notification.getTargetUsers(), Long[].class);
                userIds.addAll(Arrays.asList(targetUserIds));
            }
        } else if ("3".equals(notification.getTargetType())) {
            // 指定角色 - 暂时跳过，需要实现角色用户查询
            // TODO: 实现根据角色ID查询用户的功能
        }

        // 创建接收记录
        if (!userIds.isEmpty()) {
            sysNotificationMapper.publishNotificationToUsers(notificationId, userIds);
        }

        // 更新通知状态为已发布
        notification.setStatus("1");
        return sysNotificationMapper.updateSysNotification(notification);
    }

    /**
     * 标记通知为已读
     * 
     * @param notificationId 通知ID
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int markNotificationAsRead(Long notificationId, Long userId)
    {
        // 先确保接收记录存在（使用INSERT IGNORE或ON DUPLICATE KEY UPDATE）
        sysNotificationMapper.publishNotificationToUsers(notificationId, java.util.Arrays.asList(userId));
        // 再标记为已读
        return sysNotificationMapper.markNotificationAsRead(notificationId, userId);
    }

    /**
     * 删除用户通知
     * 
     * @param notificationId 通知ID
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserNotification(Long notificationId, Long userId)
    {
        return sysNotificationMapper.deleteUserNotification(notificationId, userId);
    }

    /**
     * 查询所有有效的系统通知（简化版）
     * 
     * @return 通知列表
     */
    @Override
    public List<Map<String, Object>> selectAllNotifications()
    {
        Long userId = com.yushu.common.utils.SecurityUtils.getUserId();
        return sysNotificationMapper.selectAllNotifications(userId);
    }

    /**
     * 统计用户未读通知数
     * 
     * @return 未读通知数
     */
    @Override
    public int countUnreadNotifications()
    {
        Long userId = com.yushu.common.utils.SecurityUtils.getUserId();
        return sysNotificationMapper.countUnreadNotifications(userId);
    }
}
