package com.tanpu.community.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanpu.biz.common.enums.RelTypeEnum;
import com.tanpu.community.api.beans.qo.ThemeQo;
import com.tanpu.community.api.beans.qo.TopicAttachment;
import com.tanpu.community.api.beans.qo.TopicAttachmentDetail;
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.beans.resp.CoursePackageSimpleResp;
import com.tanpu.community.api.beans.vo.feign.activity.OfflineActivitySimpleResp;
import com.tanpu.community.api.beans.vo.feign.fatools.UserInfoResp;
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.entity.community.TopicManagerEntity;
import com.tanpu.community.dao.entity.community.TopicSubjectEntity;
import com.tanpu.community.dao.mapper.community.TopicFollowRelMapper;
import com.tanpu.community.dao.mapper.community.TopicManagerMapper;
import com.tanpu.community.dao.mapper.community.TopicMapper;
import com.tanpu.community.dao.mapper.community.TopicSubjectMapper;
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.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
@EnableCaching
public class TopicService {

    @Resource
    TopicFollowRelMapper topicFollowRelMapper;

    @Resource
    TopicMapper topicMapper;

    @Resource
    private TopicManagerMapper topicManagerMapper;
    @Resource
    private FeignService feignService;
    @Resource
    private TopicSubjectMapper topicSubjectMapper;


    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) {
        List<TopicSubjectEntity> topicSubjectEntities = topicSubjectMapper.selectList(new LambdaQueryWrapper<TopicSubjectEntity>().eq(TopicSubjectEntity::getTopicId, topic.getTopicId()));
        if (CollectionUtils.isEmpty(topicSubjectEntities)) {
            topic.setAttachments(null);
        }

        ArrayList<TopicAttachment> attachements = new ArrayList<>();
        for (TopicSubjectEntity entity : topicSubjectEntities) {

            if (RelTypeEnum.FUND.type.equals(entity.getSubjectType().toString())) {
                // 基金
                TopicAttachment attach = TopicAttachment.builder().type(RelTypeEnum.FUND.type).detail(null).build();
                attachements.add(attach);
            }else if (RelTypeEnum.FUND_COMPANY.type.equals(entity.getSubjectType().toString())) {
                // 资管人
                TopicAttachment attach = TopicAttachment.builder().type(RelTypeEnum.FUND_COMPANY.type).detail(null).build();
                attachements.add(attach);
            }else if (RelTypeEnum.NEW_COURSE_WARE.type.equals(entity.getSubjectType().toString())) {
                // 课程包
                List<CoursePackageSimpleResp> coursePackage = feignService.getCoursePackageList(Collections.singletonList(entity.getSubjectId()));
                TopicAttachmentDetail detailVo = TopicAttachmentDetail.builder().coursePackage(coursePackage.get(0)).build();
                TopicAttachment attach = TopicAttachment.builder().type(RelTypeEnum.NEW_COURSE_WARE.type).detail(detailVo).build();
                attachements.add(attach);
            }else if (RelTypeEnum.OFFLINE_ACTIVITY.type.equals(entity.getSubjectType().toString())) {
                // 线下活动
                List<OfflineActivitySimpleResp> activitySimpleList = feignService.getActivitySimpleList(Collections.singletonList(entity.getSubjectId()));
                TopicAttachmentDetail detailVo = TopicAttachmentDetail.builder().activity(activitySimpleList.get(0)).build();
                TopicAttachment attach = TopicAttachment.builder().type(RelTypeEnum.OFFLINE_ACTIVITY.type).detail(detailVo).build();
                attachements.add(attach);
            }
        }


        topic.setAttachments(attachements);
    }


    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) {
        List<TopicManagerEntity> topicManagerEntities = topicManagerMapper.selectList(new LambdaQueryWrapper<TopicManagerEntity>().eq(TopicManagerEntity::getTopicId, topicId));

        List<String> managerIds = topicManagerEntities.stream().map(TopicManagerEntity::getUserId).collect(Collectors.toList());

        List<UserInfoResp> userList = feignService.getUserList(managerIds);

        if (CollectionUtils.isEmpty(userList)) {
            return "";
        }
        List<String> userNames = userList.stream().map(UserInfoResp::getNickName).collect(Collectors.toList());

        return StringUtils.join(userNames, "、");

    }
}