package com.YuyeTech.TPlat.service.impl;

import com.YuyeTech.TPlat.VO.ResultVO;
import com.YuyeTech.TPlat.dataobject.GameInfo;
import com.YuyeTech.TPlat.dataobject.Recommend;
import com.YuyeTech.TPlat.service.FavoritesService;
import com.YuyeTech.TPlat.service.GameTagReferenceService;
import com.YuyeTech.TPlat.service.RecommendService;
import com.YuyeTech.TPlat.dto.GameDTO;
import com.YuyeTech.TPlat.repository.GameInfoRepository;
import com.YuyeTech.TPlat.repository.RecommendRepository;
import com.YuyeTech.TPlat.utils.AliyunOSSUtil;
import com.YuyeTech.TPlat.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author:slambb
 * @date:2020/2/4
 */
@Service
@Slf4j
public class RecommendServiceImpl implements RecommendService {
    @Autowired
    private RecommendRepository recommendRepository;

    @Autowired
    private GameInfoRepository gameInfoRepository;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private FavoritesService favoritesService;

    @Autowired
    private GameTagReferenceService gameTagReferenceService;

    @Override
    public Map findByRecommendType(String userId, Integer recommendType, String endTime, Pageable pageable) {

        //排序规则和分页
        Specification<Recommend> specification = new Specification<Recommend>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                //增加筛选条件
                Predicate predicate = cb.conjunction();
                predicate.getExpressions().add(cb.equal(root.get("recommendType").as(String.class), recommendType));

                //结束日期
                if (endTime != null && !endTime.trim().equals("")) {
                    //createTime
                    predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("showTime").as(String.class), endTime));
                }

                return predicate;
            }
        };
        //1.获取推荐的对应对象id
        List<String> objectId = recommendRepository.findAll(specification, pageable).stream()
                .map(e -> e.getRObjectId()).collect(Collectors.toList());
        //2.根据游戏id 查找游戏
        Map map = new HashMap();
        List<GameDTO> gameInfos = new ArrayList<>();
        if (objectId.size() != 0) {
            //游戏返回对应的列表
//            log.info(" ===== GIRepFindByGameIdInOrderByField{}",gameInfos);
            gameInfos = gameInfoRepository.GIRepFindByGameIdInOrderByField(objectId).stream().map(e ->
                    {
//                        log.info("{} == ,{}",e.getGameName() , e.getGameIcon());
                        return new GameDTO(
                                e.getGameId(),
                                e.getGameName(),
                                aliyunOSSUtil.addDomainName(e.getGameIcon()),
                                e.getGameDescription(),
                                aliyunOSSUtil.addDomainName(e.getGamePicture()),
                                favoritesService.findByUserIdAndFObjectId(userId, e.getGameId()),
                                e.getGameRankingId(),
                                e.getGameRankingShow().equals(1),
                                e.getCreateTime(),
                                gameTagReferenceService.findGameTagByGameId(e.getGameRankingId(), e.getGameId()),
                                e.getPlatform()
                        );
                    }
            ).collect(Collectors.toList());
            map.put("gameList", gameInfos);
        } else {
            map.put("gameList", gameInfos);
        }

        return map;
    }

    @Override
    public Map findByRecommendTypeAndPlatform(String userId, Integer recommendType, Integer platform, String endTime, Pageable pageable) {

        //排序规则和分页
        Specification<Recommend> specification = new Specification<Recommend>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                //增加筛选条件
                Predicate predicate = cb.conjunction();
                predicate.getExpressions().add(cb.equal(root.get("recommendType").as(String.class), recommendType));
                //结束日期
                if (endTime != null && !endTime.trim().equals("")) {
                    //createTime
                    predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("showTime").as(String.class), endTime));
                }

                return predicate;
            }
        };
        //1.获取推荐的对应对象id
        List<String> objectId = recommendRepository.findAll(specification, pageable).stream()
                .map(e -> e.getRObjectId()).collect(Collectors.toList());
        //2.根据游戏id 查找游戏
        Map map = new HashMap();
        List<GameDTO> gameInfos = new ArrayList<>();
        if (objectId.size() != 0) {
            //游戏返回对应的列表
//            log.info(" ===== GIRepFindByGameIdInOrderByField{}",gameInfos);
            gameInfos = gameInfoRepository.GIRepFindByGameIdInOrderByField(objectId).stream()
                    .filter(e->e.getPlatform().equals(platform)|| e.getPlatform().equals(2)).map(e ->
                    {
//                        log.info("{} == ,{}",e.getGameName() , e.getGameIcon());
                        return new GameDTO(
                                e.getGameId(),
                                e.getGameName(),
                                aliyunOSSUtil.addDomainName(e.getGameIcon()),
                                e.getGameDescription(),
                                aliyunOSSUtil.addDomainName(e.getGamePicture()),
                                favoritesService.findByUserIdAndFObjectId(userId, e.getGameId()),
                                e.getGameRankingId(),
                                e.getGameRankingShow().equals(1),
                                e.getCreateTime(),
                                gameTagReferenceService.findGameTagByGameId(e.getGameRankingId(), e.getGameId()),
                                e.getPlatform()
                        );
                    }
            ).collect(Collectors.toList());
            map.put("gameList", gameInfos);
        } else {
            map.put("gameList", gameInfos);
        }

        return map;
    }

    @Override
    public List<GameInfo> TDFindByRecommendType(Integer recommendType, Pageable pageable) {
        //1.获取推荐的对应对象id
        List<String> objectId = recommendRepository.findAll(pageable).stream()
                .map(e -> e.getRObjectId()).collect(Collectors.toList());
        //2.根据游戏id 查找游戏
        List<GameInfo>  gameInfos = gameInfoRepository.GIRepFindByGameIdInOrderByField(objectId);
        return gameInfos;
    }

    @Override
    public Map findTwoListsByAll(String userId, String endTime, Pageable pageable) {
        return null;
    }

    @Override
    public Recommend addRecommend(Recommend recommend) {
        return recommendRepository.save(recommend);
    }

    @Override
    @Transactional
    public String deleteByGameId(String gameId) {
        recommendRepository.deleteByRObjectId(gameId);
        return "删除推荐";
    }
}
