package shop.alien.store.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 com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.LifeUserViolation;
import shop.alien.entity.store.vo.*;
import shop.alien.mapper.LifeMessageMapper;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.mapper.LifeUserViolationMapper;
import shop.alien.store.service.LifeNoticeService;
import shop.alien.util.type.LifeNoticeUtil;

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

@Service
@RequiredArgsConstructor
public class LifeNoticeServiceImpl extends ServiceImpl<LifeNoticeMapper, LifeNotice> implements LifeNoticeService {

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeMessageMapper lifeMessageMapper;

    private final LifeUserViolationMapper lifeUserViolationMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    @Override
    public R<IPage<LifeNoticeVo>> getNoticeList(int pageNum, int pageSize, String receiverId, int noticeType) {
        IPage<LifeNotice> ipage = new Page<>(pageNum, pageSize);
        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);
//        IPage<LifeNotice> lifeNoticeList = lifeNoticeMapper.selectPage(ipage, queryWrapper);

        List<String> senderIdList = new ArrayList<>();
        Map<String, List<String>> collect = new HashMap<>();
        List<Integer> businessIdList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(lifeNoticeList)) {
            collect = lifeNoticeList.stream()
                    .map(LifeNotice::getSenderId)
                    .filter(item -> item != null && !"system".equals(item) && item.contains("_"))
                    .collect(Collectors.groupingBy(
                            item -> item.split("_")[0],  // 按原始senderId的第一部分分组
                            Collectors.mapping(
                                    item -> item.split("_")[1],  // 提取每个分组中的第二部分
                                    Collectors.toList()
                            )));
            businessIdList = lifeNoticeList.stream()
                    .map(LifeNotice::getBusinessId)
                    .collect(Collectors.toList());
        }

        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()
                    .collect(Collectors.toMap(
                            LifeUserViolation::getId,
                            LifeUserViolation::getReportContextType,
                            (existing, replacement) -> existing
                    ));
        }


        String storePhones = collect.containsKey("store")?"'" + String.join("','", collect.get("store")) + "'":"''";
        String userPhones = collect.containsKey("user")?"'" + String.join("','", collect.get("user")) + "'":"''";
        List<LifeMessageVo> userList = lifeMessageMapper.getLifeUserAndStoreUserByPhone(storePhones, userPhones);

        List<LifeNoticeVo> noticeVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(lifeNoticeList)) {
            lifeNoticeList.forEach(item -> {
                LifeNoticeVo noticeVo = new LifeNoticeVo();
                BeanUtils.copyProperties(item, noticeVo);
                LifeMessageVo userinfo = userList.stream().filter(user -> user.getPhoneId().equals(item.getSenderId())).findFirst().orElse(null);
                if (!"system".equals(noticeVo.getSenderId()) && null != userinfo) {
                    noticeVo.setUserName(userinfo.getUserName());
                    noticeVo.setUserImage(userinfo.getUserImage());
                }
                noticeVoList.add(noticeVo);
            });
        }

        for(LifeNoticeVo lifeNoticeVo : noticeVoList){
            if(lifeNoticeVo == null){
                continue;
            }
            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");
                }
            }
        }

        List<LifeNoticeVo> pageList = noticeVoList.stream()
                .skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());

        IPage<LifeNoticeVo> result = new Page<>();
        result.setRecords(pageList);
        result.setTotal(noticeVoList.size());
        result.setPages((int) Math.ceil(noticeVoList.size() / (double) pageSize));
        result.setSize(pageSize);
        return R.data(result);
    }

    @Override
    public JSONObject getSystemAndOrderNoticeSum(String receiverId) {
        JSONObject jsonObject = new JSONObject();

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

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

        // 系统通知数据
        if (systemNotice != null) {
            LifeNoticeVo noticeVo = new LifeNoticeVo();
            BeanUtils.copyProperties(systemNotice, noticeVo);
            noticeVo.setSystemNum(lifeNoticeList.stream().filter(item -> 1 == item.getNoticeType() && item.getIsRead() == 0).count());
            jsonObject.put("systemNotice", noticeVo);
        } else {
            jsonObject.put("systemNotice", "null");
        }

        // 订单提醒数据
        if (orderNotice != null) {
            LifeNoticeVo noticeVo = new LifeNoticeVo();
            BeanUtils.copyProperties(orderNotice, noticeVo);
            noticeVo.setOrderNum(lifeNoticeList.stream().filter(item -> 2 == item.getNoticeType() && item.getIsRead() == 0).count());
            jsonObject.put("orderNotice", noticeVo);
        } else {
            jsonObject.put("orderNotice", "null");
        }

        return jsonObject;
    }

    @Override
    public int readNoticeById(Integer id) {
        LambdaUpdateWrapper<LifeNotice> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeNotice::getId, id);
        wrapper.set(LifeNotice::getIsRead, 1);
        return lifeNoticeMapper.update(null, wrapper);
    }

    @Override
    public long countUnreadByReceiverIdAndNoticeType(String receiverId, Integer noticeType) {
        LambdaQueryWrapper<LifeNotice> queryWrapper = new LambdaQueryWrapper<>();
        lifeNoticeUtil.applyReceiverQuery(queryWrapper, receiverId);
        queryWrapper.eq(LifeNotice::getNoticeType, noticeType);
        queryWrapper.eq(LifeNotice::getIsRead, 0);
        return lifeNoticeMapper.selectCount(queryWrapper);
    }
}
