package jnpf.cultivate.controller.web.gained;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.cultivate.mapper.FtbCultivateCourseChapterMapper;
import jnpf.cultivate.mapper.FtbCultivateCourseMapper;
import jnpf.cultivate.service.*;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.dto.gained.FtbGainedPagination;
import jnpf.model.cultivate.po.course.FtbCultivateCourse;
import jnpf.model.cultivate.po.course.FtbCultivateCourseChapter;
import jnpf.model.cultivate.po.gained.*;
import jnpf.model.cultivate.vo.gained.FtbCourseGainedForm;
import jnpf.model.cultivate.vo.gained.FtbCourseGainedInfoVO;
import jnpf.permission.UserApi;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.JsonUtil;
import jnpf.util.NoDataSourceBind;
import jnpf.util.UploaderUtil;
import jnpf.util.UserProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.simpleframework.xml.core.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * app岗位学习课程-心得体会
 */
@RestController
@Tag(name = "心得体会", description = "心得体会")
@RequestMapping("/course_gained")
public class FtbCourseGainedController {
    @Autowired
    private FtbCourseGainedService ftbCourseGainedService;
    @Autowired
    private FtbCourseGainedLikeService likeService;
    @Autowired
    private FtbCourseGainedShareService shareService;
    @Autowired
    private FtbCourseGainedCommentService commentService;
    @Autowired
    private FtbCultivateCourseMapper ftbCultivateCourseMapper;
    @Autowired
    private FtbCultivateCourseChapterMapper ftbCultivateCourseChapterMapper;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private UserApiV2Util userApiV2Util;

    @Operation(summary = "获取列表（移动端/web共用）")
    @GetMapping("/list")
    public ActionResult<PageListVO<FtbCourseGainedInfoVO>> list(FtbGainedPagination pagination) {
        List<FtbCourseGainedEntity> list = ftbCourseGainedService.getList(pagination);
        List<FtbCourseGainedInfoVO> listVo = list.isEmpty() ? new ArrayList<>() : getInfoVO(list, pagination.getType());
        List<FtbAppAttentionListVO> appAttentionList = new ArrayList<>();//shareApi.getAppAttentionList(new FtbAppAttentionPage());
//        if (CollectionUtils.isNotEmpty(appAttentionList)){
//            Map<String, FtbAppAttentionListVO> FtbAppAttentionListVOMap = appAttentionList.stream().filter(e -> e.getUserId() != null).collect(Collectors.toMap(FtbAppAttentionListVO::getUserId, Function.identity()));
//            if (MapUtils.isNotEmpty(FtbAppAttentionListVOMap)){
//                listVo.forEach(e->{
//                    FtbAppAttentionListVO FtbAppAttentionListVO = FtbAppAttentionListVOMap.get(e.getCreatorUserId());
//                    if (ObjectUtils.isNotEmpty(FtbAppAttentionListVO)){
//                        e.setIsAttention(FtbAppAttentionListVO.getFollowStatus());
//                    }else {
//                        e.setIsAttention(CourseEnums.FollowStatus.FALSE.getCode());
//                    }
//                });
//            }
//        }

        PaginationVO vo = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVo, vo);
    }

    @Operation(summary = "发布心得")
    @PostMapping("/{chapterId}/saveGained")
    @Parameters({
            @Parameter(name = "chapterId", description = "章节ID", required = true),
    })
    public ActionResult<String> saveGained(@PathVariable("chapterId") String chapterId,
                                           @RequestBody @Validate FtbCourseGainedForm gainedForm) {
        UserInfo userInfo = UserProvider.getUser();
//        UserEntity userEntityActionResult = userApi.getInfoById(userInfo.getUserId());
        UserBoundVO userEntityActionResult = userApiV2Util.getUserPrimaryBoundOne(userInfo.getUserId(), null);
        FtbCourseGainedEntity gainedEntity = gainedForm.getGained();
        if (Objects.isNull(gainedEntity.getOrganizeId())) {
            gainedEntity.setOrganizeId(userInfo.getOrganizeId());
        }
        if (Objects.isNull(gainedEntity.getPositionId()) && userEntityActionResult != null) {
            gainedEntity.setPositionId(userEntityActionResult.getPositionId());
        }
        gainedEntity.setChapterId(chapterId);
        ftbCourseGainedService.create(gainedEntity);

//        List<FtbCourseGainedReaderEntity> userList = gainedForm.getUserList();
//        userList.forEach(u -> {
//            u.setGainedId(gainedEntity.getId());
//            u.setTenantId(userInfo.getTenantId());
//            u.setCreatorTime(new Date());
//            u.setCreatorUserId(userInfo.getUserId());
//        });
//        //心得分享至广场
//        gainedService.sharingSquare(gainedEntity);
//        gainedReaderService.saveBatch(userList);
        return ActionResult.success("保存成功");
    }

    //    @Operation(summary = "获取章节末尾心得列表")
