package jnpf.cultivate.controller.web.gained;

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.service.FtbCourseGainedCommentService;
import jnpf.cultivate.service.FtbCourseGainedLikeService;
import jnpf.cultivate.service.FtbCourseGainedService;
import jnpf.cultivate.service.FtbCourseGainedShareService;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.dto.gained.FtbCommentPagination;
import jnpf.model.cultivate.po.gained.FtbCourseGainedCommentEntity;
import jnpf.model.cultivate.po.gained.FtbCourseGainedEntity;
import jnpf.model.cultivate.po.gained.FtbCourseGainedLikeEntity;
import jnpf.model.cultivate.po.gained.FtbCourseGainedShareEntity;
import jnpf.model.cultivate.vo.gained.FtbCourseGainedCommentVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.JsonUtil;
import jnpf.util.UploaderUtil;
import jnpf.util.UserProvider;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.simpleframework.xml.core.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * app岗位学习课程-心得评论
 */
@RestController
@Tag(name = "心得评论", description = "心得评论")
@RequestMapping("/course_gained_comment")
public class FtbCourseGainedCommentController {

    @Autowired
    private FtbCourseGainedCommentService ftbCourseGainedCommentService;

    @Autowired
    private FtbCourseGainedService gainedService;

    @Autowired
    FtbCourseGainedLikeService likeService;

    @Autowired
    FtbCourseGainedShareService shareService;

    @Autowired
    private UserApiV2Util userApiV2Util;

    /**
     * （移动端/web共用）
     *
     * @param pagination
     * @return
     */
    @Operation(summary = "获取心得评论获取列表")
    @GetMapping("/list")
    public ActionResult<PageListVO<FtbCourseGainedCommentVO>> list(FtbCommentPagination pagination) {
        List<FtbCourseGainedCommentEntity> entity = ftbCourseGainedCommentService.getList(pagination);
        List<FtbCourseGainedCommentVO> listVo = JsonUtil.getJsonToList(JsonUtil.getObjectToString(entity), FtbCourseGainedCommentVO.class);
        PaginationVO vo = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        List<String> userIds = listVo.stream().map(FtbCourseGainedCommentVO::getCreatorUserId).collect(Collectors.toList());
//        Map<String, PartUserInfoVo> map = userApi.getInfoByIds(userIds).stream().collect(Collectors.toMap(PartUserInfoVo::getUserId, Function.identity()));
        Map<String, UserBoundVO> map = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
        Map<String, FtbCourseGainedCommentEntity> nameMap = entity.stream()
                .collect(Collectors.toMap(FtbCourseGainedCommentEntity::getId, Function.identity(), (v1, v2) -> v1));
        listVo.forEach(c -> {
            c.setReplyNumber(getReplyNumber(c.getId()));
            FtbCourseGainedCommentEntity e = nameMap.get(c.getId());
            if (ObjectUtils.isNotEmpty(e)) {
                c.setUserName(e.getRealName());
            }
            UserBoundVO infoVo = map.get(c.getCreatorUserId());
            if (ObjectUtils.isNotEmpty(infoVo)) {
                c.setOrganizeName(infoVo.getOrganizeName());
                c.setPositionName(infoVo.getPositionName());
                c.setHeadIcon(UploaderUtil.uploaderImg(infoVo.getHeadIcon()));
            }
        });
        return ActionResult.page(listVo, vo);
    }

    /**
     * 查看对应的心得评论回复
     *
     * @param id
     * @return
     */
    @Operation(summary = "查看对应的心得评论回复（移动端）")
    @GetMapping("/{id}/listReply")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<List<FtbCourseGainedCommentVO>> listReply(@PathVariable("id") String id) {
        FtbCourseGainedCommentEntity commentEntity = ftbCourseGainedCommentService.getInfo(id);
        FtbCourseGainedEntity gainedEntity = gainedService.getInfo(commentEntity.getGainedId());
        List<FtbCourseGainedCommentEntity> entity = ftbCourseGainedCommentService.list(new LambdaQueryWrapper<FtbCourseGainedCommentEntity>()
                .eq(FtbCourseGainedCommentEntity::getParentId, id));
        List<FtbCourseGainedCommentVO> listVo = JsonUtil.getJsonToList(JsonUtil.getObjectToString(entity), FtbCourseGainedCommentVO.class);
        List<String> userIds = listVo.stream().map(FtbCourseGainedCommentVO::getCreatorUserId).collect(Collectors.toList());
//        List<PartUserInfoVo> userInfoVoList = userApi.getInfoByIds(userIds);
        Map<String, UserBoundVO> userMap = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
        listVo.forEach(c -> {
            c.setReplyNumber(getReplyNumber(c.getId()));
            c.setReplyId(id);
            c.setIsAuthor(0);
            if (gainedEntity.getCreatorUserId().equals(c.getCreatorUserId())) {
                c.setIsAuthor(1);
            }
//            Optional<PartUserInfoVo> infoVoOptional = userInfoVoList.stream()
//                    .filter(u -> c.getCreatorUserId().equals(u.getUserId())).findFirst();
            UserBoundVO userBoundVO = userMap.get(c.getCreatorUserId());
            if (userBoundVO != null) {
                c.setUserName(userBoundVO.getUserName());
                c.setOrganizeName(userBoundVO.getOrganizeName());
                c.setPositionName(userBoundVO.getPositionName());
                c.setHeadIcon(UploaderUtil.uploaderImg(userBoundVO.getHeadIcon()));
            }
        });
        return ActionResult.success(listVo);
    }

