package com.yizhi.application.course.controller;


import com.yizhi.application.course.utils.StuWorkUtil;
import com.yizhi.application.tools.PageTools;
import com.yizhi.assignment.application.vo.entity.Comment;
import com.yizhi.core.application.cache.CacheNamespace;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.CommClient;
import com.yizhi.course.application.feign.CommentClient;
import com.yizhi.course.application.feign.GradeClient;
import com.yizhi.course.application.vo.*;
import com.yizhi.course.application.vo.domain.CommentEntityVo;
import com.yizhi.course.application.vo.domain.ReplyEntityVo;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import com.yizhi.util.application.json.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 评论 前端控制器
 *
 * @author Fairyland
 */


@Api(tags = "学员端-课程评论", description = "评论接口")
@RestController
@RequestMapping("/api/comment")
public class CommentStuController {
    private static final Logger logger = LoggerFactory.getLogger(CommentStuController.class);

    @Autowired
    CommClient commClient;

    @Autowired
    CommentClient commentClient;

    @Autowired
    GradeClient gradeClient;

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private StuWorkUtil stuWorkUtil;


    @ApiOperation(value = "添加评论")
    @PostMapping("/save")
    public Response<String> saveComment(
            @RequestBody CommentEntityVo comment
//			@ApiParam(name="content",value="评论内容") @RequestParam(name="content") String content,
//			@ApiParam(name="course_id",value="课程id") @RequestParam(name="course_id") Long courseId,
//			@ApiParam(name="course_name",value="课程名称") @RequestParam(name="course_name") String courseName
    ) {

        try {
            RequestContext context = ContextHolder.get();
            //新增评论对象
            comment.setAccountId(context.getAccountId());
            comment.setCommentator(context.getAccountName());
            comment.setDeleted(0);
            comment.setUserAvatar(context.getHeadPortrait());
            //调用新增评论接口
            CommentEntityVo resultComment = commentClient.saveComment(comment);
            if (null != resultComment) {
                return Response.ok(resultComment);
            } else {
                return Response.fail();
            }
        } catch (Exception e) {
            return Response.fail();
        }

    }

    /**
     * 根据id 获得评论实体
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id 获得评论实体")
    @GetMapping("/get")
    public Response<Comment> get(@RequestParam("id") Long id
    ) {
        CommentEntityVo comment = commClient.get(id);
        if (comment != null) {
            List<Long> listSet = new ArrayList<>();
            listSet.add(comment.getAccountId());
            List<AccountVO> accountVOs = accountClient.idsGet(listSet);
            AccountVO accountVO = accountVOs.get(0);
            String name = ((accountVO.getFullName() == "" ? null : accountVO.getFullName()) == null ? accountVO.getName() : accountVO.getFullName());
            comment.setCommentator(name);
            comment.setUserAvatar(accountVO.getHeadPortrait());
            //过滤敏感词
            RequestContext context = ContextHolder.get();
            Long companyId = context.getCompanyId();
            Set<String> sensitiveWordList = new HashSet<>();
            String sensitiveValues = (String) redisCache.hget(CacheNamespace.REDIS_SENSITIVE_WORD_INFO, companyId.toString());
            if (sensitiveValues != null) {
                sensitiveWordList = JsonUtil.json2Ojbect(sensitiveValues, Set.class);
                System.out.println(sensitiveWordList.iterator().next());
            }
            String word = stuWorkUtil.filterWord(comment.getContent(), sensitiveWordList);
            comment.setContent(word);
        }

        return Response.ok(comment);
    }


    /**
     *  PC端 课程评论列表
     * @param commentVo
     * @return
     */
    @PostMapping("/pc/listCourseComment")
    @ApiOperation(value = "PC端查询课程评论列表")
    public Response<ListCommentVo> pcList(@ApiParam(value = "commentVo") @RequestBody CourseCommentVo commentVo) {

        Long time = System.currentTimeMillis();
        PageCommentVo page = commClient.pcList(commentVo);
        if (null != page.getPage()) {
            List<ListCommentVo> commentVos = page.getPage().getRecords();
            //取得用户id集合，只查一次库
            Set<Long> accountIds = new HashSet<>();
            List<Long> listSet = new ArrayList<>();
            if (!CollectionUtils.isEmpty(commentVos)) {
                //评论者id
                commentVos.forEach(commentVo1 -> {
                    accountIds.add(commentVo1.getAccountId());
                    List<ReplyEntityVo> replyVos = commentVo1.getReplies();
                    if (!CollectionUtils.isEmpty(replyVos)) {
                        //回复者Id
                        replyVos.forEach(replyVo -> { accountIds.add(replyVo.getAccountId()); });
                    }
                });
                //去重
                listSet.addAll(accountIds);

                List<AccountVO> accountVOs = accountClient.idsGet(listSet);
                Map<Long, String> map = new HashMap<>();
                Map<Long, String> headPhotoMap = new HashMap<>();
               //组装map
                stuWorkUtil.getMap(map,headPhotoMap,accountVOs);

                Long companyId = ContextHolder.get().getCompanyId();
                Set<String> sensitiveWordList = new HashSet<>();
                String sensitiveValues = (String) redisCache.hget(CacheNamespace.REDIS_SENSITIVE_WORD_INFO, companyId.toString());
                if (sensitiveValues != null) {
                    sensitiveWordList = JsonUtil.json2Ojbect(sensitiveValues, Set.class);
                }
                //如果用户有真实名字则用，无则采用账户名
                for (ListCommentVo commentVo2 : commentVos) {
                    commentVo2.setCommentator(map.get(commentVo2.getAccountId()));
                    commentVo2.setUserAvatar(headPhotoMap.get(commentVo2.getAccountId()));
                    String word = stuWorkUtil.filterWord(commentVo2.getContent(), sensitiveWordList);
                    commentVo2.setContent(word);
                    List<ReplyEntityVo> replyVos = commentVo2.getReplies();
                    //组装回复
                   stuWorkUtil.fillReply(replyVos,map,sensitiveWordList);
                }
            }
        }
        Pair pair = PageTools.split(page.getPage());
        logger.info("运行时间为：" + (System.currentTimeMillis() - time));
        return Response.ok(page.getPage().getRecords(), (Map<String, Integer>) pair.getRight());
    }

