package com.yizhi.application.forum.controller;



import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.accountUtil.QueryAccountUtil;
import com.yizhi.application.util.FilterSensitiveWord;
import com.yizhi.comment.application.constans.Constant;
import com.yizhi.comment.application.feign.student.StudentCommentClient;
import com.yizhi.comment.application.vo.CommentParam;
import com.yizhi.comment.application.vo.PostsCommentVo;
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.feign.student.StudentPostsClient;
import com.yizhi.forum.application.util.ForumUtil;
import com.yizhi.forum.application.vo.domain.PostsForbiddenAccountVo;
import com.yizhi.forum.application.vo.forum.PostsStudentVo;
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.web.bind.annotation.*;

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

@Api(tags = "学员端-帖子-回复管理")
@RestController
@RequestMapping("/student/forum/myReply")
public class StudentPostsCommentController {

    private static final Logger LOG = LoggerFactory.getLogger(StudentPostsCommentController.class);

    @Autowired
    private PostsForbiddenAccountClient postsForbiddenAccountClient;
    @Autowired
    private QueryAccountUtil queryAccount;
    @Autowired
    private StudentCommentClient studentCommentClient;
    @Autowired
    private StudentPostsClient studentPostsClient;
    @Autowired
    private FilterSensitiveWord filterSensitiveWord;

    /**
     * 论坛 我的回复-- 我收到的回复分页
     *
     * @param param
     * @return
     */
    @PostMapping("/myReceivedPage")
    @ApiOperation(value = "我的回复--收到的回复", response = PostsCommentVo.class)
    public Response<Page<PostsCommentVo>> myReceivedPage(@ApiParam("type必传 ") @RequestBody CommentParam param) {

        if (param.getType() == null) {
            return Response.fail("必要参数缺失！！！");
        }
        Page<PostsCommentVo> page = studentCommentClient.myReceivedPage(param);
        List<PostsCommentVo> records = page.getRecords();
        buildRecords(records);
        return Response.ok(page);
    }

    /**
     * 组装数据 处理是否被禁言、是否被删除
     *
     * @param records
     */
    public void buildRecords(List<PostsCommentVo> records) {
        RequestContext context = ContextHolder.get();
        if (!CollectionUtils.isEmpty(records)) {
            //获取帖子信息
            List<Long> postsIds = new ArrayList<>(records.size());
            Map<Long, PostsStudentVo> postsMap = null;
            Set<Long> accountIds = new HashSet<>(records.size());
            records.forEach(a -> {
                postsIds.add(a.getPostsId());
                accountIds.add(a.getAccountId());
                accountIds.add(a.getBeAnswerId());
            });
            if (!CollectionUtils.isEmpty(postsIds)) {
                postsMap = studentPostsClient.getMapByIds(postsIds);
            }
            //获取禁言名单
            Map<Long, List<Long>> forbiddenAccountIdMap = getForbiddenAccountIds(postsIds);

            //实时获取用户名
            Map<Long, AccountVO> accountMap = queryAccount.queryAccountByIds(new ArrayList<>(accountIds));

            for (PostsCommentVo a : records) {
                //判断是否被禁言
                List<Long> forbiddenAccountIds = new ArrayList<>();
                if (forbiddenAccountIdMap != null) {
                    forbiddenAccountIds = forbiddenAccountIdMap.get(a.getPostsId());
                    if (CollectionUtils.isEmpty(forbiddenAccountIds)){
                        forbiddenAccountIds = new ArrayList<>();
                    }
                    a.setHasForbidden(forbiddenAccountIds.contains(a.getAccountId()));
                    a.setBeAnswerHasForbidden(forbiddenAccountIds.contains(a.getBeAnswerId()));
                }
                //判断内容
                a.setContent(buildContent(forbiddenAccountIds, a.getAccountId(), a.getContent(), context, a.getIsDeleted()));
                if (postsMap != null) {
                    PostsStudentVo studentVo = postsMap.get(a.getPostsId());
                    if (studentVo != null) {

                        if (Constant.TYPE_COMMENT.equals(a.getType())) {
                            a.setPostsContent(filterSensitiveWord.filterWord(studentVo.getContent(), context.getCompanyId()));
                            a.setLogo(studentVo.getLogo());
                        }

                        //帖子是否被删除
                        if (!ForumConstans.UP.equals(studentVo.getStatus())) {
                            a.setPostsHasDeleted(true);
                            a.setPostsContent(ForumConstans.POSTS_HAS_DELETED);
                        }
                        a.setPostsTitle(studentVo.getTitle());
                        a.setPostsCreateTime(studentVo.getCreateTime());
                        //帖子的创建时间
                        a.setCreateTimeString(ForumUtil.getCreatTimeString(studentVo.getCreateTime()));
                    }
                }
                //填充用户信息
                setUserInfo(accountMap, a);
                if (Constant.TYPE_REPLY.equals(a.getType())) {
                    //判断被艾特的人说的内容
                    a.setBeAnswerContent(buildContent(forbiddenAccountIds, a.getBeAnswerId(), a.getBeAnswerContent(), context, a.getBeAnswerContentHasDelete()));
                }
            }
        }
    }

