package com.tanpu.community.manager;

import com.tanpu.common.exception.BizException;
import com.tanpu.common.util.JsonUtil;
import com.tanpu.community.api.beans.qo.FormerThemeQo;
import com.tanpu.community.api.beans.qo.ThemeQo;
import com.tanpu.community.api.beans.req.homepage.QueryRecordThemeReq;
import com.tanpu.community.api.beans.req.theme.*;
import com.tanpu.community.api.enums.BlockTypeEnum;
import com.tanpu.community.api.enums.CollectionTypeEnum;
import com.tanpu.community.api.enums.ThemeListTypeEnum;
import com.tanpu.community.api.enums.ThemeTypeEnum;
import com.tanpu.community.dao.entity.community.BlackListEntity;
import com.tanpu.community.dao.entity.community.CollectionEntity;
import com.tanpu.community.dao.entity.community.ThemeAttachmentEntity;
import com.tanpu.community.dao.entity.community.ThemeEntity;
import com.tanpu.community.service.*;
import com.tanpu.community.service.other.BlackListService;
import com.tanpu.community.util.ConvertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

    @Autowired
    private CollectionService collectionService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private FollowRelService followRelService;

    @Autowired
    private BlackListService blackListService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ThemeAttachmentService themeAttachmentService;

    @Autowired
    private HomePageService homePageService;

    @Resource
    private ProductService productService;

    @Autowired
    private OSSFileService ossFileService;


    public void publishTheme(CreateThemeReq req, String userId) {

        //TODO 敏感词过滤

        //保存主题表
        ThemeEntity themeEntity = new ThemeEntity();
        BeanUtils.copyProperties(req, themeEntity);
        themeEntity.setAuthorId(userId);
        themeEntity.setContent(JsonUtil.toJson(req.getContent()));
        themeService.insertTheme(themeEntity);
        //保存附件表
        List<ThemeAttachmentEntity> themeAttachments = ConvertUtil.themeReqToAttachmentList(req, themeEntity.getThemeId());
        themeAttachmentService.insertList(themeAttachments);
    }

    // 返回推荐主题文章
    public List<ThemeQo> queryThemes(ThemeListReq req, String userId) {
        List<ThemeEntity> themeEntities = new ArrayList<>();
        if (ThemeListTypeEnum.RECOMMEND.getCode().equals(req.getType())) {
            // TODO:推荐
            themeEntities = themeService.selectAll(req.getLastId(), req.getPageSize());

        } else if (ThemeListTypeEnum.FOLLOW.getCode().equals(req.getType())) {
            //根据关注列表查询
            List<String> fansList = followRelService.queryFansByFollowerId(userId);
            themeEntities = themeService.queryByFans(fansList, req.getLastId(), req.getPageSize());

        } else if (ThemeListTypeEnum.TOPIC_HOT.getCode().equals(req.getType())) {
            //TODO 根据话题查询热门
            if (StringUtils.isEmpty(req.getTopicId())) throw new BizException("TopicId为空");
            themeEntities = themeService.queryByTopic(req.getTopicId(), req.getLastId(), req.getPageSize());
        } else if (ThemeListTypeEnum.TOPIC_LATEST.getCode().equals(req.getType())) {
            //TODO 根据话题查询最新
            if (StringUtils.isEmpty(req.getTopicId())) throw new BizException("TopicId为空");
            themeEntities = themeService.queryByTopic(req.getTopicId(), req.getLastId(), req.getPageSize());
        }
        //组装详情
        return convertEntityToQo(themeEntities, userId);
    }

    // 返回用户发布、回复、收藏的主题列表
    public List<ThemeQo> queryThemesByUser(QueryRecordThemeReq req, String userId) {
//        TODO
//        List<ThemeEntity> themeEntities = themeService.queryByUser(req.getUserId(), req.getPageSize(),req.getLastId());
        List<ThemeEntity> themeEntities = themeService.selectAll(req.getLastId(), req.getPageSize());
        return convertEntityToQo(themeEntities, userId);
    }


    //查询正文
    public ThemeQo getDetail(String themeId, String userId) {

        ThemeEntity themeEntity = themeService.queryByThemeId(themeId);
        if (themeEntity == null) {
            throw new BizException("找不到帖子id:" + themeId);
        }
        ThemeQo themeQo = ConvertUtil.themeEntityToQo(themeEntity);
        buildMainTestExtraInfo(themeQo, userId);
        return themeQo;
    }

    // 点赞/取消点赞
    public void like(LikeThemeReq req, String userId) {
        //todo 枚举值
        if (1==req.getType()){
            collectionService.addIfNotExist(req.getThemeId(), userId, CollectionTypeEnum.LIKE_THEME);
        }else if (2==req.getType()) {
            collectionService.delete(req.getThemeId(), userId, CollectionTypeEnum.LIKE_THEME);
        }

    }

    //收藏/取消收藏
    public void collect(CollectThemeReq req, String userId) {
        //todo 枚举值
        if (1==req.getType()){
            collectionService.addIfNotExist(req.getThemeId(), userId, CollectionTypeEnum.COLLECT_THEME);
        }else if (2==req.getType()) {
            collectionService.delete(req.getThemeId(), userId, CollectionTypeEnum.COLLECT_THEME);
        }
    }

    //转发
    public void forward(ForwardThemeReq req, String userId) {
        ThemeEntity targetTheme = themeService.queryByThemeId(req.getFormerThemeId());
        ThemeEntity newTheme = ThemeEntity.builder()
                .content(JsonUtil.toJson(req.getContent()))
                .topicId(req.getTopicId())
                .formerThemeId(req.getFormerThemeId())
                .authorId(userId)
                .themeType(ThemeTypeEnum.FORWARD.getCode())
                .build();

        themeService.insertTheme(newTheme);
    }





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

    //    屏蔽(用户)
    public void blockUser(String blockUser, String userId) {
        BlackListEntity selectOne = blackListService.selectOne(blockUser, userId, BlockTypeEnum.USER.getCode());
        if (selectOne == null) {
            blackListService.addBlock(blockUser, userId, BlockTypeEnum.USER);
        }
    }

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

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

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


    //主题Entity转QO
    private List<ThemeQo> convertEntityToQo(List<ThemeEntity> themeEntities, String userId) {
        //Entity转Qo
        List<ThemeQo> themeQos = ConvertUtil.themeEntitiesToDTOs(themeEntities);
        //批量查询附件detail
        productService.transferAttachments(themeQos);
        for (ThemeQo themeQO : themeQos) {

            buildThemeQoExtraInfo(userId, themeQO);
        }
        return themeQos;
    }


    //组装主题列表
    private void buildThemeQoExtraInfo(String userId, ThemeQo themeQo) {
        //附件列表

        String themeId = themeQo.getThemeId();

        //迄今时间
        themeQo.setUpToNowTime(calUpToNowTime(themeQo.getCreateTime()));
        //是否关注作者
        String authorId = themeQo.getAuthorId();
        Set<String> fansSet = new HashSet<>(followRelService.queryFansByFollowerId(userId));
        themeQo.setFollow(fansSet.contains(authorId));
        //是否点赞
        CollectionEntity likeEntity = collectionService.getNotDeleteTargetCollection(themeId, userId, CollectionTypeEnum.LIKE_THEME);
        themeQo.setHasLiked(likeEntity!=null);
        //是否转发
        Integer forwardCountByUser = themeService.getForwardCountByUser(themeId, userId);
        themeQo.setHasForward(forwardCountByUser>0);
        //转发原文
        buildFormerTheme(themeQo);
        //热点数据:点赞,收藏,转发
        Integer likeCount = collectionService.getCountByTypeAndId(themeId, CollectionTypeEnum.LIKE_THEME);
        Integer bookCount = collectionService.getCountByTypeAndId(themeId, CollectionTypeEnum.COLLECT_THEME);
        Integer forwardCount = themeService.getForwardCountById(themeId);
        themeQo.setCommentCount(bookCount);
        themeQo.setLikeCount(likeCount);
        themeQo.setForwardCount(forwardCount);
    }

    //组装正文详情
    private void buildMainTestExtraInfo(ThemeQo themeQo, String userId) {
        //附件列表
        String themeId = themeQo.getThemeId();

        productService.transferAttachement(themeQo);
        //迄今时间
        themeQo.setUpToNowTime(calUpToNowTime(themeQo.getCreateTime()));
        //转发原文
        buildFormerTheme(themeQo);

        return;
    }

    private void buildFormerTheme(ThemeQo themeQo) {
        String formerThemeId = themeQo.getFormerThemeId();
        if (StringUtils.isNotEmpty(formerThemeId)){
            ThemeQo formerTheme = ConvertUtil.themeEntityToQo2(themeService.queryByThemeId(formerThemeId));
            if (formerTheme==null){
                throw new BizException("转发主题Id错误,id:"+formerThemeId);
            }
            productService.transferAttachement(formerTheme);
            FormerThemeQo f = FormerThemeQo.builder().formerThemeId(formerThemeId)
                    .forwardContent(formerTheme.getContent())
                    .userImg(formerTheme.getUserImg())
                    .nickName(formerTheme.getNickName())
                    .build();
            themeQo.setFormerTheme(f);
        }
    }


    //计算迄今时间
    private String calUpToNowTime(LocalDateTime start) {
        Duration between = Duration.between(start, LocalDateTime.now());
        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 delete(String themeId) {

        themeService.deleteById(themeId);
    }
}