    /**
     * PC端 对用户能否评分进行判断，已对课程进行评分的用户只能进行评论；
     *
     * @param
     * @return
     */
    @GetMapping("/pc/judgeWhetherSaveGrade")
    @ApiOperation(value = "PC端对用户能否评分进行判断，已对课程进行评分的用户只能进行评论")
    public Response judgeWhetherSaveGrade(@ApiParam(value = "courseId") @RequestParam(name = "courseId") Long courseId) {
        RequestContext requestContext = ContextHolder.get();
        Boolean flag = gradeClient.judgeWhetherSaveGrade(courseId);
        return Response.ok(flag);

    }

    /**
     * PC端 给课程评分及评论
     * 用户未对课程进行评分的用户可以同时进行评分和评分，已对课程进行评分的用户只能进行评论；
     *
     * @param
     * @return
     */
    @PostMapping("/pc/CommentCourse")
    @ApiOperation(value = "PC端 给课程评分及评论")
    public Response saveGrade(@ApiParam(value = "courseId、content、level 必传") @RequestBody CommentGradeVo commentGradeVo) {
        RequestContext requestContext = ContextHolder.get();
        Long accountId = requestContext.getAccountId();

        CourseGradeVO grade = new CourseGradeVO();
        System.out.println(commentGradeVo);
        grade.setAccountId(accountId);
        grade.setCourseId(commentGradeVo.getCourseId());
        grade.setLevel(commentGradeVo.getLevel());

        CommentEntityVo comment = new CommentEntityVo();
        CommentEntityVo saveComment = null;
        Integer i = null;

        comment.setContent(commentGradeVo.getContent());
        comment.setCourseId(commentGradeVo.getCourseId());
        comment.setAccountId(accountId);
        comment.setCommentator(requestContext.getAccountName());
        comment.setDeleted(0);
        comment.setUserAvatar(requestContext.getHeadPortrait());

        System.out.println(commentGradeVo.getCourseId());
        Boolean flag = gradeClient.judgeWhetherSaveGrade(commentGradeVo.getCourseId());


        if (null != comment) {
            saveComment = commentClient.saveComment(comment);
        }
        if (flag) {
            if (null != grade) {
                i = gradeClient.savePcGrade(grade);
            }
            if (i == 1 && null != saveComment) {
                return Response.ok();
            }
        } else {
            if (null != saveComment) {
                return Response.ok();
            }
        }
        return Response.fail(Constants.MSG_COMMENT_FAIL.getCode().toString(),
                Constants.MSG_COMMENT_FAIL.getName());
    }


}