    //获取禁言名单的用户ids

    /**
     * @param postsIds
     * @return
     */
    public Map<Long, List<Long>> getForbiddenAccountIds(List<Long> postsIds) {
        if (CollectionUtils.isEmpty(postsIds) || postsIds == null) {
            return null;
        }
        Map<Long, List<Long>> map = new HashMap<>();
        //获取禁言名单
        List<PostsForbiddenAccountVo> forbiddenAccounts = postsForbiddenAccountClient.getListByPostsId(postsIds);
        if (!CollectionUtils.isEmpty(forbiddenAccounts)) {
            forbiddenAccounts.forEach(a -> {
                if (map.containsKey(a.getPostsId())) {
                    List<Long> forbiddenList = map.get(a.getPostsId());
                    if (forbiddenList == null) {
                        forbiddenList = new ArrayList<>();
                        forbiddenList.add(a.getAccountId());
                    } else {
                        forbiddenList.add(a.getAccountId());
                    }
                } else {
                    List<Long> forbiddenList = new ArrayList<>();
                    forbiddenList.add(a.getAccountId());
                    map.put(a.getPostsId(), forbiddenList);
                }
            });
        }
        return map;
    }

    //填充用户信息

    /**
     * @param accountMap
     * @param a
     */
    public void setUserInfo(Map<Long, AccountVO> accountMap, PostsCommentVo a) {
        //填充用户信息
        if (accountMap != null) {
            AccountVO accountVO = accountMap.get(a.getAccountId());
            if (accountVO != null) {
                a.setCommentator(accountVO.getFullName() != null ? accountVO.getFullName() : accountVO.getName());
                a.setPhoto(accountVO.getHeadPortrait());
            }
            AccountVO accountVO1 = accountMap.get(a.getBeAnswerId());
            if (accountVO1 != null) {
                a.setBeAnswerName(accountVO1.getFullName() != null ? accountVO1.getFullName() : accountVO1.getName());
            }
        }
    }


    /**
     * 对内容做处理
     *
     * @param forbiddenAccountIds
     * @param accountId
     * @param content
     * @param context
     * @return
     */
    public String buildContent(List<Long> forbiddenAccountIds, Long accountId, String content, RequestContext context, Boolean isDeleted) {
        if (isDeleted) {
            return Constant.COMMENT_HAS_DELETED;
        }
        if (CollectionUtils.isEmpty(forbiddenAccountIds)) {
            //过滤敏感词
            return filterSensitiveWord.filterWord(content, context.getCompanyId());
        }
        if (forbiddenAccountIds.contains(accountId)) {
            //用户已被禁言
            return ForumConstans.ACCOUNT_IS_FORBIDDEN;
        } else {
            //过滤敏感词
            return filterSensitiveWord.filterWord(content, context.getCompanyId());
        }
    }

