package com.yizhi.application.caseLibrary.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.library.application.feign.StudyCaseClient;
import com.yizhi.library.application.param.InformParam;
import com.yizhi.library.application.vo.CommentReplyVO;
import com.yizhi.library.application.vo.CommentVO;
import com.yizhi.library.application.vo.FavoriteVO;
import com.yizhi.site.application.feign.InformationManageFeignClients;
import com.yizhi.site.application.feign.InformationStudentFeignClients;
import com.yizhi.site.application.feign.api.EventTrackApiClients;
import com.yizhi.site.application.vo.domain.InformationVo;
import com.yizhi.site.application.vo.site.IdOneVO;
import com.yizhi.site.application.vo.site.InformationViewVO;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Ding
 * @className StudyCaseController
 * @description TODO
 * @date 2019/7/12
 **/
@Api(tags = "学员案例接口", description = "学员案例接口")
@RestController
@RequestMapping("/api/studentCase/study")
public class StudyCaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(StudentLibraryController.class);

    @Autowired
    private StudyCaseClient studyCaseClient;

    @Autowired
    private EventTrackApiClients eventTrackApiClients;
    @Autowired
    InformationStudentFeignClients informationStudentFeignClients;
    @Autowired
    private InformationManageFeignClients informationManageFeignClients;
    @Autowired
    private RedisCache redisCache;

    @ApiOperation(value = "学习案例点赞", notes = "学习案例点赞")
    @GetMapping("/admire")
    public Response<Object> admireStudentCase(HttpServletRequest request,@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId) {

        try {
            if (studyCaseClient.admireStudentCase(studentCaseId)) {
                RequestContext context = ContextHolder.get();
                IdOneVO idOneVO =new IdOneVO();
                idOneVO.setId(studentCaseId);
                idOneVO.setContext(context);
                InformationViewVO viewVO = informationStudentFeignClients.getInformation(idOneVO);
                // 添加点赞埋点
                if(request.getHeader("Cookie")!=null&& Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                    eventTrackApiClients.addEvent("event_admire_"+viewVO.getTypeOne(),studentCaseId);
                }
                return Response.ok();
            } else {
                LOGGER.error("############学习案例点赞过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学习案例取消点赞", notes = "学习案例取消点赞")
    @GetMapping("/cancelAdmire")
    public Response<Object> cancelAdmireStudentCase(@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId) {

        try {
            if (studyCaseClient.cancelAdmireStudentCase(studentCaseId)) {
                RequestContext context = ContextHolder.get();
                IdOneVO idOneVO =new IdOneVO();
                idOneVO.setId(studentCaseId);
                idOneVO.setContext(context);
                InformationViewVO viewVO = informationStudentFeignClients.getInformation(idOneVO);
                return Response.ok();
            } else {
                LOGGER.error("############学习案例取消点赞过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学习案例收藏", notes = "学习案例收藏")
    @GetMapping("/favorite")
    public Response<Object> favorite(HttpServletRequest request, @ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId) {

        try {
            boolean result = studyCaseClient.favorite(studentCaseId);
            LOGGER.info("############学习案例收藏favorite结果:{}", result);
            if (result) {
                RequestContext context = ContextHolder.get();
                IdOneVO idOneVO =new IdOneVO();
                idOneVO.setId(studentCaseId);
                idOneVO.setContext(context);
                InformationViewVO viewVO = informationStudentFeignClients.getInformation(idOneVO);
                LOGGER.info("############学习案例收藏成功,添加埋点:{}", "event_favorite_"+viewVO.getTypeOne());
                // 添加点赞埋点
                //if(request.getHeader("Cookie")!=null&& Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                    eventTrackApiClients.addEvent("event_favorite_"+viewVO.getTypeOne(),studentCaseId);
               // }
                return Response.ok();
            } else {
                LOGGER.error("############学习案例收藏过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学习案例取消收藏", notes = "学习案例取消收藏")
    @GetMapping("/cancelFavorite")
    public Response<Object> cancelFavorite(@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId) {

        try {
            if (studyCaseClient.cancelFavorite(studentCaseId)) {
                return Response.ok();
            } else {
                LOGGER.error("############学习案例取消收藏过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学习案例举报", notes = "学习案例举报")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentCaseId", value = "学员案例id", paramType = "body", required = true),
            @ApiImplicitParam(name = "informDescription", value = "举报描述", paramType = "body", required = false),
            @ApiImplicitParam(name = "pictureUrlList", value = "举报截图", paramType = "body", required = false)
    })
    @PostMapping("/inform")
    public Response<Object> inform(@RequestBody InformParam informParam) {

        try {
            if (studyCaseClient.inform(informParam)) {
                return Response.ok();
            } else {
                LOGGER.error("############学习案例举报过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "学习案例发表评论/回复", notes = "学习案例发表评论/回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型 1:评论 2:回复", paramType = "body", required = true),
            @ApiImplicitParam(name = "studentCaseId", value = "学员案例id", paramType = "body", required = false),
            @ApiImplicitParam(name = "commentId", value = "评论id", paramType = "body", required = false),
            @ApiImplicitParam(name = "content", value = "评论/回复内容", paramType = "body", required = true),
            @ApiImplicitParam(name = "replyAccountId", value = "回复对象id", paramType = "body", required = false)
    })
    @PostMapping("/comment")
    public Response<Object> inform(@RequestBody com.yizhi.library.application.param.CommentParam commentParam) {

        try {
            if (studyCaseClient.comment(commentParam)) {
                return Response.ok();
            } else {
                LOGGER.error("############学习案例发表评论/回复过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "评论点赞", notes = "评论点赞")
    @GetMapping("/comment/admire")
    public Response<Object> admireComment(HttpServletRequest request,@ApiParam(value = "评论id", required = true) @RequestParam(name = "commentId", required = true) Long commentId) {

        try {
            if (studyCaseClient.admireComment(commentId)) {
                RequestContext context = ContextHolder.get();
                IdOneVO idOneVO =new IdOneVO();
                idOneVO.setId(commentId);
                idOneVO.setContext(context);
                InformationViewVO viewVO = informationStudentFeignClients.getInformation(idOneVO);
                // 添加点赞埋点
                if(request.getHeader("Cookie")!=null&& Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                    eventTrackApiClients.addEvent("event_admire_"+viewVO.getTypeOne(),commentId);
                }
                return Response.ok();
            } else {
                LOGGER.error("############评论点赞过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "评论取消点赞", notes = "评论取消点赞")
    @GetMapping("/comment/cancelAdmire")
    public Response<Object> cancelAdmireComment(@ApiParam(value = "评论id", required = true) @RequestParam(name = "commentId", required = true) Long commentId) {

        try {
            if (studyCaseClient.cancelAdmireComment(commentId)) {
                return Response.ok();
            } else {
                LOGGER.error("############学评论取消点赞过程中出现错误");
                return Response.fail(Constants.MSG_BIZ_FAIL);
            }

        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "获取评论列表", notes = "获取评论列表", response = CommentVO.class)
    @GetMapping("/comment/list")
    public Response<CommentVO> getCommentList(@ApiParam(value = "学员案例id", required = true) @RequestParam(name = "studentCaseId", required = true) Long studentCaseId,
                                              @ApiParam(value = "当前第几页", required = true) @RequestParam(name = "pageNo", required = true) Integer pageNo,
                                              @ApiParam(value = "每页显示条数", required = true) @RequestParam(name = "pageSize", required = true) Integer pageSize) {

        try {
            return Response.ok(studyCaseClient.getCommentList(studentCaseId, pageNo, pageSize));
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "获取回复列表", notes = "获取回复列表", response = CommentReplyVO.class)
    @GetMapping("/comment/replyList")
    public Response<CommentReplyVO> getReplyList(@ApiParam(value = "评论id", required = true) @RequestParam(name = "commentId", required = true) Long commentId,
                                                 @ApiParam(value = "当前第几页", required = true) @RequestParam(name = "pageNo", required = true) Integer pageNo,
                                                 @ApiParam(value = "每页显示条数", required = true) @RequestParam(name = "pageSize", required = true) Integer pageSize) {

        try {
            Page<CommentReplyVO> page = studyCaseClient.getReplyList(commentId, pageNo, pageSize);
            Map<String, Integer> pageMap = new HashMap<>(3);
            pageMap.put("pageNo", pageNo);
            pageMap.put("pageSize", pageSize);
            if (null != page) {
                pageMap.put("total", page.getTotal());
            }
            return Response.ok(page, pageMap);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

    @ApiOperation(value = "微信端获取我的收藏列表", notes = "微信端获取我的收藏列表", response = FavoriteVO.class)
    @GetMapping("/getFavorites")
    public Response<Page<FavoriteVO> > getFavorites(@ApiParam(value = "当前第几页", required = true) @RequestParam(name = "pageNo", required = true) Integer pageNo,
                                             @ApiParam(value = "每页显示条数", required = true) @RequestParam(name = "pageSize", required = true) Integer pageSize) {

        try {
            Page<FavoriteVO> favoriteVOPage = studyCaseClient.getFavoriteList(pageNo, pageSize);
            if(favoriteVOPage!=null&& CollectionUtils.isNotEmpty(favoriteVOPage.getRecords())){
                LOGGER.info("我的收藏列表查询,记录数:{}", favoriteVOPage.getRecords().size());
               List<Long> bizIds = favoriteVOPage.getRecords().stream().map(FavoriteVO::getFavoriteId).collect(Collectors.toList());
                List<InformationVo> informationVoList =informationManageFeignClients.listbyIds(bizIds);
                LOGGER.info("我的收藏获取资讯信息,记录数:{}", informationVoList.size());
                if(CollectionUtils.isNotEmpty(informationVoList)){
                    favoriteVOPage.getRecords().stream().forEach(vo->{
                        Optional<InformationVo> optional = informationVoList.stream().filter(i->Objects.equals(i.getId(),vo.getFavoriteId())).findFirst();
                        if(optional!=null&&optional.isPresent()){
                            InformationVo informationVo = optional.get();
                            vo.setStudentCaseTittle(informationVo.getFileName());
                            vo.setStudentCaseLogoUrl(informationVo.getLogoPath());
                        }
                    });
                }
            }
            return Response.ok(favoriteVOPage);
        } catch (Exception e) {
            LOGGER.error("############案例库服务调用出现异常", e);
            return Response.fail(Constants.MSG_BIZ_FAIL);
        }
    }

}
