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.AdmireClient;
import com.yizhi.comment.application.feign.InformRecordClient;
import com.yizhi.comment.application.feign.student.StudentCommentClient;
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.PostsClassifyAccountClient;
import com.yizhi.forum.application.feign.PostsClient;
import com.yizhi.forum.application.feign.PostsForbiddenAccountClient;
import com.yizhi.forum.application.feign.PostsReadRecordsClient;
import com.yizhi.forum.application.feign.remote.RemotePostsClient;
import com.yizhi.forum.application.feign.student.StudentPostsClient;
import com.yizhi.forum.application.vo.forum.PostsParamsVo;
import com.yizhi.forum.application.vo.forum.PostsRelationVo;
import com.yizhi.forum.application.vo.forum.PostsSaveVo;
import com.yizhi.forum.application.vo.forum.PostsStudentVo;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.live.application.vo.LiveActivityVO;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.training.application.feign.TpPlanActivityClient;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.tomcat.util.descriptor.web.ContextHandler;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "学员端-帖子接口")
@RestController
@RequestMapping("/student/posts/")
public class StudentPostsController {

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


    @Autowired
    private StudentPostsClient studentPostsClient;
    @Autowired
    private QueryAccountUtil queryAccountUtil;
    @Autowired
    private PostsForbiddenAccountClient postsForbiddenAccountClient;
    @Autowired
    private PostsClassifyAccountClient postsClassifyAccountClient;
    @Autowired
    private FilterSensitiveWord filterSensitiveWord;
    @Autowired
    private AdmireClient admireClient;
    @Autowired
    private StudentCommentClient studentCommentClient;
    @Autowired
    private RemotePostsClient remotePostsClient;
    @Autowired
    private TpPlanActivityClient tpPlanActivityClient;
    @Autowired
    private PostsClient postsClient;
    @Autowired
    private InformRecordClient informRecordClient;
    @Autowired
    private PostsReadRecordsClient postsReadRecordsClient;
    @Autowired
    private LiveActivityClient liveActivityClient;


