package com.yizhi.application.forum.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.accountUtil.AuthorizeQueryAccount;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.application.report.research.vo.ReportResearchAnalyze;
import com.yizhi.comment.application.feign.ManageCommentClient;
import com.yizhi.comment.application.vo.ManageCommentVo;
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.feign.PostsForbiddenAccountClient;
import com.yizhi.forum.application.vo.domain.PostsForbiddenAccountVo;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.util.application.constant.ReturnCode;
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("/manage/posts/comment/")
public class PostsCommentController {

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

    @Autowired
    private PostsForbiddenAccountClient postsForbiddenAccountClient;
    @Autowired
    private AuthorizeQueryAccount queryAccount;
    @Autowired
    private ManageCommentClient commentClient;

    /**
     * 管理端 评论（回复）下架或者是删除 若是评论则包含子级,否则不包含
     *
     * @param id
     * @param type 1:评论、2-回复
     * @param operationType 1-下架   2-删除
     * @return
     */
    @ApiOperation(value = "管理端 下架或删除")
    @GetMapping("/down/include/children")
    public Response downIncludeChildren(@ApiParam(name = "id", value = "评论或回复id")@RequestParam("id") Long id,
                                        @ApiParam(name = "type", value = "1:评论、2-回复")@RequestParam("type") Integer type,
                                        @ApiParam(name = "operationType", value = "1-下架   2-删除") @RequestParam("operationType") Integer operationType) {
        Integer tem = commentClient.downIncludeChildren(id, type, operationType);
        if (tem > 0) {
            return Response.ok("操作成功！");
        } else {
            return Response.fail(InternationalEnums.TPPLANCONTROLLER6.getName());
        }
    }

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

        Page<ManageCommentVo> page = commentClient.getPageToManage(type, postsId, pageNo, pageSize);
        List<ManageCommentVo> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)){
            //获取禁言名单
            List<PostsForbiddenAccountVo> forbiddenAccounts = postsForbiddenAccountClient.getListByPostsId(Arrays.asList(postsId));
            List<Long> forbiddenAccountIds = new ArrayList<>();
            if (!CollectionUtils.isEmpty(forbiddenAccounts)){
                forbiddenAccountIds = forbiddenAccounts.stream().map(a -> a.getAccountId()).collect(Collectors.toList());
            }
            //实时获取用户名
            Set<Long> accountIds = new HashSet<>(records.size());
            records.forEach(a -> { accountIds.add(a.getAccountId()); });
            Map<Long, AccountVO> accountMap = queryAccount.queryAccountByIds(new ArrayList<>(accountIds));

            for (ManageCommentVo a : records) {
                //判断是否被禁言
                if (!CollectionUtils.isEmpty(forbiddenAccountIds)){
                    if (forbiddenAccountIds.contains(a.getAccountId())) {
                        a.setHasForbidden(true);
                        a.setStatusString("已禁言");
                    }
                }
                //填充用户信息
                if (accountMap != null) {
                    AccountVO accountVO = accountMap.get(a.getAccountId());
                    if (accountVO != null) {
                        a.setCommentator(accountVO.getName());
                        a.setFullName(accountVO.getFullName());
                        a.setPhoto(accountVO.getHeadPortrait());
                    }
                    AccountVO accountVO1 = accountMap.get(a.getBeAnswerId());
                    if (accountVO1 != null) {
                        a.setBeAnswerName(accountVO1.getFullName() != null ? accountVO1.getFullName() : accountVO1.getName());
                    }
                }
            }
        }
        return Response.ok(page);
    }


    @ApiOperation(value = "单个帖子的回复下载")
    @GetMapping("/export")
    public Response<ReportResearchAnalyze> export(
            @ApiParam(name = "bizId", value = "业务id") @RequestParam(name = "bizId") Long bizId,
            @ApiParam(name = "bizType", value = "业务类型 1：帖子") @RequestParam("bizType") Integer bizType,
            @ApiParam(name = "bizName", value = "业务名称") @RequestParam(name = "bizName") String bizName
    ) {
            RequestContext requestContext = ContextHolder.get();
            Date submitTime = new Date();
            Long currentTaskId = submitTime.getTime();
            String serialNo = "COMMENT-EXPORT-" + currentTaskId;
            String currentTaskName = bizName + "_导出回复数据" + "_" + currentTaskId;

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("accountId", requestContext.getAccountId());
            map.put("siteId", requestContext.getSiteId());
            map.put("companyId", requestContext.getCompanyId());
            map.put("serialNo", serialNo);
            map.put("submitTime", submitTime);
            map.put("bizId", bizId);
            map.put("bizType", bizType);
            map.put("bizName", bizName);
            map.put("currentTaskId", currentTaskId);
            map.put("currentTaskName", currentTaskName);

        try {
            commentClient.exportFromForum(map);
            return Response.ok("导出成功," + " 任务编号："+serialNo + "  任务名称:" + currentTaskName);
        } catch (Exception e) {
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }
}
