package com.yizhi.application.project.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.project.controller.util.CommentUtil;
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.vo.ReplyVo;
import com.yizhi.site.application.feign.api.EventTrackApiClients;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.training.application.feign.TpCommentReplyClient;
import com.yizhi.training.application.vo.domain.TpCommentReplyVo;
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.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 javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 培训项目 - 评论 前端控制器
 * </p>
 *
 * @author shengchenglong
 * @since 2018-03-27
 */
@Api(tags = "培训项目--评论回复接口")
@RestController
@RequestMapping("/api/tpCommentReply")
public class TpCommentReplyApiController {

    @Autowired
    TpCommentReplyClient tpCommentReplyClient;
    @Autowired
    AccountClient accountClient;
    @Autowired
    private CommentUtil workUtil;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private EventTrackApiClients eventTrackApiClients;

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


    @PostMapping("/save")
    @ApiOperation(value = "学员端回复项目评论", notes = "返回操作是否成功")
    public Response save(HttpServletRequest request,
                         @ApiParam(value = "项目trainingProjectId，项目评论commmentId，评论内容content")@RequestBody TpCommentReplyVo tpCommentReply
//            @ApiParam(value = "项目id",required = true)@RequestParam("trainingProjectId")Long trainingProjectId,
//            @ApiParam(value = "项目评论id",required = true)@RequestParam("commmentId")Long commmentId,
//            @ApiParam(value = "评论内容",required = true)@RequestParam(name = "content")String content
    ){
        RequestContext requestContext = ContextHolder.get();
        tpCommentReply.setCreateById(requestContext.getAccountId());
        tpCommentReply.setCreateByName(requestContext.getAccountName());
        tpCommentReply.setCompanyId(requestContext.getCompanyId());
        tpCommentReply.setSiteId(requestContext.getSiteId());
        tpCommentReply.setOrgId(requestContext.getOrgId() == null? 0L:requestContext.getOrgId());
        tpCommentReply.setAuditStatus("0");
        //tpCommentReply.setState(1);
        tpCommentReply.setUserAvatar(requestContext.getHeadPortrait());
        Boolean f = tpCommentReplyClient.save(tpCommentReply);
        // 添加发表评论埋点
        //if(request.getHeader("Cookie")!=null&&Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
            eventTrackApiClients.addEvent("event_tp_comment",tpCommentReply.getTrainingProjectId());
        //}
        if (f) {
            LOGGER.info("回复评论成功");
            return Response.ok("回复评论成功");
        } else {
            LOGGER.error("回复失败");
            return Response.fail("回复失败");
        }
    }


