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.xq.domain.User;
import com.ruoyi.xq.domain.UserPictures;
import com.ruoyi.xq.dto.admin.user.UserPicturesAdminMergeVo;
import com.ruoyi.xq.dto.admin.user.UserPicturesAdminVo;
import com.ruoyi.xq.dto.common.user.MinUser;
import com.ruoyi.xq.enums.common.AuditEnum;
import com.ruoyi.xq.mapper.UserPicturesMapper;
import com.ruoyi.xq.service.UserPicturesService;
import com.ruoyi.xq.service.UserService;
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.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户相册管理Service业务层处理
 *
 * @author 77
 * @date 2024-03-04
 */
@Service
public class UserPicturesServiceImpl extends ServiceImpl<UserPicturesMapper,UserPictures> implements UserPicturesService {

    @Autowired
    private UserService userService;

    @Override
    public List<UserPictures> listByUserIdAuditingAndSuccess(Long userId) {
        return this.list(Wrappers.lambdaQuery(UserPictures.class)
                .eq(UserPictures::getUserId, userId)
                .in(UserPictures::getAuditStatus, AuditEnum.AUDITING.getCode(), AuditEnum.SUCCESS.getCode()));
    }

    @Override
    public List<UserPictures> listByUserIdSuccess(Long userId) {
        return this.list(Wrappers.lambdaQuery(UserPictures.class)
                .eq(UserPictures::getUserId, userId)
                .in(UserPictures::getAuditStatus, AuditEnum.AUDITING.getCode(), AuditEnum.SUCCESS.getCode()));
    }

    @Override
    public Page<UserPicturesAdminVo> pageAdmin(PageQuery pageQuery, UserPicturesAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(),bo);
    }

    @Override
    public Page<UserPicturesAdminMergeVo> pageAdminManager(PageQuery pageQuery, UserPicturesAdminMergeVo bo) {
        Page<UserPicturesAdminMergeVo> page = baseMapper.pageAdminManager(pageQuery.build(), bo);
        List<UserPicturesAdminMergeVo> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return page;
        }
        List<Long> userIds = records.stream().map(UserPicturesAdminMergeVo::getUserId).collect(Collectors.toList());
        List<UserPictures> list = this.list(Wrappers.lambdaQuery(UserPictures.class)
                .in(UserPictures::getUserId, userIds)
                .eq(UserPictures::getAuditStatus, AuditEnum.SUCCESS.getCode()));
        Map<Long, List<UserPictures>> userIdPictursMap = list.stream().collect(Collectors.groupingBy(UserPictures::getUserId));
        for (UserPicturesAdminMergeVo record : records) {
            record.setUserPictureList(userIdPictursMap.getOrDefault(record.getUserId(), Collections.emptyList()));
        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdate(Long userId, List<UserPictures> userPictures) {
        MinUser minUser = userService.getMinUserById(userId);
        if(minUser == null){
            throw new ServiceException("用户不存在");
        }
        if(CollectionUtils.isEmpty(userPictures)){
            this.remove(Wrappers.lambdaQuery(UserPictures.class).eq(UserPictures::getUserId, userId));
            return;
        }
        List<UserPictures> userPicturesList = this.listByUserIdAuditingAndSuccess(userId);
        // 处理新增
        List<Long> pictureIds = new ArrayList<>();
        for (UserPictures pictures : userPictures) {
            if(pictures.getId() == null){
                pictures.setUsercode(minUser.getUsercode());
                pictures.setAuditStatus(AuditEnum.SUCCESS.getCode());
                pictures.setAuditRemark("后台管理操作");
                this.save(pictures);
            }else{
                pictureIds.add(pictures.getId());
            }
        }
        // 处理删除
        for (UserPictures pictures : userPicturesList) {
            if(!pictureIds.contains(pictures.getId())){
                this.removeById(pictures.getId());
            }
        }
    }


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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPictures(List<String> picturesList, User user) {
        for (String picture : picturesList) {
            UserPictures userPictures = new UserPictures();
            userPictures.setUserId(user.getId());
            userPictures.setUsercode(user.getUsercode());
            userPictures.setPicture(picture);
            userPictures.setAuditStatus(AuditEnum.SUCCESS.getCode());
            this.save(userPictures);
        }
    }


}
