package shop.alien.storeplatform.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.LifeUserViolation;
import shop.alien.entity.store.vo.LifeMessageVo;
import shop.alien.entity.store.vo.LifeNoticeVo;
import shop.alien.mapper.LifeMessageMapper;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.mapper.LifeUserViolationMapper;
import shop.alien.storeplatform.service.NoticeService;
import shop.alien.util.type.LifeNoticeUtil;

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

/**
 * web端商户通知管理服务实现类
 *
 * @author ssk
 * @since 2025-01-xx
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NoticeServiceImpl implements NoticeService {

    private final LifeNoticeMapper lifeNoticeMapper;
    
    private final LifeMessageMapper lifeMessageMapper;
    
    private final LifeUserViolationMapper lifeUserViolationMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    @Override
    public JSONObject getNoticeStatistics(String receiverId) {
        log.info("NoticeServiceImpl.getNoticeStatistics - 查询通知统计: receiverId={}", receiverId);
        
        JSONObject jsonObject = new JSONObject();

        // 1. 查询系统通知和订单提醒（noticeType: 1-系统通知, 2-订单提醒）
        LambdaQueryWrapper<LifeNotice> queryWrapper = new LambdaQueryWrapper<>();
        lifeNoticeUtil.applyReceiverQuery(queryWrapper, receiverId);
        queryWrapper.in(LifeNotice::getNoticeType, 1, 2);
        List<LifeNotice> lifeNoticeList = lifeNoticeMapper.selectList(queryWrapper);

        // 检查查询结果
        if (lifeNoticeList == null || lifeNoticeList.isEmpty()) {
            log.info("NoticeServiceImpl.getNoticeStatistics - 未查询到通知数据: receiverId={}", receiverId);
            jsonObject.put("systemNotice", "null");
            jsonObject.put("orderNotice", "null");
            return jsonObject;
        }

        log.info("NoticeServiceImpl.getNoticeStatistics - 查询到通知总数: {}", lifeNoticeList.size());

        // 2. 系统通知最新一条
        LifeNotice systemNotice = lifeNoticeList.stream()
                .filter(item -> 1 == item.getNoticeType())
                .max(Comparator.comparing(LifeNotice::getCreatedTime))
                .orElse(null);

        // 3. 订单提醒最新一条
        LifeNotice orderNotice = lifeNoticeList.stream()
                .filter(item -> 2 == item.getNoticeType())
                .max(Comparator.comparing(LifeNotice::getCreatedTime))
                .orElse(null);

        // 4. 系统通知数据
        if (systemNotice != null) {
            LifeNoticeVo noticeVo = new LifeNoticeVo();
            BeanUtils.copyProperties(systemNotice, noticeVo);
            // 统计系统通知未读数量
            long systemUnreadCount = lifeNoticeList.stream()
                    .filter(item -> 1 == item.getNoticeType() && item.getIsRead() == 0)
                    .count();
            noticeVo.setSystemNum(systemUnreadCount);
            jsonObject.put("systemNotice", noticeVo);
            log.info("NoticeServiceImpl.getNoticeStatistics - 系统通知未读数: {}", systemUnreadCount);
        } else {
            jsonObject.put("systemNotice", "null");
            log.info("NoticeServiceImpl.getNoticeStatistics - 系统通知为空");
        }

        // 5. 订单提醒数据
        if (orderNotice != null) {
            LifeNoticeVo noticeVo = new LifeNoticeVo();
            BeanUtils.copyProperties(orderNotice, noticeVo);
            // 统计订单提醒未读数量
            long orderUnreadCount = lifeNoticeList.stream()
                    .filter(item -> 2 == item.getNoticeType() && item.getIsRead() == 0)
                    .count();
            noticeVo.setOrderNum(orderUnreadCount);
            jsonObject.put("orderNotice", noticeVo);
            log.info("NoticeServiceImpl.getNoticeStatistics - 订单提醒未读数: {}", orderUnreadCount);
        } else {
            jsonObject.put("orderNotice", "null");
            log.info("NoticeServiceImpl.getNoticeStatistics - 订单提醒为空");
        }

        log.info("NoticeServiceImpl.getNoticeStatistics - 查询完成: receiverId={}", receiverId);
        return jsonObject;
    }

    @Override
    public IPage<LifeNoticeVo> getNoticeList(int pageNum, int pageSize, String receiverId, int noticeType) {
        log.info("NoticeServiceImpl.getNoticeList - 查询通知列表: receiverId={}, noticeType={}, pageNum={}, pageSize={}", 
                receiverId, noticeType, pageNum, pageSize);

        // 1. 查询通知列表
        LambdaQueryWrapper<LifeNotice> queryWrapper = new LambdaQueryWrapper<>();
        lifeNoticeUtil.applyReceiverQuery(queryWrapper, receiverId);
        queryWrapper.eq(LifeNotice::getNoticeType, noticeType);
        queryWrapper.eq(LifeNotice::getDeleteFlag, 0);
        queryWrapper.orderByDesc(LifeNotice::getCreatedTime);
        List<LifeNotice> lifeNoticeList = lifeNoticeMapper.selectList(queryWrapper);

        // 2. 提取 senderId 列表，用于查询用户信息
        Map<String, List<String>> senderIdMap = new HashMap<>();
        List<Integer> businessIdList = new ArrayList<>();
        
        if (CollectionUtil.isNotEmpty(lifeNoticeList)) {
            // 解析 senderId，分组为 store 和 user
            senderIdMap = lifeNoticeList.stream()
                    .map(LifeNotice::getSenderId)
                    .filter(item -> item != null && !"system".equals(item) && item.contains("_"))
                    .collect(Collectors.groupingBy(
                            item -> item.split("_")[0],  // 按 store 或 user 分组
                            Collectors.mapping(
                                    item -> item.split("_")[1],  // 提取手机号
                                    Collectors.toList()
                            )));
            
            // 提取 businessId 列表
            businessIdList = lifeNoticeList.stream()
                    .map(LifeNotice::getBusinessId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }

        // 3. 查询违规举报信息
        List<LifeUserViolation> lifeUserViolationList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(businessIdList)) {
            lifeUserViolationList = lifeUserViolationMapper.selectBatchIds(businessIdList);
        }
        
        Map<Integer, String> lifeUserViolationMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(lifeUserViolationList)) {
            lifeUserViolationMap = lifeUserViolationList.stream()
                    .filter(item -> item.getReportContextType() != null)
                    .collect(Collectors.toMap(
                            LifeUserViolation::getId,
                            LifeUserViolation::getReportContextType,
                            (existing, replacement) -> existing
                    ));
        }

        // 4. 查询用户信息（包括商户和普通用户）
        String storePhones = senderIdMap.containsKey("store") ? 
                "'" + String.join("','", senderIdMap.get("store")) + "'" : "''";
        String userPhones = senderIdMap.containsKey("user") ? 
                "'" + String.join("','", senderIdMap.get("user")) + "'" : "''";
        
        List<LifeMessageVo> userList = lifeMessageMapper.getLifeUserAndStoreUserByPhone(storePhones, userPhones);

        // 5. 组装 LifeNoticeVo 列表
        List<LifeNoticeVo> noticeVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(lifeNoticeList)) {
            lifeNoticeList.forEach(item -> {
                if (item == null) {
                    return;
                }
                
                LifeNoticeVo noticeVo = new LifeNoticeVo();
                BeanUtils.copyProperties(item, noticeVo);
                
                // 设置用户信息（如果不是系统通知）
                if (!"system".equals(noticeVo.getSenderId())) {
                    LifeMessageVo userinfo = userList.stream()
                            .filter(user -> user.getPhoneId().equals(item.getSenderId()))
                            .findFirst()
                            .orElse(null);
                    if (userinfo != null) {
                        noticeVo.setUserName(userinfo.getUserName());
                        noticeVo.setUserImage(userinfo.getUserImage());
                    }
                }
                
                noticeVoList.add(noticeVo);
            });
        }

        // 6. 设置平台类型标识
        for (LifeNoticeVo lifeNoticeVo : noticeVoList) {
            if (lifeNoticeVo == null) {
                continue;
            }
            
            // businessId 为空时，设置为默认平台
            if (lifeNoticeVo.getBusinessId() == null) {
                lifeNoticeVo.setPlatformType("1");
            }
            
            // 店铺审核通知设置为默认平台
            if (StringUtils.isNotBlank(lifeNoticeVo.getTitle()) && "店铺审核通知".equals(lifeNoticeVo.getTitle())) {
                lifeNoticeVo.setPlatformType("1");
            }
            
            // 根据举报类型判断平台类型
            if (lifeNoticeVo.getBusinessId() != null && lifeUserViolationMap.containsKey(lifeNoticeVo.getBusinessId())) {
                String reportContextType = lifeUserViolationMap.get(lifeNoticeVo.getBusinessId());
                if (StringUtils.isNotBlank(reportContextType) && "1,2,3".contains(reportContextType)) {
                    lifeNoticeVo.setPlatformType("1");
                }
            }
        }

        // 7. 手动分页
        List<LifeNoticeVo> pageList = noticeVoList.stream()
                .skip((long) (pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());

        // 8. 构建分页结果
        IPage<LifeNoticeVo> result = new Page<>();
        result.setRecords(pageList);
        result.setTotal(noticeVoList.size());
        result.setPages((int) Math.ceil(noticeVoList.size() / (double) pageSize));
        result.setSize(pageSize);
        result.setCurrent(pageNum);

        log.info("NoticeServiceImpl.getNoticeList - 查询完成: 总数={}, 当前页数据量={}", 
                noticeVoList.size(), pageList.size());
        return result;
    }

    @Override
    public int markNoticeAsRead(Integer id) {
        log.info("NoticeServiceImpl.markNoticeAsRead - 标记通知为已读: id={}", id);
        
        // 使用 LambdaUpdateWrapper 更新 isRead 字段
        LambdaUpdateWrapper<LifeNotice> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeNotice::getId, id);
        wrapper.set(LifeNotice::getIsRead, 1);
        
        int result = lifeNoticeMapper.update(null, wrapper);
        
        log.info("NoticeServiceImpl.markNoticeAsRead - 标记完成: id={}, 影响行数={}", id, result);
        return result;
    }

    @Override
    public int markAllNoticesAsRead(String receiverId, Integer noticeType) {
        log.info("NoticeServiceImpl.markAllNoticesAsRead - 批量标记通知为已读: receiverId={}, noticeType={}", 
                receiverId, noticeType);
        
        // 使用 LambdaUpdateWrapper 批量更新 isRead 字段
        LambdaUpdateWrapper<LifeNotice> wrapper = new LambdaUpdateWrapper<>();
        
        // 1. 接收人条件（必须）
        lifeNoticeUtil.applyReceiverUpdate(wrapper, receiverId);
        
        // 2. 只更新未读的通知
        wrapper.eq(LifeNotice::getIsRead, 0);
        
        // 3. 通知类型条件（可选）
        if (noticeType != null) {
            wrapper.eq(LifeNotice::getNoticeType, noticeType);
        }
        
        // 4. 设置为已读
        wrapper.set(LifeNotice::getIsRead, 1);
        
        int result = lifeNoticeMapper.update(null, wrapper);
        
        log.info("NoticeServiceImpl.markAllNoticesAsRead - 批量标记完成: receiverId={}, noticeType={}, 影响行数={}", 
                receiverId, noticeType, result);
        return result;
    }
}

