package com.yizhi.application.comment;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.accountUtil.QueryAccountUtil;
import com.yizhi.application.util.FilterSensitiveWord;
import com.yizhi.comment.application.feign.AdmireClient;
import com.yizhi.comment.application.feign.ManageCommentClient;
import com.yizhi.comment.application.feign.ReplyClient;
import com.yizhi.comment.application.feign.student.StudentCommentClient;
import com.yizhi.comment.application.vo.CommentParam;
import com.yizhi.comment.application.vo.NewApiCommentVo;
import com.yizhi.comment.application.vo.TaskAppendixVo;
import com.yizhi.comment.application.vo.domain.NewCommentVo;
import com.yizhi.comment.application.vo.domain.NewReplyVo;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.forum.application.constans.ForumConstans;
import com.yizhi.forum.application.feign.PostsForbiddenAccountClient;
import com.yizhi.forum.application.vo.domain.PostsForbiddenAccountVo;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.util.application.domain.Response;
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.util.StringUtils;
import org.springframework.web.bind.annotation.*;

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

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


@Api(tags = "学员端-评论", description = "评论接口")
@RestController
@RequestMapping("/comment/api")
public class NewCommentController {

    private static final Logger logger = LoggerFactory.getLogger(NewCommentController.class);

	@Autowired
	private AdmireClient admireClient;
	@Autowired
	private ManageCommentClient commentClient;
	@Autowired
	private ReplyClient replyClient;
	@Autowired
	private StudentCommentClient studentCommentClient;
	@Autowired
	private QueryAccountUtil queryAccountUtil;
	@Autowired
	private FilterSensitiveWord filterSensitiveWord;
	@Autowired
	private PostsForbiddenAccountClient postsForbiddenAccountClient;

    @ApiOperation(value = "添加评论")
    @PostMapping("/saveComment")
    public Response<String> saveComment(
            @RequestBody NewCommentVo comment ) {

        try {
            //调用新增评论接口
            NewCommentVo resultComment = commentClient.saveComment(comment);
            if (null != resultComment) {
                return Response.ok(resultComment);
            } else {
                return Response.fail();
            }
        } catch (Exception e) {
            return Response.fail();
        }
    }

	@ApiOperation(value = "根据前端传入的回复评论对象新增回复评论(新增)")
	@PostMapping("/saveReply")
	public Response<String> saveReply(@RequestBody NewReplyVo reply) {
		try {
		    if (StringUtils.isEmpty(reply.getContent())||reply.getContent().trim().equals("")){
		        //您未填写回复内容
		        return Response.fail("msg.reply.not.null");
            }
			if(replyClient.saveReply(reply)!=null){
				return Response.ok();
			}
			return Response.fail();
		} catch (Exception e) {
			logger.error("",e);
			return Response.fail();
		}
	}

    @GetMapping("/list")
    @ApiOperation(value = "查看评论", notes = "查看评论", response = NewApiCommentVo.class)
    public Response commentList(
            @ApiParam(value = "业务主键id", required = true) @RequestParam("bizId") Long bizId, @RequestParam("bizType") Integer bizType,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize) {
		RequestContext context = ContextHolder.get();
    	Page<NewApiCommentVo> page = commentClient.apiList(bizId,bizType, context.getAccountId(),context.getCompanyId(), pageNo, pageSize);
    	return Response.ok(page);
    }

	@ApiOperation(value="根据评论id获取回复列表(分页查询)",response = NewReplyVo.class)
	@GetMapping("/reply/list")
	public Response getReplyList(
			@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<NewReplyVo> page = replyClient.replyList2(commentId, pageNo, pageSize);
    	return Response.ok(page);
	}

	@ApiOperation(value="根据前端传入的点赞对象新增点赞(新增)")
	@GetMapping("/save")
	public Response<String> up(@ApiParam(name = "commentId")@RequestParam(name = "commentId")Long commentId,@ApiParam(name = "bizType",value = "业务类型 1评论 2帖子") @RequestParam("bizType") Integer bizType){
		try {
			if(admireClient.up(commentId,bizType)){
				return Response.ok();
			}
			return Response.fail();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("",e);
			return Response.fail();
		}
	}