//    @GetMapping("/endGained")
//    public ActionResult<List<FtbChapterEndGainedVO>> getGainedListOfChapterEnd(@RequestParam String chapterId){
//        return ActionResult.success(ftbCourseGainedService.getGainedListOfChapterEnd(chapterId));
//    }
    @Operation(summary = "获取详情（移动端/web共用）")
    @GetMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<FtbCourseGainedInfoVO> info(@PathVariable("id") String id) {
        FtbCourseGainedInfoVO infoVO = getInfoVO(id);
        List<FtbAppAttentionListVO> appAttentionList = new ArrayList<>();// = shareApi.getAppAttentionList(new FtbAppAttentionPage());
//        if (CollectionUtils.isNotEmpty(appAttentionList)){
//            Map<String, FtbAppAttentionListVO> FtbAppAttentionListVOMap = appAttentionList.stream().filter(e -> e.getUserId() != null).collect(Collectors.toMap(FtbAppAttentionListVO::getUserId, Function.identity()));
//            if (MapUtils.isNotEmpty(FtbAppAttentionListVOMap)){
//                FtbAppAttentionListVO FtbAppAttentionListVO = FtbAppAttentionListVOMap.get(infoVO.getCreatorUserId());
//                if (ObjectUtils.isNotEmpty(FtbAppAttentionListVO)){
//                    infoVO.setIsAttention(FtbAppAttentionListVO.getFollowStatus());
//                }else {
//                    infoVO.setIsAttention(CourseEnums.FollowStatus.FALSE.getCode());
//                }
//            }
//        }
        return ActionResult.success(infoVO);
    }

    @NoDataSourceBind
    @Operation(summary = "获取详情（移动端/web共用）-不需要登录")
    @GetMapping("/other/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<FtbCourseGainedInfoVO> otherInfo(@PathVariable("id") String id) {
        return ActionResult.success(getInfoVO(id));
    }


    @Operation(summary = "删除（移动端/web共用)")
    @DeleteMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<String> delete(@PathVariable("id") String id) {
        UserInfo userInfo = userProvider.get();
        FtbCourseGainedEntity info = ftbCourseGainedService.getInfo(id);
        if (userInfo.getIsAdministrator()) {
            ftbCourseGainedService.delete(info);
            return ActionResult.success("删除成功");
        }
        if (ObjectUtils.isNotEmpty(userInfo) && ObjectUtils.isNotEmpty(info)
                && !userInfo.getUserId().equals(info.getCreatorUserId())) {
            return ActionResult.fail("删除失败，只能删除当前用户的心得体会");
        }
        ftbCourseGainedService.delete(info);
        return ActionResult.success("删除成功");
    }