    /**
     * 获取学员端帖子分页列表
     *
     * @param type
     * @param keyword  分类名称或=帖子名称
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getPageToStudent")
    @ApiOperation(value = "获取学员端帖子分页列表", response = PostsStudentVo.class)
    public Response<Object> getPageToStudent(@ApiParam("1:最新讨论、2：最热讨论、3：精选热帖 0:全部帖子 ") @RequestParam(value = "type",required = false) Integer type,
                                             @ApiParam("分类名称或帖子标题") @RequestParam(value = "keyword", required = false) String keyword,
                                             @ApiParam("分类id") @RequestParam(value = "classifyId", required = false) Long classifyId,
                                             @ApiParam("当前页码") @RequestParam("pageNo") Integer pageNo,
                                             @ApiParam("页内条数") @RequestParam("pageSize") Integer pageSize) {
        Page<PostsStudentVo> page = studentPostsClient.getPageToStudent(type, keyword, classifyId, pageNo, pageSize);
        RequestContext context = ContextHolder.get();
        List<PostsStudentVo> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> accountIds = new ArrayList<>(records.size());
            records.forEach(a -> {
                //屏蔽敏感词
                a.setContent(filterSensitiveWord.filterWord(a.getContent(),context.getCompanyId()));
                accountIds.add(a.getAuthor());
            });
            Map<Long, AccountVO> accountVOMap = queryAccountUtil.queryAccountByIds(accountIds);
            if (accountVOMap != null) {
                records.forEach(a -> {
                    AccountVO accountVO = accountVOMap.get(a.getAuthor());
                    if (accountVO != null) {
                        a.setAuthorName(accountVO.getFullName() != null ? accountVO.getFullName() : accountVO.getName());
                        a.setAuthorPhoto(accountVO.getHeadPortrait());
                    }
                });
            }
        }
        return Response.ok(page);
    }


    @PostMapping("/save")
    @ApiOperation(value = "帖子新增")
    public Response save(@ApiParam("postsClassify") @RequestBody PostsSaveVo vo) {
        String title = vo.getTitle();
        Long classifyId = vo.getPostsClassifyId();
        String content = vo.getContent();

        if (vo.getTerminalType() == null || vo.getType() == null || vo.getVisibleRange() == null) {
            return Response.fail("terminalType、type、visibleRange参数必传！！！");
        }

        if (title == null || title.trim().equals("") || title.length() > 50) {
            return Response.fail("标题不能为空且长度不得多于50字符！");
        }
        if (null == classifyId || classifyId.equals(0)) {
            return Response.fail("请选择分类！");
        }
        if (null == content || content.trim().equals("") || content.length() > 15000) {
            return Response.fail("请填写内容且长度不得多于15000字符！");
        }
        if (!CollectionUtils.isEmpty(vo.getPostsAppendixVos())) {
            if (vo.getPostsAppendixVos().size() > 9) {
                return Response.fail("每次最多上传9个文件！");
            }
        }
        studentPostsClient.studentSave(vo);
        return Response.ok("操作成功！");
    }

    /**
     * 学员端帖子回显
     *
     * @param vo
     * @return
     */
    @PostMapping("/studentGet")
    @ApiOperation(value = "帖子回显", response = PostsSaveVo.class)
    public Response get(@ApiParam("帖子id必填 terminalType必填") @RequestBody PostsParamsVo vo) {
        PostsSaveVo saveVo = studentPostsClient.studentGet(vo);


        // 查询直播的观看权限类型
        List<PostsRelationVo> data = saveVo.getPostsRelationVos();
        List<Long> filterData = data.parallelStream().filter(filterItem ->
                Integer.valueOf(6).equals(filterItem.getType())).map(dataItem-> dataItem.getRelationId()).collect(Collectors.toList());
        if(filterData != null){
            Page<LiveActivityVO> liveData = liveActivityClient.LiveActivityByIds(filterData,0,filterData.size());
            Map<Long,Integer> dataMap = liveData.getRecords().stream().
                    collect(Collectors.toMap(key->key.getId(),val->val.getViewType()));
            for(PostsRelationVo itemTmp :  data){
                if(Integer.valueOf(6).equals(itemTmp.getType()) && dataMap.containsKey(itemTmp.getRelationId())){
                    itemTmp.setViewType(dataMap.get(itemTmp.getRelationId()));
                }
            }
        }


        RequestContext context = ContextHolder.get();
        if (saveVo != null) {
            //过滤敏感词
            saveVo.setContent(filterSensitiveWord.filterWord(saveVo.getContent(), context.getCompanyId()));

            AccountVO accountVO = queryAccountUtil.findById(saveVo.getAuthor());
            if (accountVO != null) {
                saveVo.setAuthorName(accountVO.getFullName() != null ? accountVO.getFullName() : accountVO.getName());
                saveVo.setAuthorPhoto(accountVO.getHeadPortrait());
            }
            //判断是否收藏、被禁言、点赞
            //判断是否有权限评论
            try {
                Integer canComment = postsClassifyAccountClient.canComment(vo.getId());
                saveVo.setCanComment(canComment);
                if (canComment > 0) {
                    saveVo.setHasForbidden(postsForbiddenAccountClient.hasForbiddenByPostsId(vo.getId()));
                }
                if (admireClient.getNum(Constant.TASK_TYPE_POSTS, vo.getId(), context.getAccountId()) > 0) {
                    saveVo.setHasThumbs(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Response.ok(saveVo);
    }

    /**
     * 我的发帖 我的收藏 我的管理 分页数据
     *
     * @param type       1：我的发帖 2：我的收藏 3：我的管理
     * @param status     0：草稿  1：下架  2:上架
     * @param keyword    分类名称或帖子标题
     * @param classifyId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/myPage")
    @ApiOperation(value = "我的", response = PostsStudentVo.class)
    public Response<Object> myPage(@ApiParam("1：我的发帖 2：我的收藏 3：我的管理 ") @RequestParam("type") Integer type,
                                   @ApiParam(" 1：草稿  2：已发表") @RequestParam(value = "status", required = false) Integer status,
                                   @ApiParam("分类名称或帖子标题") @RequestParam(value = "keyword", required = false) String keyword,
                                   @ApiParam("分类id") @RequestParam(value = "classifyId", required = false) Long classifyId,
                                   @ApiParam("当前页码") @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                   @ApiParam("页内条数") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<PostsStudentVo> page = studentPostsClient.myPage(type, status, keyword, classifyId, pageNo, pageSize);
        if (type != 1) {
            List<PostsStudentVo> records = page.getRecords();
            if (!CollectionUtils.isEmpty(records)) {
                List<Long> accountIds = records.stream().map(a -> a.getAuthor()).collect(Collectors.toList());
                Map<Long, AccountVO> accountVOMap = queryAccountUtil.queryAccountByIds(accountIds);
                if (accountVOMap != null) {
                    records.forEach(a -> {
                        AccountVO accountVO = accountVOMap.get(a.getAuthor());
                        if (accountVO != null) {
                            a.setAuthorName(accountVO.getFullName() != null ? accountVO.getFullName() : accountVO.getName());
                            a.setAuthorPhoto(accountVO.getHeadPortrait());
                        }
                    });
                }
            }
        }
        return Response.ok(page);
    }

    @PostMapping("/update")
    @ApiOperation(value = "学员端帖子修改")
    public Response update(@ApiParam("vo") @RequestBody PostsSaveVo vo) {
        String title = vo.getTitle();
        Long classifyId = vo.getPostsClassifyId();
        String content = vo.getContent();

        if (null == vo.getId() ||vo.getId().equals(0)) {
            return Response.fail("id缺少！");
        }

        if (vo.getTerminalType() == null || vo.getType() == null || vo.getVisibleRange() == null) {
            return Response.fail("terminalType、type、visibleRange参数必传！！！");
        }

        if (title == null || title.trim().equals("") || title.length() > 50) {
            return Response.fail("标题不能为空且长度不得多于50字符！");
        }
        if (null == classifyId || classifyId.equals(0)) {
            return Response.fail("请选择分类！");
        }
        if (null == content || content.trim().equals("") || content.length() > 15000) {
            return Response.fail("请填写内容且长度不得多于15000字符！");
        }
        if (!CollectionUtils.isEmpty(vo.getPostsAppendixVos())) {
            if (vo.getPostsAppendixVos().size() > 9) {
                return Response.fail("每次最多上传9个文件！");
            }
        }
        if (studentPostsClient.update(vo) == 1) {
            return Response.ok("操作成功！");
        } else {
            return Response.fail("操作失败！");
        }
    }

    @PostMapping("/up")
    @ApiOperation(value = "帖子发布")
    public Response upOrDown(@ApiParam("vo") @RequestBody PostsParamsVo vo) {
        vo.setType(ForumConstans.UP);
        if (postsClient.upOrDown(vo) == 1) {
            return Response.ok("操作成功！");
        } else {
            return Response.fail("操作失败！");
        }
    }

    @PostMapping("/deleted")
    @ApiOperation(value = "帖子删除")
    public Response deleted(@ApiParam("vo") @RequestBody PostsParamsVo vo) {


        //14是帖子在培训活动中的类型
        Boolean canDown = tpPlanActivityClient.checkBizCanDown(14, vo.getId());
        if (!canDown) {
            return Response.fail("已被培训项目关联，无法下架！");
        }

        //学员端的删除相当于管理端的下架
        vo.setType(ForumConstans.DOWN);
        if (studentPostsClient.deleted(vo) == 1) {
            if (vo.getInformNeed()) {
                //如果是举报列表的下架帖子则需要删除相关举报
                informRecordClient.cancelByCommentId(Constant.TASK_TYPE_POSTS, vo.getId(), 0, null);
            }
            return Response.ok("操作成功！");
        } else {
            return Response.fail("操作失败！");
        }
    }

    /**
     * type 3：加精、4：置顶
     *
     * @param vo
     * @return
     */

    @PostMapping("/topOrHighlight")
    @ApiOperation(value = "帖子加精或置顶")
    public Response<Object> topOrHighlight(@ApiParam("vo") @RequestBody PostsParamsVo vo) {

        if (studentPostsClient.topOrHighlight(vo) == 1) {
            return Response.ok("操作成功！");
        } else {
            return Response.fail("操作失败！");
        }
    }

    /**
     * 获取我的回复（用户的回复收到新的回复未查看时）、我的管理（有回复、举报或帖子未查看）的数量
     *
     * @return
     */

    @GetMapping("/getMyNum")
    @ApiOperation(value = "获取我的回复（用户的回复收到新的回复未查看时）、我的管理（有回复、举报或帖子未查看）的数量")
    public Response<Object> getMyNum() {

        Map<String, Integer> numMap = new HashMap<>();
        PostsParamsVo vo = new PostsParamsVo();
        vo.setAuthor(ContextHolder.get().getAccountId());
        Map<Long, PostsStudentVo> map = remotePostsClient.getMap(vo);

        //获取作者已发帖ids
        List<Long> authorTaskIds = null;
        if (map != null) {
            authorTaskIds = new ArrayList<>(map.size());
            authorTaskIds.addAll(map.keySet());
        }
        Integer myCommentNum = studentCommentClient.myNum(Constant.TASK_TYPE_POSTS, authorTaskIds);
        Integer myManageNum = studentPostsClient.getMyNum();
        numMap.put("myCommentNum", myCommentNum);
        numMap.put("myManageNum", myManageNum);
        return Response.ok(numMap);
    }

    @GetMapping("/postsReadRecords/insertReadRecord")
    @ApiOperation(value = "增加阅读记录")
    public Response insertRecord(@ApiParam("帖子id必传")@RequestParam("postsId") Long postsId,@ApiParam("终端类型") @RequestParam("terminalType") Integer terminalType) {
        //插入查看帖子的阅读记录
        return Response.ok(postsReadRecordsClient.insertReadRecord(postsId, terminalType));
    }

}
