package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import jnpf.base.UserInfo;
import jnpf.base.service.SuperServiceImpl;
import jnpf.cultivate.mapper.FtbCourseGainedMapper;
import jnpf.cultivate.service.*;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.dto.gained.FtbGainedPagination;
import jnpf.model.cultivate.dto.gained.FtbGainedQueryDto;
import jnpf.model.cultivate.po.gained.FtbCourseGainedEntity;
import jnpf.model.cultivate.po.gained.FtbCourseGainedLikeEntity;
import jnpf.model.cultivate.po.gained.FtbCourseGainedReaderEntity;
import jnpf.model.cultivate.vo.gained.FtbChapterEndGainedVO;
import jnpf.model.cultivate.vo.gained.FtbGroupGainedVO;
import jnpf.model.enums.CourseEnums;
import jnpf.permission.UserApi;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.util.RandomUtil;
import jnpf.util.UploaderUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

//import jnpf.memoo.share.ShareApi;

/**
 * 心得体会 服务实现类
 */
@Service
@Slf4j
public class FtbCourseGainedServiceImpl extends SuperServiceImpl<FtbCourseGainedMapper, FtbCourseGainedEntity> implements FtbCourseGainedService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private FtbCourseGainedReaderService readerService;
    @Autowired
    private FtbCourseGainedLikeService likeService;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Override
    public List<FtbCourseGainedEntity> getList(FtbGainedPagination pagination) {
        //通过UserProvider获取用户信息
        UserInfo userInfo = userProvider.get();
        QueryWrapper<FtbCourseGainedEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(pagination.getChapterId())) {
            queryWrapper.lambda().eq(FtbCourseGainedEntity::getChapterId, pagination.getChapterId());
        }
        if (!StringUtils.isEmpty(pagination.getOrganizeId())) {
            queryWrapper.lambda().eq(FtbCourseGainedEntity::getOrganizeId, pagination.getOrganizeId());
        }

        if (!StringUtils.isEmpty(pagination.getCourseId())) {
            queryWrapper.lambda().eq(FtbCourseGainedEntity::getCourseId, pagination.getCourseId());
        }
        if (!StringUtils.isEmpty(pagination.getKeyword())) {
//            List<MiniUserVo> userVoList = userApi.getUserByName(null, null, pagination.getKeyword());
            List<UserPageListVO> userVoList = userApiV2Util.getUserForNameOrPhone(pagination.getKeyword(), "", null);
            List<String> userIdList = userVoList.stream().map(UserPageListVO::getId).collect(Collectors.toList());
            if (userIdList.size() > 0) {
                queryWrapper.lambda().in(FtbCourseGainedEntity::getCreatorUserId, userIdList);
            } else {
                queryWrapper.lambda().in(FtbCourseGainedEntity::getCreatorUserId, "-1");
            }
        }
        if (Objects.nonNull(pagination.getType()) && pagination.getType() == 1) {
            List<FtbCourseGainedReaderEntity> readerEntityList = readerService.list(new LambdaQueryWrapper<FtbCourseGainedReaderEntity>()
                    .eq(FtbCourseGainedReaderEntity::getUserId, userInfo.getUserId()));
            List<String> list = readerEntityList.stream().map(FtbCourseGainedReaderEntity::getGainedId).collect(Collectors.toList());
            if (list.size() > 0) {
                queryWrapper.lambda().and(
                        t -> t.eq(FtbCourseGainedEntity::getReadType, 0)
                                .or().eq(FtbCourseGainedEntity::getCreatorUserId, userInfo.getUserId())
                                .or().in(FtbCourseGainedEntity::getId, list)
                );
            } else {
                queryWrapper.lambda().and(
                        t -> t.eq(FtbCourseGainedEntity::getReadType, 0)
                                .or().eq(FtbCourseGainedEntity::getCreatorUserId, userInfo.getUserId())
                );
            }
        }
        //排序
        if (StringUtils.isEmpty(pagination.getSidx())) {
        } else {
            queryWrapper = "asc".equalsIgnoreCase(pagination.getSort()) ? queryWrapper.orderByAsc(pagination.getSidx()) : queryWrapper.orderByDesc(pagination.getSidx());
        }
        Page<FtbCourseGainedEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<FtbCourseGainedEntity> userIPage = this.page(page, queryWrapper);
        return pagination.setData(userIPage.getRecords(), page.getTotal());
    }

    @Override
    public List<FtbChapterEndGainedVO> getGainedListOfChapterEnd(String chapterId) {
        List<FtbCourseGainedEntity> list = new ArrayList<>();//ftbCourseGainedMapper.getGainedListOfChapterEnd(chapterId);
        //查询用户信息
//        List<PartUserInfoVo> infoByIds = userApi.getInfoByIds(list.stream().map(FtbCourseGainedEntity::getCreatorUserId).collect(Collectors.toList()));
        List<UserBoundVO> userPrimaryBoundBatchReturnList = userApiV2Util.getUserPrimaryBoundBatchReturnList(list.stream().map(FtbCourseGainedEntity::getCreatorUserId).collect(Collectors.toList()), null);
        Map<String, UserBoundVO> collect1 = userPrimaryBoundBatchReturnList.stream().collect(Collectors.toMap(UserBoundVO::getId, user -> user));
        List<FtbGroupGainedVO> gainedDetailByIds = getGainedDetailByIds(list.stream().map(FtbCourseGainedEntity::getId).collect(Collectors.toList()));
        Map<String, FtbGroupGainedVO> gainedMap = gainedDetailByIds.stream().collect(Collectors.toMap(FtbGroupGainedVO::getEventId, gained -> gained));
        return list.stream().map(v -> {
            UserBoundVO user = collect1.getOrDefault(v.getCreatorUserId(), new UserBoundVO());
            FtbGroupGainedVO detail = gainedMap.getOrDefault(v.getId(), new FtbGroupGainedVO());
            FtbChapterEndGainedVO build = FtbChapterEndGainedVO.builder().realName(user.getUserName()).headIcon(UploaderUtil.uploaderImg(user.getHeadIcon())).time(v.getCreatorTime()).build();
            BeanUtils.copyProperties(detail, build);
            return build;
        }).collect(Collectors.toList());
    }

    @Override
    public FtbCourseGainedEntity getInfo(String id) {
        QueryWrapper<FtbCourseGainedEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FtbCourseGainedEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    @DSTransactional
    public void create(FtbCourseGainedEntity entity) {
        UserInfo userInfo = userProvider.get();
        entity.setId(RandomUtil.uuId());
        entity.setCreatorUserId(userInfo.getUserId());
        entity.setTenantId(userInfo.getTenantId());
        entity.setLastModifyTime(new Date());
        entity.setStatus(1);
        entity.setEnabledMark(CourseEnums.EnabledMarkType.VALID.getCode());
        this.save(entity);
        // ftbGroupEventService.add(entity.getCourseId(), entity.getId(), null, FtbGroupEventTypeEnum.GAINED.getCode());
    }

    @Override
    @Transactional
    public void update(String id, FtbCourseGainedEntity entity) {
        entity.setId(id);
        this.updateById(entity);
    }

    @Override
    public void delete(FtbCourseGainedEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
            // ftbGroupEventService.del(entity.getId());
        }
    }

    @Override
    public List<FtbCourseGainedEntity> list(FtbGainedQueryDto queryDto) {
        LambdaQueryWrapper<FtbCourseGainedEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(queryDto.getUserId()) && queryDto.getType() == 0) {
            //查询用户发布和可查看的
            List<FtbCourseGainedReaderEntity> readerEntityList = readerService.list(new LambdaQueryWrapper<FtbCourseGainedReaderEntity>()
                    .eq(FtbCourseGainedReaderEntity::getUserId, queryDto.getUserId()));
            List<String> readList = readerEntityList.stream().map(FtbCourseGainedReaderEntity::getGainedId).collect(Collectors.toList());
            if (readList.size() == 0) {
                queryWrapper.eq(FtbCourseGainedEntity::getCreatorUserId, queryDto.getUserId());
            } else {
                queryWrapper.eq(FtbCourseGainedEntity::getCreatorUserId, queryDto.getUserId())
                        .or().in(FtbCourseGainedEntity::getId, readList);
            }
        }
        if (queryDto.getType() == 1) {
            //查询用户发布的
            queryWrapper.eq(FtbCourseGainedEntity::getCreatorUserId, queryDto);
        } else if (queryDto.getType() == 2) {
            //查询用户点赞的
            List<FtbCourseGainedLikeEntity> likeEntityList = likeService.list(new LambdaQueryWrapper<FtbCourseGainedLikeEntity>()
                    .eq(FtbCourseGainedLikeEntity::getLikeUserId, queryDto.getUserId()));
            List<String> likeList = likeEntityList.stream().map(FtbCourseGainedLikeEntity::getGainedId).collect(Collectors.toList());
            if (likeList.size() == 0) {
                return new ArrayList<>();
            }
            queryWrapper.in(FtbCourseGainedEntity::getId, likeList);
        }
        queryWrapper.orderByDesc(FtbCourseGainedEntity::getCreatorTime);
        PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
        return list(queryWrapper);
    }

    @Override
    public List<FtbGroupGainedVO> getGainedDetailByIds(List<String> gainedIds) {
        if (CollUtil.isEmpty(gainedIds)) {
            return CollUtil.newArrayList();
        }
        List<FtbCourseGainedEntity> FtbCourseGainedEntities = listByIds(gainedIds);
        if (CollUtil.isEmpty(FtbCourseGainedEntities)) {
            return CollUtil.newArrayList();
        }
        // TODO
//        //查询课程详情
//        List<String> courseIds = FtbCourseGainedEntities.stream().map(FtbCourseGainedEntity::getCourseId).collect(Collectors.toList());
//        List<FtbCourseEntity> FtbCourseEntities = courseService.listByIds(courseIds);
//        Map<String, FtbCourseEntity> courseMap = FtbCourseEntities.stream().collect(Collectors.toMap(course -> course.getId(), course -> course));
//        //查询章节详情
//        List<String> chapterIds = FtbCourseGainedEntities.stream().map(FtbCourseGainedEntity::getChapterId).collect(Collectors.toList());
//        List<FtbCourseChapterEntity> FtbCourseChapterEntities = courseChapterService.listByIds(chapterIds);
//        Map<String, FtbCourseChapterEntity> chapterMap = FtbCourseChapterEntities.stream().collect(Collectors.toMap(chapter -> chapter.getId(), chapter -> chapter));
//        List<FtbCourseGainedShareEntity> shareNumberList = shareService.list(new LambdaQueryWrapper<FtbCourseGainedShareEntity>()
//                .in(FtbCourseGainedShareEntity::getGainedId, gainedIds));
//        Map<String, List<FtbCourseGainedShareEntity>> shareNumberGroup = CollectionUtils.isNotEmpty(shareNumberList) ?
//                shareNumberList.stream().collect(Collectors.groupingBy(FtbCourseGainedShareEntity::getGainedId)) : new HashMap<>();
//
//        List<FtbCourseGainedLikeEntity> likeNumberList = likeService.list(new LambdaQueryWrapper<FtbCourseGainedLikeEntity>()
//                .in(FtbCourseGainedLikeEntity::getGainedId, gainedIds));
//        Map<String, List<FtbCourseGainedLikeEntity>> likeNumberGroup = CollectionUtils.isNotEmpty(likeNumberList) ?
//                likeNumberList.stream().collect(Collectors.groupingBy(FtbCourseGainedLikeEntity::getGainedId)) : new HashMap<>();
//
//        List<FtbCourseGainedCommentEntity> commentNumberList = commentService.list(new LambdaQueryWrapper<FtbCourseGainedCommentEntity>()
//                .in(FtbCourseGainedCommentEntity::getGainedId, gainedIds));
//        Map<String, List<FtbCourseGainedCommentEntity>> commentNumberGroup = CollectionUtils.isNotEmpty(commentNumberList) ?
//                commentNumberList.stream().collect(Collectors.groupingBy(FtbCourseGainedCommentEntity::getGainedId)) : new HashMap<>();
//        String loginUserId = UserProvider.getLoginUserId();
//        return FtbCourseGainedEntities.stream().map(gained -> {
//            FtbGroupGainedVO FtbCourseGainedInfoVO = new FtbGroupGainedVO();
//            FtbCourseGainedInfoVO.setContent(gained.getContent());
//            FtbCourseGainedInfoVO.setEventId(gained.getId());
//            //课程
//            FtbCourseEntity FtbCourseEntity = courseMap.get(gained.getCourseId());
//            FtbCourseGainedInfoVO.setCourseId(gained.getCourseId());
//            FtbCourseGainedInfoVO.setCourseName(FtbCourseEntity.getName());
//            FtbCourseGainedInfoVO.setCourseIcon(FtbCourseEntity.getCover());
//            //章节
//            FtbCourseChapterEntity FtbCourseChapterEntity = chapterMap.get(gained.getChapterId());
//            FtbCourseGainedInfoVO.setChapter(FtbCourseChapterEntity.getName());
//            FtbCourseGainedInfoVO.setChapterId(FtbCourseChapterEntity.getId());
//            //分享数
//            FtbCourseGainedInfoVO.setForwardNum(shareNumberGroup.getOrDefault(gained.getId(), CollUtil.newArrayList()).size());
//            //点赞数
//            List<FtbCourseGainedLikeEntity> orDefault = likeNumberGroup.getOrDefault(gained.getId(), CollUtil.newArrayList());
//            FtbCourseGainedInfoVO.setLikeNum(orDefault.size());
//            //是否已点赞
//            List<FtbCourseGainedLikeEntity> collect = orDefault.stream().filter(like -> StringUtil.equals(loginUserId, like.getLikeUserId())).collect(Collectors.toList());
//            FtbCourseGainedInfoVO.setIsLike(!collect.isEmpty());
//            //评论数
//            FtbCourseGainedInfoVO.setReplyNum(commentNumberGroup.getOrDefault(gained.getId(), CollUtil.newArrayList()).size());
//            return FtbCourseGainedInfoVO;
//        }).collect(Collectors.toList());
        return null;
    }