	@ApiOperation(value="根据前端传入的点赞对象取消点赞(删除)")
	@GetMapping("/down")
	public Response<String> down(@ApiParam(name = "commentId")@RequestParam(name = "commentId")Long commentId,@ApiParam(name = "bizType",value = "业务类型 1评论 2帖子") @RequestParam("bizType") Integer bizType){
		try {
			if(admireClient.down(commentId,bizType)){
				return Response.ok();
			}
			return Response.fail();
		} catch (Exception e) {
//			 TODO Auto-generated catch block
			logger.error("",e);
			return Response.fail();
		}
	}

    @ApiOperation(value = "学员端评论或回复删除")
    @GetMapping("/comment/down")
    public Response<String> commentDown(@ApiParam(name = "id", value = "评论或回复id") @RequestParam("id") Long id,
                                        @ApiParam(name = "type", value = "1评论 2回复") @RequestParam("type") Integer type) {
        Integer tem = studentCommentClient.down(id, type,false);
        if (tem > 0) {
            return Response.ok("操作成功！");
        } else {
            return Response.fail("操作失败");
        }
    }

	/**
	 * 帖子查看分页评论带回复
	 * @param param
	 * @return
	 */
	@PostMapping("/posts/getPage")
	@ApiOperation(value = "论坛帖子查看分页评论列表", response = NewApiCommentVo.class)
	public Response getPage(@ApiParam("param") @RequestBody CommentParam param) {
		if (param.getAuthor()== null){
			return Response.fail("作者id必传！");
		}
		Page<NewApiCommentVo> page = studentCommentClient.getPage(param);
		List<NewApiCommentVo> records = page.getRecords();
		RequestContext context = ContextHolder.get();
		buildVo(records,context,param.getBizId());

		return Response.ok(page);
	}

	public void  buildVo(List<NewApiCommentVo> records,RequestContext context,Long taskId){
		if (!CollectionUtils.isEmpty(records)) {
			Set<Long> accountIds = new HashSet<>();

			//获取禁言名单
			Page<PostsForbiddenAccountVo> page1 = postsForbiddenAccountClient.getPage(taskId, 1, Integer.MAX_VALUE);
			List<PostsForbiddenAccountVo> forbiddenAccounts = page1.getRecords();
			List<Long> forbiddenAccountIds = forbiddenAccounts.stream().map(a -> a.getAccountId()).collect(Collectors.toList());

			//实时获取用户名
			records.forEach(a -> {
				List<NewReplyVo> replies = a.getReplies();
				List<Long> replyAccountIds = replies.stream().map(b -> b.getCommenterId()).collect(Collectors.toList());
				accountIds.add(a.getAccountId());
				accountIds.addAll(replyAccountIds);
			});
			Map<Long, AccountVO> accountMap = queryAccountUtil.queryAccountByIds(new ArrayList<>(accountIds));
			records.forEach(a -> {
				//构建最终内容
				a.setContent(buildContent(forbiddenAccountIds,a.getAccountId(),a.getContent(),context));
				a.setHasForbidden(forbiddenAccountIds.contains(a.getAccountId()));

				if (accountMap != null) {
					AccountVO accountVO = accountMap.get(a.getAccountId());
					if (accountVO != null) {
						a.setCommentator(accountVO.getFullName() != null ? accountVO.getFullName() : accountVO.getName());
						a.setUserAvatar(accountVO.getHeadPortrait());
					}
					List<NewReplyVo> replies = a.getReplies();
					if(!CollectionUtils.isEmpty(a.getReplyPage().getRecords())){
						replies = a.getReplyPage().getRecords();
					}
					if (!CollectionUtils.isEmpty(replies)) {
						replies.forEach(c -> {
							//构建最终内容
							c.setContent(buildContent(forbiddenAccountIds,c.getCreateById(),c.getContent(),context));
							c.setHasForbidden(forbiddenAccountIds.contains(c.getCreateById()));

							AccountVO accountVO1 = accountMap.get(c.getCreateById());
							if (accountVO1 != null) {
								c.setCreateByName(accountVO1.getFullName() != null ? accountVO1.getFullName() : accountVO1.getName());
								c.setUserAvatar(accountVO1.getHeadPortrait());
							}
							AccountVO accountVO2 = accountMap.get(c.getCommenterId());
							if (accountVO2 != null) {
								c.setCommenterName(accountVO2.getFullName() != null ? accountVO2.getFullName() : accountVO2.getName());
							}else {
								c.setCommenterName(accountVO.getFullName() != null ? accountVO.getFullName() : accountVO.getName());
							}
						});
					}
				}
			});
		}
	}

