package com.ruoyi.frequency.browserecord.service.impl;

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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.controller.req.CollectPageReq;
import com.ruoyi.controller.resp.WorksPageResp;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.workspanorama.entity.WorksPanorama;
import com.ruoyi.frequency.workspanorama.service.WorksPanoramaService;
import com.ruoyi.frequency.workstype.service.WorksTypeService;
import com.ruoyi.post.controller.resp.PostPageResp;
import com.ruoyi.post.controller.vo.SelectedComment;
import com.ruoyi.post.frequency.postcomment.service.PostCommentService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.frequency.browserecord.mapper.BrowseRecordMapper;
import com.ruoyi.frequency.browserecord.entity.BrowseRecord;
import com.ruoyi.frequency.browserecord.service.BrowseRecordService;

/**
 * 浏览记录Service业务层处理
 *
 * @author liwenlong
 * @date 2023-11-25
 */
@Service
public class BrowseRecordServiceImpl extends ServiceImpl<BrowseRecordMapper, BrowseRecord>  implements BrowseRecordService
{
    @Autowired
    private BrowseRecordMapper browseRecordMapper;

    /**
     * 查询浏览记录
     *
     * @param id 浏览记录主键
     * @return 浏览记录
     */
    @Override
    public BrowseRecord selectBrowseRecordById(Long id)
    {
        return browseRecordMapper.selectBrowseRecordById(id);
    }

    /**
     * 查询浏览记录列表
     *
     * @param browseRecord 浏览记录
     * @return 浏览记录
     */
    @Override
    public List<BrowseRecord> selectBrowseRecordList(BrowseRecord browseRecord)
    {
        return browseRecordMapper.selectBrowseRecordList(browseRecord);
    }

    /**
     * 新增浏览记录
     *
     * @param browseRecord 浏览记录
     * @return 结果
     */
    @Override
    public int insertBrowseRecord(BrowseRecord browseRecord)
    {
        browseRecord.setCreateData();
        return browseRecordMapper.insert(browseRecord);
    }

    /**
     * 修改浏览记录
     *
     * @param browseRecord 浏览记录
     * @return 结果
     */
    @Override
    public int updateBrowseRecord(BrowseRecord browseRecord)
    {
        browseRecord.setUpdateData();
        return browseRecordMapper.updateBrowseRecord(browseRecord);
    }

    /**
     * 批量删除浏览记录
     *
     * @param ids 需要删除的浏览记录主键
     * @return 结果
     */
    @Override
    public int deleteBrowseRecordByIds(Long[] ids,Integer delFlag)
    {
        this.lambdaUpdate().set(BrowseRecord::getDelFlag,delFlag).in(BrowseRecord::getId,ids).update();
        return ids.length;
    }

    @Autowired
    private WorksTypeService worksTypeService;

    @Autowired
    private PostCommentService postCommentService;

    @Autowired
    private UserService userService;

    @Autowired
    private WorksPanoramaService worksPanoramaService;

    @Override
    public ResponseData browsePage(CollectPageReq req, UserVo userVo) {
        //收藏类型 1作品 2 动态
        switch (req.getType()){
            case 1:
                if (ObjectUtil.isNotEmpty(req.getTypeId())){
                    //根据类型id获取三级id
                    List<Long> typeIdList = worksTypeService.getIdsByTypeId(req.getTypeId());
                    if (typeIdList.isEmpty()){
                        return ResponseData.success(new PageResult<>(new Page<>(req.getPageNo(),req.getPageSize())));
                    }
                    req.setTypeIds(typeIdList);
                }

                Page<WorksPageResp> worksPage = baseMapper.worksBrowsePage(new Page<>(req.getPageNo(),req.getPageSize()),req,userVo);
                if (!worksPage.getRecords().isEmpty()){

                    Set<UserVo> userVoSet = worksPage.getRecords().stream().map(worksPageResp -> new UserVo(worksPageResp.getUserType(), worksPageResp.getStoreId())).collect(Collectors.toSet());
                    //查询用户信息
                    Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

                    //作品ids
                    List<Long> worksIds = worksPage.getRecords().stream().map(WorksPageResp::getId).collect(Collectors.toList());
                    //查询3D图
                    List<WorksPanorama> worksPanoramaList = worksPanoramaService.list(new QueryWrapper<WorksPanorama>().lambda().in(WorksPanorama::getWorksId, worksIds).orderByDesc(WorksPanorama::getCreateTime));

                    Map<Long, List<WorksPanorama>> map = worksPanoramaList.stream().collect(Collectors.groupingBy(WorksPanorama::getWorksId));

                    worksPage.getRecords().stream().forEach(worksPageResp ->{
                        worksPageResp.setUserInfo(userMap.get(new UserVo(worksPageResp.getUserType(), worksPageResp.getStoreId())));
                        worksPageResp.setWorksPanoramaList(map.get(worksPageResp.getId()));
                    });
                }

                return ResponseData.success(new PageResult<>(worksPage));
            case 2:
                Page<PostPageResp> postPage = baseMapper.postBrowsePage(new Page<>(req.getPageNo(), req.getPageSize()),req,userVo);

                if (!postPage.getRecords().isEmpty()){
                    Set<UserVo> userVoSet = postPage.getRecords().stream().map(postPageResp -> new UserVo(postPageResp.getUserType(), postPageResp.getUserId())).collect(Collectors.toSet());
                    //查询用户信息
                    Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

                    //精彩评论ids
                    List<Long> commentIds = postPage.getRecords().stream().filter(s-> ObjectUtil.isNotEmpty(s.getCommentId())).map(PostPageResp::getCommentId).collect(Collectors.toList());

                    //查询精选评论
                    Map<Long, SelectedComment> selectedCommentMap = postCommentService.getSelectedCommentMap(commentIds,userVo);

                    postPage.getRecords().stream().forEach(videoPageResp ->{
                        videoPageResp.setUserInfo(userMap.get(new UserVo(videoPageResp.getUserType(), videoPageResp.getUserId())));
                        videoPageResp.setSelectedComment(selectedCommentMap.get(videoPageResp.getId()));
                    });
                }

                return ResponseData.success(new PageResult<>(postPage));
            default:
                throw new IllegalStateException("Unexpected value: " + req.getType());
        }
    }

