package com.ruoyi.cai.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.cache.DynamicTotalCache;
import com.ruoyi.cai.domain.Dynamic;
import com.ruoyi.cai.domain.DynamicImages;
import com.ruoyi.cai.domain.User;
import com.ruoyi.cai.dto.admin.vo.DynamicAdminVo;
import com.ruoyi.cai.dto.app.query.DynamicAddReq;
import com.ruoyi.cai.dto.app.query.DynamicQuery;
import com.ruoyi.cai.dto.app.vo.DynamicImageVo;
import com.ruoyi.cai.dto.app.vo.DynamicListVo;
import com.ruoyi.cai.dto.app.vo.DynamicVo;
import com.ruoyi.cai.enums.SystemConfigEnum;
import com.ruoyi.cai.manager.SystemConfigManager;
import com.ruoyi.cai.mapper.DynamicMapper;
import com.ruoyi.cai.service.CitysService;
import com.ruoyi.cai.service.DynamicImagesService;
import com.ruoyi.cai.service.DynamicService;
import com.ruoyi.cai.service.UserService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BeanConvertUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 主播动态Service业务层处理
 *
 * @author 77
 * @date 2023-12-23
 */
@RequiredArgsConstructor
@Service
public class DynamicServiceImpl extends ServiceImpl<DynamicMapper, Dynamic> implements DynamicService {

    @Autowired
    private DynamicImagesService dynamicImagesService;
    @Autowired
    private DynamicTotalCache dynamicTotalCache;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemConfigManager systemConfigManager;
    @Autowired
    private CitysService citysService;

    @Override
    public List<String> selectDynamicImageList(Long userId, Integer limit) {
        return baseMapper.selectDynamicImageList(userId,limit);
    }

    @Override
    public Page<DynamicListVo> pageApp(PageQuery pageQuery, DynamicQuery query) {
        Page<DynamicListVo> page = baseMapper.pageApp(pageQuery.build(),query);
        List<DynamicListVo> records = page.getRecords();
        List<Long> dynamicIds = records.stream().filter(i -> i.getIsAttach() == 1).map(DynamicVo::getId).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(dynamicIds)){
            List<DynamicImages> dynamicImages = dynamicImagesService.list(Wrappers.lambdaQuery(DynamicImages.class)
                    .in(DynamicImages::getDynamicId, dynamicIds));
            Map<Long, List<DynamicImages>> map =
                    dynamicImages.stream().collect(Collectors.groupingBy(DynamicImages::getDynamicId));
            for (DynamicVo re : records) {
                List<DynamicImages> images = map.get(re.getId());
                re.setImageList(BeanConvertUtil.convertListTo(images, DynamicImageVo::new));
            }
        }
        return page;
    }

    @Override
    public void saveDynamic(DynamicAddReq res) {
        if(res.getImageList() != null && res.getImageList().size() > 9){
            throw new ServiceException("最多只能发送9张照片哦");
        }
        User user = userService.getById(res.getUserId());
        if(user.getSendDynamic() == 0){
            throw new ServiceException("您已被禁止发送动态");
        }
        Integer maxNum = systemConfigManager.getSystemConfigOfInt(SystemConfigEnum.DAY_MAX_DYNAMIC);
        if(maxNum > 0){
            int alreadySendNum = dynamicTotalCache.get(res.getUserId());
            if(alreadySendNum > maxNum){
                throw new ServiceException("每天最大可发送"+maxNum+"条动态");
            }
        }
        Dynamic dynamic = BeanConvertUtil.convertTo(res, Dynamic::new);
        if(dynamic.getCityId() == null || dynamic.getCityId() == 0){
            dynamic.setCityId(user.getCityId());
            dynamic.setCity(user.getCity());
        } else {
            dynamic.setCity(citysService.getByCityId(dynamic.getCityId()));
        }
        if(CollectionUtil.isNotEmpty(res.getImageList())){
            dynamic.setIsAttach(1);
        }else{
            dynamic.setIsAttach(0);
        }
        this.save(dynamic);
        List<DynamicImageVo> imageList = res.getImageList();
        if(CollectionUtil.isNotEmpty(imageList)){
            for (DynamicImageVo imageVo : imageList) {
                imageVo.setDynamicId(dynamic.getId());
                imageVo.setUserId(dynamic.getUserId());
                imageVo.setId(null);
            }
            dynamicImagesService.saveBatch(BeanConvertUtil.convertListTo(imageList, DynamicImages::new));
        }
    }

    @Override
    public Page<DynamicAdminVo> pageAdmin(PageQuery pageQuery, DynamicAdminVo bo) {
        Page<DynamicAdminVo> page = baseMapper.pageAdmin(pageQuery.build(), bo);
        List<DynamicAdminVo> records = page.getRecords();
        List<Long> dynamicIds = records.stream().filter(i -> i.getIsAttach() == 1).map(DynamicAdminVo::getId).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(dynamicIds)){
            List<DynamicImages> dynamicImages = dynamicImagesService.list(Wrappers.lambdaQuery(DynamicImages.class)
                    .in(DynamicImages::getDynamicId, dynamicIds));
            Map<Long, List<DynamicImages>> map =
                    dynamicImages.stream().collect(Collectors.groupingBy(DynamicImages::getDynamicId));
            for (DynamicAdminVo re : records) {
                List<DynamicImages> images = map.get(re.getId());
                re.setDynamicImageList(images);
            }
        }
        return page;
    }

}
