package com.ruoyi.xq.service.impl;

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.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.xq.domain.*;
import com.ruoyi.xq.dto.admin.dynamic.DynamicAddReq;
import com.ruoyi.xq.dto.admin.dynamic.DynamicAdminVo;
import com.ruoyi.xq.dto.app.auth.LoginUser;
import com.ruoyi.xq.dto.app.dynamic.AddDynamicReq;
import com.ruoyi.xq.dto.app.dynamic.DynamicListVo;
import com.ruoyi.xq.dto.app.dynamic.DynamicQuery;
import com.ruoyi.xq.dto.app.dynamic.MyDynamicListVo;
import com.ruoyi.xq.enums.common.AuditEnum;
import com.ruoyi.xq.enums.user.UserInfoAuditTypeEnum;
import com.ruoyi.xq.mapper.DynamicMapper;
import com.ruoyi.xq.service.DynamicImageService;
import com.ruoyi.xq.service.DynamicService;
import com.ruoyi.xq.service.DynamicStarService;
import com.ruoyi.xq.service.UserService;
import com.ruoyi.xq.util.AgeUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 动态审核Service业务层处理
 *
 * @author 77
 * @date 2024-03-04
 */
@RequiredArgsConstructor
@Service
public class DynamicServiceImpl extends ServiceImpl<DynamicMapper,Dynamic> implements DynamicService {

    @Autowired
    private UserService userService;
    @Autowired
    private DynamicImageService dynamicImageService;
    @Autowired
    private DynamicStarService dynamicStarService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void push(AddDynamicReq req) {
        User user = userService.getById(req.getUserId());
        Dynamic dynamic = new Dynamic();
        dynamic.setUserId(user.getId());
        dynamic.setUsercode(user.getUsercode());
        dynamic.setContent(req.getContent());
        dynamic.setAuditStatus(AuditEnum.AUDITING.getCode());
        this.save(dynamic);
        List<String> imagesList = req.getImageList();
        for (String image : imagesList) {
            DynamicImage dynamicImage = new DynamicImage();
            dynamicImage.setUserId(user.getId());
            dynamicImage.setUsercode(user.getUsercode());
            dynamicImage.setDynamicId(dynamic.getId());
            dynamicImage.setUrl(image);
            dynamicImageService.save(dynamicImage);
        }
    }