//    @Override
//    public void sharingSquare(FtbCourseGainedEntity gainedEntity) {
//        //add
//        ShareContentEntityFormContent shareContentEntityFormContent = new ShareContentEntityFormContent();
//
//        //用户id
//        UserInfo userInfo = userProvider.get();
//        String userId = userInfo.getId();
//
//        String content = gainedEntity.getContent();
//        String contentId = gainedEntity.getCourseId();
//
//        FtbCourseEntity FtbCourse = FtbCourseService.getById(contentId);
//
//        shareContentEntityFormContent.setUserId(userId);
//        shareContentEntityFormContent.setContent(StringUtils.isEmpty(content) ? "" : content);
//        //fixme 未提供图片地址
//        shareContentEntityFormContent.setPicture("");
//        shareContentEntityFormContent.setContentId(ObjectUtils.isEmpty(FtbCourse) ? null : contentId);
//        shareContentEntityFormContent.setCourseName(ObjectUtils.isEmpty(FtbCourse) ? "" :
//                FtbCourse.getName());
//        try {
//            Boolean shareFeignSate = shareApi.publishContent(shareContentEntityFormContent);
//            log.info("--------分享到广场内部接口调用成功--------");
//            log.info("--------分享到广场是否成功:{}", shareFeignSate + "---------");
//        } catch (Exception e) {
//            log.debug("--------分享到广场内部接口调用失败--------");
//            log.error("失败原因:{}", e.getMessage());
//        }
//    }
}