package com.yizhi.application.course.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.course.utils.StuWorkUtil;
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.vo.ReplyVo;
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.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.*;

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

	@Autowired
	private CommentClient commentClient;

	@Autowired
	CommClient commClient;
	@Autowired
	AccountClient accountClient;
	@Autowired
	private StuWorkUtil stuWorkUtil;
    @Autowired
    private RedisCache redisCache;

	@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<ReplyEntityVo> page = commClient.replyList2(commentId, pageNo, pageSize);
		RequestContext context = ContextHolder.get();
		List<ReplyEntityVo> 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.getAccountId());
			});
			//去重
			listSet.addAll(accountIds);
			List<AccountVO> accountVOs = accountClient.idsGet(listSet);
			Map<Long, String> nameMap = new HashMap<>();
			Map<Long,String> headPhotoMap = new HashMap<>();
			//组装Map
			stuWorkUtil.getMap(nameMap,headPhotoMap,accountVOs);

			//过滤敏感词
            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);
            }
			stuWorkUtil.fillReply2(replys,nameMap,headPhotoMap,sensitiveWordList);
			}

		return Response.ok(page);
	}

	@ApiOperation(value = "根据前端传入的回复评论对象新增回复评论(新增)")
	@PostMapping("/save")
	public Response<String> saveReply(
			@RequestBody ReplyEntityVo reply
//			@ApiParam(name = "comment_id", value = "评论id") @RequestParam(name = "comment_id") Long commentId,
//			@ApiParam(name = "account_id", value = "账号id") @RequestParam(name = "account_id") Long accountId,
//			@ApiParam(name = "replier", value = "回复人") @RequestParam(name = "replier") String replier,
//			@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
	) {

		RequestContext context = ContextHolder.get();
		reply.setAccountId(context.getAccountId());
		reply.setReplier(context.getAccountName());
		reply.setDeleted(0);

		try {
			if(commentClient.saveReply(reply)!=null){
				return Response.ok();
			}
			return Response.fail();
		} catch (Exception e) {
			logger.error("",e);
			return Response.fail();
		}
	}

	/**
	 * PC端课程回复评论
	 * @param
	 * @return
	 */
	@PostMapping("/pc/saveCourseReply")
	@ApiOperation(value = "PC端课程评论回复")
	public Response saveCourseReply(@ApiParam(value = "reply")@RequestBody ReplyEntityVo reply){

		RequestContext context = ContextHolder.get();
		reply.setAccountId(context.getAccountId());
		reply.setReplier(context.getAccountName());
		reply.setDeleted(0);

		if (reply.getReplyParentId()!=null){
			AccountVO accountVO = accountClient.findById(reply.getParentAccountId());
			if (accountVO != null) {
				reply.setParentAccountFullName(accountVO.getFullName());
				reply.setParentAccountName(accountVO.getName());
			}
		}else{
			reply.setParentAccountId(reply.getParentAccountId()==null?0:reply.getParentAccountId());
			reply.setParentAccountFullName(null);
			reply.setParentAccountName(null);
			reply.setReplyParentId(0L);
		}

		Boolean flag = commentClient.saveReply(reply);
		if (flag) {
			return Response.ok(Constants.MSG_REPLY_SUCCESS.getCode().toString(), Constants.MSG_REPLY_SUCCESS.getName());
		}
		return Response.fail(Constants.MSG_REPLY_COMMENT_FAIL.getCode().toString(),
				Constants.MSG_REPLY_COMMENT_FAIL.getName());
	}

	@ApiOperation(value="PC端根据评论id获取回复列表(分页查询)",response = ReplyEntityVo.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<ReplyEntityVo> page = commClient.replyList2(commentId, pageNo, pageSize);
        RequestContext context =ContextHolder.get();
        List<ReplyEntityVo> 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.getAccountId());
            });
            //去重
            listSet.addAll(accountIds);
            List<AccountVO> accountVOs = accountClient.idsGet(listSet);
            Map<Long, String> nameMap = new HashMap<>();
            Map<Long,String> headPhotoMap = new HashMap<>();
            //组装Map
            stuWorkUtil.getMap(nameMap,headPhotoMap,accountVOs);

            //过滤敏感词
            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);
            }
            stuWorkUtil.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);
	}

}