    @Override
    public ResponseData otherBrowsePage(CollectPageReq req, UserVo userVo) {
        //收藏类型 1作品 2 动态
        switch (req.getType()){
            case 1:
                if (ObjectUtil.isNotEmpty(req.getTypeId())){
                    //根据类型id获取三级id
                    List<Long> typeIdList = worksTypeService.getIdsByTypeId(req.getTypeId());
                    if (typeIdList.isEmpty()){
                        return ResponseData.success(new PageResult<>(new Page<>(req.getPageNo(),req.getPageSize())));
                    }
                    req.setTypeIds(typeIdList);
                }

                Page<WorksPageResp> worksPage = baseMapper.worksBrowsePage(new Page<>(req.getPageNo(),req.getPageSize()),req,userVo);

                if (!worksPage.getRecords().isEmpty()){

                    Set<UserVo> userVoSet = worksPage.getRecords().stream().map(worksPageResp -> new UserVo(worksPageResp.getUserType(), worksPageResp.getStoreId())).collect(Collectors.toSet());
                    //查询用户信息
                    Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

                    //作品ids
                    List<Long> worksIds = worksPage.getRecords().stream().map(WorksPageResp::getId).collect(Collectors.toList());
                    //查询3D图
                    List<WorksPanorama> worksPanoramaList = worksPanoramaService.list(new QueryWrapper<WorksPanorama>().lambda().in(WorksPanorama::getWorksId, worksIds).orderByDesc(WorksPanorama::getCreateTime));

                    Map<Long, List<WorksPanorama>> map = worksPanoramaList.stream().collect(Collectors.groupingBy(WorksPanorama::getWorksId));

                    worksPage.getRecords().stream().forEach(worksPageResp ->{
                        worksPageResp.setUserInfo(userMap.get(new UserVo(worksPageResp.getUserType(), worksPageResp.getStoreId())));
                        worksPageResp.setWorksPanoramaList(map.get(worksPageResp.getId()));
                    });
                }

                return ResponseData.success(new PageResult<>(worksPage));
            case 2:
                Page<PostPageResp> postPage = baseMapper.postBrowsePage(new Page<>(req.getPageNo(), req.getPageSize()),req,userVo);

                if (!postPage.getRecords().isEmpty()){
                    Set<UserVo> userVoSet = postPage.getRecords().stream().map(postPageResp -> new UserVo(postPageResp.getUserType(), postPageResp.getUserId())).collect(Collectors.toSet());
                    //查询用户信息
                    Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

                    //精彩评论ids
                    List<Long> commentIds = postPage.getRecords().stream().filter(s-> ObjectUtil.isNotEmpty(s.getCommentId())).map(PostPageResp::getCommentId).collect(Collectors.toList());

                    //查询精选评论
                    Map<Long, SelectedComment> selectedCommentMap = postCommentService.getSelectedCommentMap(commentIds,userVo);

                    postPage.getRecords().stream().forEach(videoPageResp ->{
                        videoPageResp.setUserInfo(userMap.get(new UserVo(videoPageResp.getUserType(), videoPageResp.getUserId())));
                        videoPageResp.setSelectedComment(selectedCommentMap.get(videoPageResp.getId()));
                    });
                }

                return ResponseData.success(new PageResult<>(postPage));
            default:
                throw new IllegalStateException("Unexpected value: " + req.getType());
        }
    }
}