//
//    @Operation(summary = "分页")
//    @GetMapping("/page")
//    public PageListVO<FtbCourseGainedInfoVO> getGainedInfoPage(FtbGainedQueryDto queryDto) {
//        List<FtbCourseGainedInfoVO> listVo = new ArrayList<>();
//        List<FtbCourseGainedEntity> entityList = ftbCourseGainedService.list(queryDto);
//        PageInfo<FtbCourseGainedEntity> pageInfo = new PageInfo<>(entityList);
//        entityList.forEach(g -> listVo.add(getInfoVO(g.getId())));
//        List<String> userIds = listVo.stream().map(FtbCourseGainedInfoVO::getCreatorUserId).collect(Collectors.toList());
//        List<PartUserInfoVo> userInfoVoList = userApi.getInfoByIds(userIds);
//        listVo.forEach(c -> {
//            Optional<PartUserInfoVo> infoVoOptional = userInfoVoList.stream()
//                    .filter(u -> c.getCreatorUserId().equals(u.getUserId())).findFirst();
//            if (infoVoOptional.isPresent()){
//                PartUserInfoVo partUserInfoVo = infoVoOptional.get();
//                c.setUserName(partUserInfoVo.getRealName());
//                c.setOrganizeName(partUserInfoVo.getOrganizeName());
//                c.setPositionName(partUserInfoVo.getPositionName());
//            }
//            if (Objects.nonNull(c.getReadType()) && c.getReadType() == 2){
//                List<FtbCourseGainedReaderEntity> readerEntityList = readerService.list(new LambdaQueryWrapper<FtbCourseGainedReaderEntity>()
//                        .eq(FtbCourseGainedReaderEntity::getGainedId, c.getId()));
//                c.setReaderList(readerEntityList.stream().map(FtbCourseGainedReaderEntity::getUserId).collect(Collectors.toList()));
//            }
//        });
//
//        PageListVO<FtbCourseGainedInfoVO> vo = new PageListVO<>();
//        PaginationVO paginationVO = new PaginationVO();
//        paginationVO.setTotal((int) pageInfo.getTotal());
//        paginationVO.setPageSize((long) pageInfo.getPageSize());
//        paginationVO.setCurrentPage((long) pageInfo.getPageNum());
//        vo.setList(listVo);
//        vo.setPagination(paginationVO);
//        return vo;
//    }

    private List<FtbCourseGainedInfoVO> getInfoVO(List<FtbCourseGainedEntity> list, Integer type) {
        String userId = userProvider.get().getUserId();
        List<String> ids = list.stream().map(FtbCourseGainedEntity::getId).collect(Collectors.toList());
        List<FtbCourseGainedInfoVO> infoVOs = new ArrayList<>();
        List<FtbCourseGainedShareEntity> shareNumberList = shareService.list(new LambdaQueryWrapper<FtbCourseGainedShareEntity>()
                .in(FtbCourseGainedShareEntity::getGainedId, ids));
        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, ids));
        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, ids));
        Map<String, List<FtbCourseGainedCommentEntity>> commentNumberGroup = CollectionUtils.isNotEmpty(commentNumberList) ?
                commentNumberList.stream().collect(Collectors.groupingBy(FtbCourseGainedCommentEntity::getGainedId)) : new HashMap<>();


        List<String> userIds = list.stream().map(FtbCourseGainedEntity::getCreatorUserId).collect(Collectors.toList());
