package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.NotificationRecords;
import com.ruoyi.common.core.domain.entity.Notifications;
import com.ruoyi.common.core.domain.entity.ShopUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.NotificationRecordsMapper;
import com.ruoyi.system.service.INotificationRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-23
 */
@Transactional
@Service
public class NotificationRecordsServiceImpl implements INotificationRecordsService 
{
    @Autowired
    private NotificationRecordsMapper notificationRecordsMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public NotificationRecords selectNotificationRecordsById(Long id)
    {
        return notificationRecordsMapper.selectNotificationRecordsById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param notificationRecords 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<NotificationRecords> selectNotificationRecordsList(NotificationRecords notificationRecords)
    {
        return notificationRecordsMapper.selectNotificationRecordsList(notificationRecords);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param notificationRecords 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertNotificationRecords(NotificationRecords notificationRecords)
    {
        notificationRecords.setCreateTime(DateUtils.getNowDate());
        return notificationRecordsMapper.insertNotificationRecords(notificationRecords);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param notificationRecords 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateNotificationRecords(NotificationRecords notificationRecords)
    {
        notificationRecords.setUpdateTime(DateUtils.getNowDate());
        return notificationRecordsMapper.updateNotificationRecords(notificationRecords);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteNotificationRecordsByIds(Long[] ids)
    {
        return notificationRecordsMapper.deleteNotificationRecordsByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteNotificationRecordsById(Long id)
    {
        return notificationRecordsMapper.deleteNotificationRecordsById(id);
    }
    
    /**
     * 绑定用户到通知记录
     *
     * @param id 通知ID
     * @param shopUsers 用户列表
     */
    @Override
    @Transactional
    public void bind(Long id, List<ShopUser> shopUsers) {
        System.out.println("开始绑定用户，通知ID: " + id + ", 用户数量: " + (shopUsers != null ? shopUsers.size() : 0));
        
        if (id == null || shopUsers == null || shopUsers.isEmpty()) {
            System.out.println("通知ID为空或用户列表为空，无法绑定");
            return;
        }
        
        // 打印用户列表信息
        System.out.println("用户列表详情:");
        for (ShopUser user : shopUsers) {
            System.out.println("用户ID: " + (user != null ? user.getUserId() : "null") + 
                    ", 类型: " + (user != null && user.getUserId() != null ? user.getUserId().getClass().getName() : "null"));
        }
        
        // 获取当前时间
        Date now = DateUtils.getNowDate();
        
        // 查询该通知已经绑定的用户ID列表
        NotificationRecords query = new NotificationRecords();
        query.setNotificationId(id);
        List<NotificationRecords> existingRecords = notificationRecordsMapper.selectNotificationRecordsList(query);
        Set<Long> existingUserIds = existingRecords.stream()
                .map(NotificationRecords::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        
        System.out.println("已绑定用户数量: " + existingUserIds.size());
        
        // 创建通知记录列表
        List<NotificationRecords> recordsList = new ArrayList<>();
        
        // 遍历用户列表，为每个用户创建通知记录（排除已绑定的用户）
        int validUserCount = 0;
        int invalidUserCount = 0;
        int duplicateUserCount = 0;
        
        for (ShopUser user : shopUsers) {
            try {
                // 验证用户ID是否有效
                if (user == null || user.getUserId() == null) {
                    System.out.println("用户或用户ID为空，跳过");
                    invalidUserCount++;
                    continue;
                }

                
                if (existingUserIds.contains(user.getUserId())) {
                    System.out.println("用户ID: " + user.getUserId() + " 已绑定，跳过");
                    duplicateUserCount++;
                    continue;
                }
                
                // 创建通知记录
                NotificationRecords record = new NotificationRecords();
                record.setUserId(user.getUserId());
                // 默认设置为in-app渠道
                record.setChannel("in-app");
                // 设置状态为待发送
                record.setStatus("pending");
                record.setCreateTime(now);
                record.setNotificationId(id);
                recordsList.add(record);
                validUserCount++;
                
                System.out.println("添加用户ID: " + user.getUserId() + " 到待绑定列表");
            } catch (Exception e) {
                // 记录错误日志，但继续处理其他用户
                System.err.println("处理用户ID时出错: " + (user != null ? user.getUserId() : "null") + ", 错误: " + e.getMessage());
                e.printStackTrace();
                invalidUserCount++;
            }
        }
        
        System.out.println("有效用户数: " + validUserCount + ", 无效用户数: " + invalidUserCount + ", 重复用户数: " + duplicateUserCount);
        System.out.println("待插入记录数: " + recordsList.size());
        
        // 批量插入通知记录
        if (!recordsList.isEmpty()) {
            try {
                int insertCount = notificationRecordsMapper.batchInsertNotificationRecords(recordsList);
                System.out.println("成功插入记录数: " + insertCount);
            } catch (Exception e) {
                System.err.println("批量插入通知记录失败: " + e.getMessage());
                e.printStackTrace();
                throw new RuntimeException("批量插入通知记录失败: " + e.getMessage(), e);
            }
        } else {
            System.out.println("没有需要插入的记录");
        }
    }
    
    /**
     * 获取通知已绑定的用户列表
     *
     * @param notificationId 通知ID
     * @return 用户列表
     */
    @Override
    public List<ShopUser> getBindUsers(Long notificationId) {
        if (notificationId == null) {
            return new ArrayList<>();
        }
        
        // 创建查询条件
        NotificationRecords query = new NotificationRecords();
        query.setNotificationId(notificationId);
        
        // 查询通知记录
        List<NotificationRecords> records = notificationRecordsMapper.selectNotificationRecordsList(query);
        
        // 提取用户ID列表
        List<Long> userIds = records.stream()
                .map(NotificationRecords::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        
        // 如果没有绑定用户，返回空列表
        if (userIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 查询用户信息
        // 这里需要调用ShopUserMapper来查询用户信息
        // 由于没有提供ShopUserMapper，这里简单处理，将用户ID封装成ShopUser对象返回
        List<ShopUser> users = new ArrayList<>();
        for (Long userId : userIds) {
            ShopUser user = new ShopUser();
            user.setUserId(userId);
            users.add(user);
        }
        
        return users;
    }
}
