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.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.vo.*;
import shop.alien.mapper.LifeMessageMapper;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.store.service.LifeNoticeService;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

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

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeMessageMapper lifeMessageMapper;

    @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<>();
        queryWrapper.eq(LifeNotice::getReceiverId, 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<>();
        if (CollectionUtil.isNotEmpty(lifeNoticeList)) {
            senderIdList = lifeNoticeList.stream()
                    .map(LifeNotice::getSenderId)
                    .filter(item -> item != null && !"system".equals(item) && item.contains("_"))
                    .map(item -> item.split("_")[1])
                    .collect(Collectors.toList());
        }


        String senderIds = "'" + String.join("','", senderIdList) + "'";
        List<LifeMessageVo> userList = lifeMessageMapper.getLifeUserAndStoreUserByPhone(senderIds, "''");

        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);
            });
        }

        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();

        // 查询系统通知和订单提醒
        LambdaQueryWrapper<LifeNotice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeNotice::getReceiverId, 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);
    }
}