    @ApiOperation(value="根据评论id获取回复列表(分页查询)",response = ReplyVo.class)
    @GetMapping("/list")
    public Response getCommentList(
            @ApiParam(name="commentId",value="项目评论id") @RequestParam(name="commentId") Long commentId,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页") @RequestParam(name = "pageNo", defaultValue = "1",required = false) Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条") @RequestParam(name = "pageSize", defaultValue = "10",required = false) Integer pageSize
    ){
        Page<TpCommentReplyVo> page = tpCommentReplyClient.replyList(commentId, pageNo, pageSize,1);
        List<TpCommentReplyVo> replys = page.getRecords();
        //取得用户id集合，只查一次库
        Set<Long> accountIds = new HashSet<>();
        List<Long> listSet = new ArrayList<>();
        if (!CollectionUtils.isEmpty(replys)) {
            replys.forEach(reply -> {
                //回复者id
                accountIds.add(reply.getCreateById());
            });
            //去重
            listSet.addAll(accountIds);

            List<AccountVO> accountVOs = accountClient.idsGet(listSet);
            Map<Long, String> nameMap = new HashMap<>();
            Map<Long,String> headPhotoMap = new HashMap<>();
            workUtil.getMap(nameMap,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);
            }
           //组装回复
            workUtil.fillReply(replys,nameMap,sensitiveWordList);

        }
        return Response.ok(page);
    }

    /**
     * Pc端回复评论
     *
     * @param commentReply
     * @return
     */
    @PostMapping("/pc/save")
    @ApiOperation(value = "pc端培训项目回复评论")
    Response saveTpCommentReply(@ApiParam(value = "content-回复内容,trainingProjectId-项目Id,tpCommentId-评论Id")@RequestBody TpCommentReplyVo commentReply) {
        RequestContext requestContext = ContextHolder.get();

        commentReply.setCreateById(requestContext.getAccountId());
        commentReply.setCreateByName(requestContext.getAccountName());
        commentReply.setCompanyId(requestContext.getCompanyId());
        commentReply.setSiteId(requestContext.getSiteId());
        commentReply.setOrgId(requestContext.getOrgId() == null? 0L:requestContext.getOrgId());
        commentReply.setAuditStatus("0");
        commentReply.setUserAvatar(requestContext.getHeadPortrait());
        if (null == commentReply.getContent()){
            Response.fail(Constants.MSG_REPLY_IS_NOT_NULL.getCode().toString(),
                    Constants.MSG_REPLY_IS_NOT_NULL.getName());
        }

        Boolean flag = tpCommentReplyClient.save(commentReply);
        if (!flag) {
            return Response.fail(Constants.MSG_REPLY_COMMENT_FAIL.getCode().toString(),
                    Constants.MSG_REPLY_COMMENT_FAIL.getName());
        }
        return Response.ok(Constants.MSG_REPLY_SUCCESS.getCode().toString(), Constants.MSG_REPLY_SUCCESS.getName());

    }

    /**
     * Pc端回复评论  支持回复的回复
     *
     * @param commentReply
     * @return
     */
    @PostMapping("/pc/reply/Children/save")
    @ApiOperation(value = "pc端培训项目 支持回复的回复")
    Response saveTpCommentReplyChildren(@ApiParam(value = "commentReply")@RequestBody TpCommentReplyVo commentReply) {
        RequestContext requestContext = ContextHolder.get();

        commentReply.setCreateById(requestContext.getAccountId());
        commentReply.setCreateByName(requestContext.getAccountName());
        commentReply.setCreateByFullName(requestContext.getAccountFullName());
        commentReply.setCompanyId(requestContext.getCompanyId());
        commentReply.setSiteId(requestContext.getSiteId());
        commentReply.setOrgId(requestContext.getOrgId() == null ? 0L : requestContext.getOrgId());
        commentReply.setAuditStatus("0");
        commentReply.setUserAvatar(requestContext.getHeadPortrait());
        if (commentReply.getReplyParentId()!=null){
            AccountVO accountVO = accountClient.findById(commentReply.getParentAccountId());
            if (accountVO != null) {
                commentReply.setParentAccountFullName(accountVO.getFullName());
                commentReply.setParentAccountName(accountVO.getName());
            }
        }else{
            commentReply.setParentAccountId(commentReply.getParentAccountId()==null?null:commentReply.getParentAccountId());
            commentReply.setParentAccountFullName(null);
            commentReply.setParentAccountName(null);
            commentReply.setReplyParentId(null);
        }



        if (null == commentReply.getContent()) {
            Response.fail(Constants.MSG_REPLY_IS_NOT_NULL.getCode().toString(),
                    Constants.MSG_REPLY_IS_NOT_NULL.getName());
        }

        Boolean flag = tpCommentReplyClient.save(commentReply);
        if (!flag) {
            return Response.fail(Constants.MSG_REPLY_COMMENT_FAIL.getCode().toString(),
                    Constants.MSG_REPLY_COMMENT_FAIL.getName());
        }
        return Response.ok();
    }

    @ApiOperation(value="PC端根据评论id获取回复列表(分页查询)",response = ReplyVo.class)
    @GetMapping("/pc/list")
    public Response pcGetCommentList(
            @ApiParam(name="commentId",value="项目评论id") @RequestParam(name="commentId") Long commentId,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页") @RequestParam(name = "pageNo", defaultValue = "1",required = false) Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认10条") @RequestParam(name = "pageSize", defaultValue = "10",required = false) Integer pageSize
    ){
        Page<TpCommentReplyVo> page = tpCommentReplyClient.replyList(commentId, pageNo, pageSize,1);
        List<TpCommentReplyVo> replys = page.getRecords();
        //取得用户id集合，只查一次库
        Set<Long> accountIds = new HashSet<>();
        List<Long> listSet = new ArrayList<>();
        if (!CollectionUtils.isEmpty(replys)) {
            replys.forEach(reply -> {
                //回复者id
                accountIds.add(reply.getCreateById());
            });
            //去重
            listSet.addAll(accountIds);

            List<AccountVO> accountVOs = accountClient.idsGet(listSet);
            Map<Long, String> nameMap = new HashMap<>();
            Map<Long,String> headPhotoMap = new HashMap<>();
            workUtil.getMap(nameMap,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);
            }
            //组装回复
            workUtil.fillReply(replys,nameMap,sensitiveWordList);

        }
        Map<String, Integer> pageMap = new HashMap<>();
        pageMap.put("pageNo", page.getCurrent());
        pageMap.put("pageSize", page.getSize());
        pageMap.put("pageTotal", page.getPages());
        return Response.ok(page,pageMap);
    }
}

