package com.tanpu.community.manager;

import com.tanpu.community.api.beans.CommentReq;
import com.tanpu.community.api.beans.ForwardThemeDTO;
import com.tanpu.community.api.beans.ThemeDTO;
import com.tanpu.community.api.constants.BlockTypeEnum;
import com.tanpu.community.api.constants.CollectionTypeEnum;
import com.tanpu.community.api.constants.CommentTypeEnum;
import com.tanpu.community.dao.entity.community.*;
import com.tanpu.community.dao.entity.user.CurriculumResEntity;
import com.tanpu.community.dao.entity.user.OrderFlowEntity;
import com.tanpu.community.service.*;
import com.tanpu.community.util.ConvertUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ThemeManager {
    @Resource
    private ThemeService themeService;

    @Autowired
    private CollectionService collectionService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private FansRelService fansRelService;

    @Autowired
    private BlackListService blackListService;

    @Autowired
    private FinProResService finProResService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ZhiboService zhiboService;

    @Autowired
    private CurriculumResService curriculumResService;

    @Autowired
    private OrderFlowService orderFlowService;

    @Autowired
    private ThemeAttachmentService themeAttachmentService;

    // 返回推荐主题文章
    public List<ThemeDTO> selectHotThemes(String userId) {
        // TODO:根据算法计算推荐主题
        List<ThemeEntity> themeEntities = themeService.selectAll();
        List<ThemeDTO> themeDTOS = ConvertUtil.themeEntitiesToDTOs(themeEntities);
        for (ThemeDTO themeDTO : themeDTOS) {
            fillDTOExtraInfo(themeDTO, userId);
        }
        return themeDTOS;
    }


    // 返回关注主题
    public List<ThemeDTO> selectInterestThemes(String userId) {
        List<String> fansList = fansRelService.queryFansByFollowerId(userId).stream().map(FansRelEntity::getIdolId).collect(Collectors.toList());
        List<ThemeEntity> themeEntities = themeService.selectByFans(fansList);
        List<ThemeDTO> themeDTOS = ConvertUtil.themeEntitiesToDTOs(themeEntities);
        for (ThemeDTO themeDTO : themeDTOS) {
            fillDTOExtraInfo(themeDTO, userId);
        }
        return themeDTOS;
    }

    private String calUpToNowTime(LocalDateTime start) {
        Duration between = Duration.between(LocalDateTime.now(), start);
        long duration = between.toMinutes();
        if (duration < 1) {
            return "刚刚";
        } else if (duration < 60) {
            return duration + "分钟前";
        } else if (duration < 60 * 24) {
            return duration / 60 + "小时前";
        } else if (start.getYear() == LocalDateTime.now().getYear()) {
            return start.format(DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"));
        }
        return start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    // 点赞
    public void like(String themeId, String userId) {
        collectionService.addIfNotExist(themeId, userId, CollectionTypeEnum.LIKE);
    }

    public void unlike(String themeId, String userId) {
    }

    // 评论(对主题)
    public void comment(CommentReq req, String userId) {
        CommentEntity commentEntity = CommentEntity.builder()
                .targetId(req.getThemeId())
                .authorId(userId)
                .createBy(userId)
                .content(req.getComment())
                .commentType(CommentTypeEnum.THEME.getCode())
                .build();

        commentService.insertComment(commentEntity);
    }

    //转发
    public void forward(ForwardThemeDTO forwardThemeDTO, String userId) {
        ThemeEntity targetTheme = themeService.selectById(forwardThemeDTO.getFormerThemeId());
        ThemeEntity newTheme = ThemeEntity.builder()
                .content(targetTheme.getContent())
                .formerThemeId(targetTheme.getId())
                .authorId(userId)
                .createBy(userId)
                .build();

        themeService.insertTheme(newTheme);
    }


    //收藏
    public void favorite(String themeId, String userId) {
        collectionService.addIfNotExist(themeId, userId, CollectionTypeEnum.BOOK);
    }

    public void unFavorite(String themeId, String userId) {

    }

    //投诉(主题)
    public void complaint(String themeId, String user) {
        //TODO
    }

    //屏蔽(用户)
    public void blockUser(String themeId, String userId) {
        String blockId = themeService.selectById(themeId).getAuthorId();
        blackListService.addBlock(blockId, userId, BlockTypeEnum.USER);
    }

    // 解除屏蔽(用户)
    public void unblockUser(String themeId, String userId) {
    }

    // 屏蔽(主题)
    public void blockTheme(String themeId, String userId) {
        blackListService.addBlock(themeId, userId, BlockTypeEnum.THEME);
        BlackListEntity selectOne = blackListService.selectOne(userId, BlockTypeEnum.USER.getCode(), themeService.selectById(themeId).getAuthorId());
        if (selectOne == null) {
            blackListService.addBlock(themeService.selectById(themeId).getAuthorId(), userId, BlockTypeEnum.USER);
        }
    }

    // 解除屏蔽(主题)
    public void unblockTheme(String themeId, String userId) {
        blackListService.removeBlackList(themeId, userId, BlockTypeEnum.USER);
    }

    //屏蔽(内容)
//    public void blockContent(String themeId, String userId) {
//        BlackListEntity selectOne = blackListService.selectOne(userId, BlockTypeEnum.USER.getCode(), themeId);
//        if (selectOne==null){
//            blackListService.insertBlackList(userId, BlockTypeEnum.USER.getCode(), themeId);
//        }
//    }

    public void insert(ThemeEntity themeEntity) {
        themeService.insertTheme(themeEntity);
    }


    //查询话题所需关联信息
    private void fillDTOExtraInfo(ThemeDTO themeDTO,String userId) {
        List<ThemeAttachmentEntity> attachments = themeAttachmentService.selectByThemeId(themeDTO.getId());
        if (CollectionUtils.isEmpty(attachments)){
            return;
        }
        List<Object> obs = attachments.stream().map(themeAttachmentEntity -> transferAttachment(themeAttachmentEntity, userId)).collect(Collectors.toList());
        themeDTO.setAttachment(obs);
        //是否关注
        themeDTO.setUpToNowTime(calUpToNowTime(themeDTO.getCreateTime()));
        String authorId = themeDTO.getCreateBy();
        Map<String, FansRelEntity> fansMap = fansRelService.queryFansByFollowerId(userId).stream().collect(Collectors.toMap(FansRelEntity::getIdolId, c -> c));
        if (fansMap.containsKey(authorId)) {
            themeDTO.setFollow(true);
        }else {
            themeDTO.setFollow(false);
        }
        //TODO 添加用户名、头像、认证、是否关注
    }

    public Object transferAttachment(ThemeAttachmentEntity themeAttachment,String userId){
        switch (themeAttachment.getAttachType()) {
            //附件类型 1:产品 2:直播 3:短视频 4:课程
            //TODO ENTITY 转 DTO
            case 1:
                return finProResService.selectById(themeAttachment.getAttchId());
            case 2:
                return zhiboService.selectByid(themeAttachment.getAttchId());
            case 3:
                CurriculumResEntity curriculumResEntity = curriculumResService.selectShortVideo(themeAttachment.getAttchId());
                return curriculumResEntity;
            case 4:
                curriculumResEntity = curriculumResService.selectById(themeAttachment.getAttchId());
                //todo 栏目详情,需要判断当前用户是否购买
                OrderFlowEntity orderFlowEntity = orderFlowService.queryByUserAndProId(themeAttachment.getThemeId(), userId);
                return curriculumResEntity;
            default:
               return null;


        }
    }

}