	/**
	 * 构建最终内容
	 * @param forbiddenAccountIds
	 * @param accountId
	 * @param content
	 * @param context
	 * @return
	 */
	public String buildContent(List<Long> forbiddenAccountIds,Long accountId,String content,RequestContext context){
		if (forbiddenAccountIds.contains(accountId)){
			return ForumConstans.ACCOUNT_IS_FORBIDDEN;
		}else {
			//过滤敏感词
			return filterSensitiveWord.filterWord(content,context.getCompanyId());
		}
	}

	/**
	 * 目前是论坛需要    评论可以携带附件（图片）
	 * @param comment
	 * @return
	 */
	@ApiOperation(value = " 目前论坛需要 添加评论  评论可以携带附件（图片）")
	@PostMapping("/studentSaveComment")
	public Response<String> studentSaveComment(@RequestBody NewCommentVo comment) {
		try {
            if (StringUtils.isEmpty(comment.getContent())||comment.getContent().trim().equals("")){
                //您未填写回复内容
                return Response.fail("msg.reply.not.null");
            }
			if (!CollectionUtils.isEmpty(comment.getTaskAppendixVos())) {
				if (comment.getTaskAppendixVos().size() > 9) {
					return Response.fail("最多携带9张图片！");
				}
				TaskAppendixVo appendixVo = comment.getTaskAppendixVos().get(0);
				if (appendixVo.getFileSize()==null
						|| StringUtils.isEmpty(appendixVo.getName())
						||StringUtils.isEmpty(appendixVo.getUrl())){
					return Response.fail("附件必要参数缺失！！");
				}
			}
			//调用新增评论接口
			Integer result = studentCommentClient.studentSave(comment);
			if (result == 1) {

				return Response.ok("评论成功！");
			} else {
				return Response.fail("评论失败！");
			}
		} catch (Exception e) {
			return Response.fail();
		}
	}

	/**
	 * 根据评论id  查询评论及其下的回复
	 * @param taskType
	 * @param taskId
	 * @param commentId
	 * @param orderType
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@GetMapping("/getCommentDetails")
    @ApiOperation(value = "根据评论id  查询评论及其下的回复")
	public Response getCommentDetails(@ApiParam("taskType必传 ") @RequestParam("taskType") Integer taskType,
											 @ApiParam("业务id ") @RequestParam("taskId") Long taskId,
											 @ApiParam("评论id ") @RequestParam("commentId") Long commentId,
											 @ApiParam("作者id ") @RequestParam(value = "author",required = false) Long author,
											 @ApiParam("回复排序方式 ") @RequestParam("orderType") Integer orderType,
											 @ApiParam("回复的pageNo") @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
											 @ApiParam("回复的pageSize ") @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){

		NewApiCommentVo record = studentCommentClient.getCommentDetails(taskType, taskId, commentId, author, orderType, pageNo, pageSize);
		buildVo(Arrays.asList(record),ContextHolder.get(),taskId);
		return Response.ok(record);
	}
}