//        List<PartUserInfoVo> userList = userApi.getInfoByIds(userIds);
        Map<String, UserBoundVO> userMap = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
        if (Objects.isNull(type) || type != 1) {
            userId = "";
        }

        List<FtbCourseGainedLikeEntity> likeEntityList = likeService.list(new LambdaQueryWrapper<FtbCourseGainedLikeEntity>()
                .in(FtbCourseGainedLikeEntity::getGainedId, ids)
                .eq(FtbCourseGainedLikeEntity::getLikeUserId, userId));

        list.forEach(entity -> {
            FtbCourseGainedInfoVO vo = JsonUtil.getJsonToBean(entity, FtbCourseGainedInfoVO.class);
            if (MapUtils.isNotEmpty(shareNumberGroup)) {
                vo.setShareNumber(CollectionUtils.isNotEmpty(shareNumberGroup.get(entity.getId())) ? (long) shareNumberGroup.get(entity.getId()).size() : 0L);
            }

            if (MapUtils.isNotEmpty(likeNumberGroup)) {
                vo.setLikeNumber(CollectionUtils.isNotEmpty(likeNumberGroup.get(entity.getId())) ? (long) likeNumberGroup.get(entity.getId()).size() : 0L);
            }

            if (MapUtils.isNotEmpty(commentNumberGroup)) {
                vo.setCommentNumber(CollectionUtils.isNotEmpty(commentNumberGroup.get(entity.getId())) ? (long) commentNumberGroup.get(entity.getId()).size() : 0L);
            }
            // 根据课程id获取到课程信息
            FtbCultivateCourse ftbCultivateCourse = ftbCultivateCourseMapper.selectById(entity.getCourseId());
            if (ObjectUtils.isNotEmpty(ftbCultivateCourse)) {
                vo.setCourseName(ftbCultivateCourse.getName());
            }
            // 根据章节id 获取章节信息
            FtbCultivateCourseChapter ftbCultivateCourseChapter = ftbCultivateCourseChapterMapper.selectById(entity.getChapterId());
            if (ObjectUtils.isNotEmpty(ftbCultivateCourseChapter)) {
                vo.setChapterName(ftbCultivateCourseChapter.getName());
            }
//            List<PartUserInfoVo> userInfoVoList = userList.stream()
//                    .filter(u -> u.getUserId().equals(entity.getCreatorUserId())).collect(Collectors.toList());
            UserBoundVO userBoundVO = userMap.get(entity.getCreatorUserId());
            if (userBoundVO != null) {
                vo.setUserName(userBoundVO.getUserName());
                vo.setOrganizeName(userBoundVO.getOrganizeName());
                vo.setPositionName(userBoundVO.getPositionName());
                vo.setHeadIcon(UploaderUtil.uploaderImg(userBoundVO.getHeadIcon()));
            }
            long count = likeEntityList.stream().filter(l -> l.getGainedId().equals(vo.getId())).count();
            vo.setLiked(0);
            if (count > 0) {
                vo.setLiked(1);
            }
            infoVOs.add(vo);
        });
        return infoVOs;
    }

    private FtbCourseGainedInfoVO getInfoVO(String id) {
        String userId = userProvider.get().getUserId();
        FtbCourseGainedEntity entity = ftbCourseGainedService.getInfo(id);
        FtbCourseGainedInfoVO vo = JsonUtil.getJsonToBean(entity, FtbCourseGainedInfoVO.class);
        long shareNumber = shareService.count(new LambdaQueryWrapper<FtbCourseGainedShareEntity>()
                .eq(FtbCourseGainedShareEntity::getGainedId, id));
        vo.setShareNumber(shareNumber);

        long likeNumber = likeService.count(new LambdaQueryWrapper<FtbCourseGainedLikeEntity>()
                .eq(FtbCourseGainedLikeEntity::getGainedId, id));
        vo.setLikeNumber(likeNumber);

        long commentNumber = commentService.count(new LambdaQueryWrapper<FtbCourseGainedCommentEntity>()
                .eq(FtbCourseGainedCommentEntity::getGainedId, id));
        vo.setCommentNumber(commentNumber);
        // 根据课程id 查询课程信息
        FtbCultivateCourse ftbCultivateCourse = ftbCultivateCourseMapper.selectById(entity.getCourseId());
        if (ObjectUtils.isNotEmpty(ftbCultivateCourse)) {
            vo.setCourseName(ftbCultivateCourse.getName());
        }
        // 根据章节id 获取章节信息
        FtbCultivateCourseChapter ftbCultivateCourseChapter = ftbCultivateCourseChapterMapper.selectById(entity.getChapterId());
        if (ObjectUtils.isNotEmpty(ftbCultivateCourseChapter)) {
            vo.setChapterName(ftbCultivateCourseChapter.getName());
        }
//        List<PartUserInfoVo> userList = userApi.getInfoByIds(Collections.singletonList(entity.getCreatorUserId()));
        UserBoundVO userInfoVo = userApiV2Util.getUserPrimaryBoundOne(entity.getCreatorUserId(), null);
        if (userInfoVo != null) {
            vo.setUserName(userInfoVo.getUserName());
            vo.setOrganizeName(userInfoVo.getOrganizeName());
            vo.setPositionName(userInfoVo.getPositionName());
            vo.setHeadIcon(UploaderUtil.uploaderImg(userInfoVo.getHeadIcon()));
        }
        //设置点赞标识
        List<FtbCourseGainedLikeEntity> likeEntityList = likeService.list(new LambdaQueryWrapper<FtbCourseGainedLikeEntity>()
                .eq(FtbCourseGainedLikeEntity::getGainedId, vo.getId())
                .eq(FtbCourseGainedLikeEntity::getLikeUserId, userId));
        vo.setLiked(0);
        if (likeEntityList.size() > 0) {
            vo.setLiked(1);
        }
        return vo;
    }


}