package com.mcwl.resource.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.constant.QueueConstants;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.page.PageDomain;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.ModelImage;
import com.mcwl.resource.domain.ModelImageLike;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.resource.domain.response.ResponseModelImage;
import com.mcwl.resource.domain.vo.ModelImageLikeVo;
import com.mcwl.resource.domain.vo.PageVo;
import com.mcwl.resource.mapper.ModelImageLikeMapper;
import com.mcwl.resource.mapper.ModelImageMapper;
import com.mcwl.resource.service.ModelImageLikeService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 图片点赞实现
 */
@Service
@RequiredArgsConstructor
public class ModelImageLikeServiceImpl extends ServiceImpl<ModelImageLikeMapper, ModelImageLike> implements ModelImageLikeService {

    private final ModelImageMapper modelImageMapper;

    private final ISysUserService sysUserService;

    private final RabbitTemplate rabbitTemplate;

    @Override
    public void like(Long imageId) {
        Map<String, Long> map = new HashMap<>();
        map.put("userId", SecurityUtils.getUserId());
        map.put("commentId", imageId);
        Long userId = SecurityUtils.getUserId();
        rabbitTemplate.convertAndSend(QueueConstants.IMAGE_LIKE_QUEUE, map);
    }

    @Override
    public void setModelImageTop(Long id, boolean isTop) {
        modelImageMapper.setModelImageTop(id, isTop ? 1 : 0);
    }

    @Override
    public List<ModelImage> fetchModelImageSortedByTopStatus() {
        return modelImageMapper.fetchModelImageSortedByTopStatus();
    }


    /**
     * 分页查询
     *
     * @param pageDomain 分页参数
     * @return 分页数据
     */
    @Override
    public TableDataInfo listByPage(PageDomain pageDomain) {

        if (StringUtils.isEmpty(pageDomain.getOrderByColumn())) {
            pageDomain.setOrderByColumn("create_time");
        }

        // 2. 构建分页对象并设置排序规则
        Page<ModelImageLikeVo> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());

        List<ModelImageLikeVo> modelImageLikeVoList = modelImageMapper.selectLikedImagesByUser(
                page,
                SecurityUtils.getUserIdMax(),
                pageDomain.getOrderByColumn());

        // 4. 封装分页结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(modelImageLikeVoList);
        rspData.setTotal(page.getTotal());
        return rspData;
    }

    @Override
    public PageInfo<ResponseModelImage> imageList(PageVo pageVo) {

        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(pageVo.getPageNumber(), pageVo.getPageSize());

        List<ResponseModelImage> responseModelImageList = modelImageMapper.imageList(pageVo);

        List<Long> modelImageLikeIds = new ArrayList<>();

        List<ModelImageLike> modelImageLikes = baseMapper.selectList(new LambdaQueryWrapper<ModelImageLike>()
                .eq(ModelImageLike::getUserId, SecurityUtils.getUserIdMax()));
        for (ModelImageLike modelImageLike : modelImageLikes) {
            modelImageLikeIds.add(modelImageLike.getModelImageId());
        }


        for (ResponseModelImage responseModelImage : responseModelImageList) {

            String[] split = responseModelImage.getImagePaths().split(",");
            responseModelImage.setPath(split[0]);

            //查询是否点赞
            if (!modelImageLikeIds.contains(responseModelImage.getId())) {
                responseModelImage.setIsLike(0);
            } else {
                responseModelImage.setIsLike(1);
            }
        }

        return new PageInfo<>(responseModelImageList);

    }


    private void addLikeAdvice(ModelImage modelImage) {

        Long userId = SecurityUtils.getUserId();
        Long receiverUserId = modelImage.getUserId();

        if (Objects.equals(userId, receiverUserId)) {
            return;
        }

        String content = StringUtils.format("恭喜！{}点赞了您的图片：{}",
                SecurityUtils.getLoginUser().getUser().getNickName(), modelImage.getTitle());

        SysAdvice sysAdvice = new SysAdvice();
        sysAdvice.setSenderId(userId);
        sysAdvice.setReceiverId(receiverUserId);
        sysAdvice.setContent(content);
        sysAdvice.setProductId(modelImage.getId());
        sysAdvice.setProductType(2);
        sysAdvice.setIsRead(0);
        sysAdvice.setType(AdviceEnum.LIKE_REMIND);


    }


}
