package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.UserComment;
import com.gxwebsoft.shop.entity.UserLike;
import com.gxwebsoft.shop.mapper.UserCommentMapper;
import com.gxwebsoft.shop.param.UserCommentParam;
import com.gxwebsoft.shop.service.UserCommentService;
import com.gxwebsoft.shop.service.UserLikeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户评价记录表Service实现
 *
 * @author 科技小王子
 * @since 2023-07-06 13:55:16
 */
@Service
public class UserCommentServiceImpl extends ServiceImpl<UserCommentMapper, UserComment> implements UserCommentService {
    @Resource
    private UserLikeService userLikeService;

    @Override
    public PageResult<UserComment> pageRel(UserCommentParam param) {
        PageParam<UserComment, UserCommentParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        List<UserComment> list = baseMapper.selectPageRel(page, param);
        if (param.getLoginUserId() != null) {
          // 我点赞的人
          final List<UserLike> myLikes = userLikeService.list(new LambdaQueryWrapper<UserLike>().eq(UserLike::getUserId, param.getLoginUserId()));
          System.out.println("myLikes = " + myLikes);
          list.forEach(d -> {
            final boolean isLike = myLikes.stream().anyMatch(f -> f.getToUserId().equals(param.getLoginUserId()));
            d.setLikes(isLike);
          });
        }
        // List转为树形结构
      final List<UserComment> userComments = CommonUtil.toTreeData(list, 0, UserComment::getReplyCommentId, UserComment::getCommentId, UserComment::setChildren);
      return new PageResult<>(userComments, page.getTotal());
    }

    @Override
    public List<UserComment> listRel(UserCommentParam param) {
        List<UserComment> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<UserComment, UserCommentParam> page = new PageParam<>();
        page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public UserComment getByIdRel(Integer commentId) {
        UserCommentParam param = new UserCommentParam();
        param.setCommentId(commentId);
        return param.getOne(baseMapper.selectListRel(param));
    }

}