    private Long getReplyNumber(String id) {
        return ftbCourseGainedCommentService.count(new LambdaQueryWrapper<FtbCourseGainedCommentEntity>()
                .eq(FtbCourseGainedCommentEntity::getParentId, id));
    }

    @Operation(summary = "获取心得评论详情")
    @GetMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<FtbCourseGainedCommentEntity> info(@PathVariable("id") String id) {
        FtbCourseGainedCommentEntity entity = ftbCourseGainedCommentService.getInfo(id);
        return ActionResult.success(entity);
    }

    @Operation(summary = "心得评论删除")
    @DeleteMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<String> delete(@PathVariable("id") String id) {
        ftbCourseGainedCommentService.removeById(id);
        return ActionResult.success("删除成功");
    }


    @Operation(summary = "心得评论点赞")
    @PostMapping("/{gainedId}/like")
    @Parameters({
            @Parameter(name = "gainedId", description = "心得ID", required = true),
    })
    public ActionResult<String> saveGainedLike(@PathVariable("gainedId") String gainedId,
                                               @RequestBody @Validate FtbCourseGainedLikeEntity gainedLikeEntity) {
        FtbCourseGainedEntity gainedEntity = gainedService.getInfo(gainedId);
        gainedLikeEntity.setCourseId(gainedEntity.getCourseId());
        gainedLikeEntity.setChapterId(gainedEntity.getChapterId());
        gainedLikeEntity.setGainedId(gainedId);
        gainedLikeEntity.setLikeUserId(UserProvider.getUser().getUserId());
        //验证当前用户有无点赞 已点赞 删除之前的记录 未点赞新增点赞记录
        Integer myLike = likeService.getMyLike(gainedLikeEntity);
        if (null != myLike && myLike > 0) {
            likeService.deleteLikeByGainedId(gainedLikeEntity.getGainedId(), gainedLikeEntity.getLikeUserId());
        } else {
            likeService.create(gainedLikeEntity);
        }
        return ActionResult.success("保存成功");
    }

    @Operation(summary = "心得评论分享")
    @PostMapping("/{gainedId}/share")
    @Parameters({
            @Parameter(name = "gainedId", description = "心得ID", required = true),
    })
    public ActionResult<String> saveGainedShare(@PathVariable("gainedId") String gainedId,
                                                @RequestBody @Validate FtbCourseGainedShareEntity gainedShareEntity) {

        FtbCourseGainedEntity gainedEntity = gainedService.getInfo(gainedId);
        gainedShareEntity.setCourseId(gainedEntity.getCourseId());
        gainedShareEntity.setChapterId(gainedEntity.getChapterId());
        gainedShareEntity.setGainedId(gainedId);
        shareService.create(gainedShareEntity);
        return ActionResult.success("保存成功");
    }

    @Operation(summary = "根据心得进行评论")
    @PostMapping("/{gainedId}/comment")
    @Parameters({
            @Parameter(name = "gainedId", description = "心得ID", required = true),
    })
    public ActionResult<String> saveGainedComment(@PathVariable("gainedId") String gainedId,
                                                  @RequestBody @Validate FtbCourseGainedCommentEntity gainedCommentEntity) {
        FtbCourseGainedEntity gainedEntity = gainedService.getInfo(gainedId);
        if (ObjectUtils.isEmpty(gainedEntity)) {
            return ActionResult.fail("未找到对应心得体会");
        }
        gainedCommentEntity.setCourseId(gainedEntity.getCourseId());
        gainedCommentEntity.setChapterId(gainedEntity.getChapterId());
        gainedCommentEntity.setGainedId(gainedId);
        UserInfo userInfo = UserProvider.getUser();
        if (ObjectUtils.isNotEmpty(userInfo)) {
            gainedCommentEntity.setRealName(userInfo.getUserName());
            gainedCommentEntity.setAccount(userInfo.getUserAccount());
            if (Objects.isNull(gainedCommentEntity.getOrganizeId())) {
                gainedCommentEntity.setOrganizeId(userInfo.getOrganizeId());
            }
            if (Objects.isNull(gainedCommentEntity.getPositionId())) {
                gainedCommentEntity.setPositionId(userInfo.getPortalId());
            }
        }
        if (StringUtils.isNotEmpty(gainedCommentEntity.getParentId())) {
            String path = calAndQueryPath(gainedCommentEntity.getParentId());
            gainedCommentEntity.setPath(path);
        }
        ftbCourseGainedCommentService.create(gainedCommentEntity);
        return ActionResult.success("保存成功");
    }

    private String calAndQueryPath(String parentId) {
        String path = "";
        FtbCourseGainedCommentEntity parent = ftbCourseGainedCommentService.getById(parentId);
        if (ObjectUtils.isNotEmpty(parent)) {
            if (StringUtils.isEmpty(parent.getPath())) {
                path = parent.getId();
            } else {
                path = parent.getPath() + "/" + parent.getId();
            }
        }
        return path;
    }

}