    @Override
    public Page<MyDynamicListVo> currentPage(PageQuery pageQuery) {
        Long currentUserId = LoginHelper.getUserId();
        Page<MyDynamicListVo> page = baseMapper.currentPage(pageQuery.build(), currentUserId);
        List<MyDynamicListVo> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return page;
        }
        List<Long> dynamicIds = records.stream().map(MyDynamicListVo::getId).collect(Collectors.toList());
        List<DynamicImage> list = dynamicImageService.list(Wrappers.lambdaQuery(DynamicImage.class).in(DynamicImage::getDynamicId, dynamicIds));
        Map<Long, List<DynamicImage>> map = list.stream().collect(Collectors.groupingBy(DynamicImage::getDynamicId));
        for (MyDynamicListVo record : records) {
            record.setAge(AgeUtil.getAge(record.getBirthday()));
            List<DynamicImage> images = map.get(record.getId());
            if(images == null){
                images = new ArrayList<>();
            }
            record.setImageList(images.stream().map(DynamicImage::getUrl).collect(Collectors.toList()));
        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeDynamicOfApp(Long id) {
        Dynamic dynamic = this.getById(id);
        if(dynamic == null){
            throw new ServiceException("动态不存在");
        }
        Long userId = LoginHelper.getUserId();
        if(dynamic.getUserId().equals(userId)){
            throw new ServiceException("只能删除自己的动态哦");
        }
        this.removeById(id);
        dynamicImageService.removeByDynamicId(id);
        dynamicStarService.removeByDynamicId(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDynamic(DynamicAddReq bo) {
        String usercode = bo.getUsercode();
        User user = userService.getByUsercode(usercode);
        if(user == null){
            throw new ServiceException("用户不存在");
        }
        if(StringUtils.isEmpty(bo.getDynamicImages())){
            throw new ServiceException("请上传动态图");
        }
        Dynamic dynamic = new Dynamic();
        dynamic.setUserId(user.getId());
        dynamic.setUsercode(user.getUsercode());
        dynamic.setContent(bo.getContent());
        dynamic.setAuditStatus(AuditEnum.SUCCESS.getCode());
        dynamic.setAuditRemark("后台新增");
        this.save(dynamic);
        String[] dynamicPictures = bo.getDynamicImages().split(",");
        for (String dynamicPicture : dynamicPictures) {
            DynamicImage dynamicImage = new DynamicImage();
            dynamicImage.setUserId(user.getId());
            dynamicImage.setUsercode(user.getUsercode());
            dynamicImage.setDynamicId(dynamic.getId());
            dynamicImage.setUrl(dynamicPicture);
            dynamicImageService.save(dynamicImage);
        }
    }

    @Override
    public Page<DynamicListVo> pageApp(PageQuery pageQuery, DynamicQuery dynamicQuery) {
        Page<DynamicListVo> page = baseMapper.pageApp(pageQuery.build(), dynamicQuery);
        List<DynamicListVo> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return page;
        }
        Long currentUserId = LoginHelper.getUserId();
        List<Long> dynamicIds = records.stream().map(DynamicListVo::getId).collect(Collectors.toList());
        List<DynamicStar> starList = dynamicStarService.isStarList(dynamicIds, currentUserId);
        Set<Long> starDynamicSet = starList.stream().map(DynamicStar::getDynamicId).collect(Collectors.toSet());
        List<DynamicImage> list = dynamicImageService.list(Wrappers.lambdaQuery(DynamicImage.class).in(DynamicImage::getDynamicId, dynamicIds));
        Map<Long, List<DynamicImage>> map = list.stream().collect(Collectors.groupingBy(DynamicImage::getDynamicId));
        for (DynamicListVo record : records) {
            record.setAge(AgeUtil.getAge(record.getBirthday()));
            List<DynamicImage> images = map.get(record.getId());
            if(images == null){
                images = new ArrayList<>();
            }
            record.setImageList(images.stream().map(DynamicImage::getUrl).collect(Collectors.toList()));
            record.setStar(starDynamicSet.contains(record.getId()));
        }
        return page;
    }

    @Override
    public Page<DynamicAdminVo> pageAdmin(PageQuery pageQuery, DynamicAdminVo bo) {
        Page<DynamicAdminVo> page = baseMapper.pageAdmin(pageQuery.build(), bo);
        List<DynamicAdminVo> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return page;
        }
        List<Long> dynamicIds = records.stream().map(DynamicAdminVo::getId).collect(Collectors.toList());
        List<DynamicImage> list = dynamicImageService.list(Wrappers.lambdaQuery(DynamicImage.class).in(DynamicImage::getDynamicId, dynamicIds));
        Map<Long, List<DynamicImage>> map = list.stream().collect(Collectors.groupingBy(DynamicImage::getDynamicId));
        for (DynamicAdminVo record : records) {
            List<DynamicImage> images = map.get(record.getId());
            if(images == null){
                images = new ArrayList<>();
            }
            record.setImageList(images.stream().map(DynamicImage::getUrl).collect(Collectors.toList()));
        }
        return page;
    }

    @Override
    public void auditSuccess(String ids) {
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            this.update(Wrappers.lambdaUpdate(Dynamic.class)
                    .eq(Dynamic::getId, id)
                    .eq(Dynamic::getAuditStatus, AuditEnum.AUDITING.getCode())
                    .set(Dynamic::getAuditStatus, AuditEnum.SUCCESS.getCode())
                    .set(Dynamic::getAuditIp, ServletUtils.getClientIP())
                    .set(Dynamic::getAuditOpId, LoginHelper.getUserId())
                    .set(Dynamic::getAuditOpName, LoginHelper.getUsername())
                    .set(Dynamic::getAuditTime, LocalDateTime.now())
                    .set(Dynamic::getAuditRemark, "审核成功"));
        }
    }

    @Override
    public void auditFail(Long id, String auditRemark) {
        this.update(Wrappers.lambdaUpdate(Dynamic.class)
                .eq(Dynamic::getId, id)
                .eq(Dynamic::getAuditStatus, AuditEnum.AUDITING.getCode())
                .set(Dynamic::getAuditStatus, AuditEnum.FAIL.getCode())
                .set(Dynamic::getAuditIp, ServletUtils.getClientIP())
                .set(Dynamic::getAuditOpId, LoginHelper.getUserId())
                .set(Dynamic::getAuditOpName, LoginHelper.getUsername())
                .set(Dynamic::getAuditTime, LocalDateTime.now())
                .set(Dynamic::getAuditRemark, auditRemark));
    }


}