    /**
     * 论坛  我收到的回复 查看对话
     *
     * @param id
     * @return
     */
    @GetMapping("/catCommunication")
    @ApiOperation(value = "我的回复--收到的回复--查看对话", response = PostsCommentVo.class)
    public Response<Page<PostsCommentVo>> catCommunication(@ApiParam("回复id必传 ") @RequestParam("id") Long id) {
        List<PostsCommentVo> postsCommentVos = studentCommentClient.catCommunication(id);

        if (!CollectionUtils.isEmpty(postsCommentVos)) {
            //实时获取用户名
            Set<Long> accountIds = new HashSet<>(postsCommentVos.size());
            List<Long> postsIds = Arrays.asList(postsCommentVos.get(0).getPostsId());
            postsCommentVos.forEach(a -> {
                accountIds.add(a.getAccountId());
            });

            //获取禁言名单
            Map<Long, List<Long>> forbiddenAccountIdMap = getForbiddenAccountIds(postsIds);
            Map<Long, AccountVO> accountMap = queryAccount.queryAccountByIds(new ArrayList<>(accountIds));
            RequestContext context = ContextHolder.get();
            for (PostsCommentVo a : postsCommentVos) {

                //帖子的创建时间
                a.setCreateTimeString(ForumUtil.getCreatTimeString(a.getCreateTime()));
                //填充用户信息
                setUserInfo(accountMap, a);
                //判断是否被禁言
                List<Long> forbiddenAccountIds = new ArrayList<>();
                if (forbiddenAccountIdMap != null) {
                    forbiddenAccountIds = forbiddenAccountIdMap.get(a.getPostsId());
                }
                if (CollectionUtils.isEmpty(forbiddenAccountIds)){
                    forbiddenAccountIds = new ArrayList<>();
                }
                //当前记录创建人是否被禁言
                a.setHasForbidden(forbiddenAccountIds.contains(a.getAccountId()));
                a.setContent(this.buildContent(forbiddenAccountIds, a.getAccountId(), a.getContent(), context, a.getIsDeleted()));
                //当前用户是否被禁言
                a.setCurrentHasForbidden(forbiddenAccountIds.contains(context.getAccountId()));

            }
        }
        return Response.ok(postsCommentVos);
    }

    /**
     * 论坛  我发送的回复分页
     *
     * @param param
     * @return
     */
    @PostMapping("/mySendPage")
    @ApiOperation(value = "我发送的回复", response = PostsCommentVo.class)
    public Response<Page<PostsCommentVo>> mySendPage(@ApiParam("type必传 ") @RequestBody CommentParam param) {

        Page<PostsCommentVo> page = studentCommentClient.mySendPage(param);
        List<PostsCommentVo> records = page.getRecords();
        buildRecords(records);
        return Response.ok(page);
    }


    /**
     * 论坛  我的管理--回复管理--回复列表分页
     *
     * @param type
     * @param postsId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getPageByPostsId")
    @ApiOperation(value = "我的管理--回复管理--回复列表", response = PostsCommentVo.class)
    public Response<Page<PostsCommentVo>> getPageByPostsId(@ApiParam("type必传 ") @RequestParam("type") Integer type,
                                                           @ApiParam("帖子id ") @RequestParam("postsId") Long postsId,
                                                           @ApiParam("pageNo") @RequestParam("pageNo") Integer pageNo,
                                                           @ApiParam("pageSize ") @RequestParam("pageSize") Integer pageSize) {

        Page<PostsCommentVo> page = studentCommentClient.getPageByPostsId(type, postsId, pageNo, pageSize);
        List<PostsCommentVo> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            //获取禁言名单
            Map<Long, List<Long>> forbiddenAccountIdMap = getForbiddenAccountIds(Arrays.asList(postsId));
            //实时获取用户名
            Set<Long> accountIds = records.stream().map(a -> a.getAccountId()).collect(Collectors.toSet());
            Map<Long, AccountVO> accountMap = queryAccount.queryAccountByIds(new ArrayList<>(accountIds));

            for (PostsCommentVo a : records) {
                //判断是否被禁言
                List<Long> forbiddenAccountIds = new ArrayList<>();
                if (forbiddenAccountIdMap != null) {
                    forbiddenAccountIds = forbiddenAccountIdMap.get(a.getPostsId());
                }
                if (CollectionUtils.isEmpty(forbiddenAccountIds)){
                    forbiddenAccountIds = new ArrayList<>();
                }
                a.setHasForbidden(forbiddenAccountIds.contains(a.getAccountId()));
                //填充用户信息
                setUserInfo(accountMap, a);
            }
        }
        return Response.ok(page);
    }

    @GetMapping("/down")
    @ApiOperation(value = "我的管理--回复管理--回复列表--回复删除", response = PostsCommentVo.class)
    public Response down(@ApiParam("回复评论id ") @RequestParam("id") Long id,
                         @ApiParam(name = "type", value = "1评论 2回复") @RequestParam("type") Integer type,
                         @ApiParam(name = "isInform", value = "true:来自举报") @RequestParam(value = "isInform", defaultValue = "false") Boolean isInform) {
        Integer tem = studentCommentClient.down(id, type, isInform);
        if (tem > 0) {
            return Response.ok("操作成功！");
        } else {
            return Response.fail("操作失败！");
        }
    }
}