package com.tanpu.community.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanpu.common.uuid.UuidGenHelper;
import com.tanpu.community.api.beans.qo.ThemeQo;
import com.tanpu.community.api.beans.qo.TopicAttachement;
import com.tanpu.community.api.beans.qo.TopicFollowQo;
import com.tanpu.community.api.beans.qo.TopicPageDetailQo;
import com.tanpu.community.api.beans.qo.TopicRankQo;
import com.tanpu.community.api.enums.DeleteTagEnum;
import com.tanpu.community.api.enums.StatusEnum;
import com.tanpu.community.api.enums.TopicSpecialPermissionEnum;
import com.tanpu.community.dao.entity.community.TopicEntity;
import com.tanpu.community.dao.entity.community.TopicFollowRelEntity;
import com.tanpu.community.dao.mapper.community.TopicFollowRelMapper;
import com.tanpu.community.dao.mapper.community.TopicMapper;
import com.tanpu.community.util.ConvertUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


@Service
@EnableCaching
public class TopicService {

    @Resource
    TopicFollowRelMapper topicFollowRelMapper;

    @Resource
    TopicMapper topicMapper;

    @Resource
    private UuidGenHelper uuidGenHelper;
    @Resource
    private ThemeService themeService;
    @Resource
    private VisitLogService visitLogService;


    public List<TopicEntity> queryAll() {
        List<TopicEntity> retList = new ArrayList<>();

        Long lastId = 0L;
        while (true) {
            List<TopicEntity> tmpList = topicMapper.selectGtIdPageable(lastId, 100);
            if (tmpList.isEmpty()) {
                break;
            }
            retList.addAll(tmpList);
            lastId = tmpList.stream().map(TopicEntity::getId).max(Long::compareTo).get();
        }
        return retList;
    }


    public TopicEntity queryOnlineTopicById(String topicId) {
        return topicMapper.selectOne(new LambdaQueryWrapper<TopicEntity>()
                .eq(TopicEntity::getTopicId, topicId)
                .eq(TopicEntity::getIsConceal, StatusEnum.FALSE)
                .eq(TopicEntity::getDeleteTag, StatusEnum.FALSE));
    }

    // 根据话题id查询title,(包括已删除)
    public String queryTitleById(String topicId) {
        TopicEntity topicEntity = topicMapper.selectOne(new LambdaQueryWrapper<TopicEntity>()
                .eq(TopicEntity::getTopicId, topicId));
        return topicEntity != null ? topicEntity.getTopicTitle() : null;
    }

    public List<TopicEntity> queryByIds(List<String> topicIds) {
        if (CollectionUtils.isEmpty(topicIds)) {
            return Collections.emptyList();
        }
        return topicMapper.selectList(new LambdaQueryWrapper<TopicEntity>().in(TopicEntity::getTopicId, topicIds));
    }

    public List<TopicFollowQo> queryFollowTopic(String keyword, String userId) {
        // 用户的关注列表(包括专属)
        List<String> followTopicIds = topicFollowRelMapper.selectTopicIdByUserId(userId);
        if (CollectionUtils.isEmpty(followTopicIds)) {
            return Collections.emptyList();
        }

        List<TopicEntity> topicEntities = topicMapper.selectAllByTopicIdIn(followTopicIds);
        List<TopicFollowQo> topicFollowQos = ConvertUtil.topicEntityToFollowQos(topicEntities);
        return topicFollowQos;

    }


    public boolean addFollowTopic(String topicId, String userId) {
        TopicFollowRelEntity searchResult = topicFollowRelMapper.queryOneByTopicIdAndUserId(topicId, userId);
        if (searchResult == null) {
            TopicFollowRelEntity entity = TopicFollowRelEntity.builder()
                    .topicId(topicId)
                    .userId(userId)
                    .followTime(LocalDateTime.now())
                    .build();

            topicFollowRelMapper.insert(entity);
            return true;
        } else {
            searchResult.setFollowTime(LocalDateTime.now());
            searchResult.setDeleteTag(DeleteTagEnum.NOT_DELETED.getCode());
            topicFollowRelMapper.updateById(searchResult);
            return false;
        }
    }

    public void deleteFollowTopic(String topicId, String userId) {
        TopicFollowRelEntity searchResult = topicFollowRelMapper.queryOneByTopicIdAndUserId(topicId, userId);
        if (searchResult != null) {
            searchResult.setUnfollowTime(LocalDateTime.now());
            searchResult.setDeleteTag(DeleteTagEnum.DELETED.getCode());
            topicFollowRelMapper.updateById(searchResult);
        }
    }

    public void batchCheckPermission(List<TopicRankQo> content, String userId) {
        if (StringUtils.isBlank(userId)) {
            return;
        }
    }


    /**
     * 判断用户是否拥有权限(1对1)
     *
     * @param topicId
     * @param userId
     */
    public boolean checkPermission(String topicId, String userId) {

        TopicEntity topicEntity = queryOnlineTopicById(topicId);
        if (TopicSpecialPermissionEnum.FALSE.getCode().equals(topicEntity.getSpecialPermission())) {
            return true;
        }
        TopicFollowRelEntity topicFollowRelEntity = topicFollowRelMapper.queryOneByTopicIdAndUserId(topicId, userId);
        if (topicFollowRelEntity != null) {
            return true;
        } else {
            return false;
        }
    }


    public String getPermissionToast(String topicId) {

        String permission = "专业版会员";

        return "暂无权限参与此话题~您可联系官方客服 021- 了解详情";
        // return "该话题仅限" + permission + "可参与哦~";
    }

    public String queryManagers(String topicId) {
        return "小王、小李、小刘";
    }

    public void queryAttachments(TopicPageDetailQo topic) {
        TopicAttachement a1 = TopicAttachement.builder().type("88").detail(null).build();
        TopicAttachement a2 = TopicAttachement.builder().type("300").detail(null).build();
        TopicAttachement a3 = TopicAttachement.builder().type("323").detail(null).build();


        topic.setAttachments(Arrays.asList(a1, a2, a3));
    }

    public boolean checkFollow(String topicId, String userId) {
        if (StringUtils.isBlank(userId)) {
            return false;
        }
        TopicFollowRelEntity topicFollowRelEntity = topicFollowRelMapper.queryOneByTopicIdAndUserId(topicId, userId);
        return topicFollowRelEntity != null;
    }


    public void checkManager(String topicId, List<ThemeQo> themes) {
        String managerId = getManagerId(topicId);
        for (ThemeQo theme : themes) {
            theme.setManager(theme.getAuthorId().equals(managerId));
        }
    }

    public String getManagerId(String topicId) {
        return "123";

    }
}