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.core.application.context.ContextHolder;
import com.yizhi.forum.application.constans.ForumConstans;
import com.yizhi.forum.application.feign.PostsClient;
import com.yizhi.forum.application.feign.PostsVisibleRangeClient;
import com.yizhi.forum.application.vo.domain.PostsVisibleRangeVo;
import com.yizhi.forum.application.vo.forum.PostsManageVo;
import com.yizhi.forum.application.vo.forum.PostsParamsVo;
import com.yizhi.forum.application.vo.forum.PostsSaveVo;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.system.application.vo.OrgVO;
import com.yizhi.system.application.vo.UserInfoVO;
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.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.ArrayList;
import java.util.List;
import java.util.Map;

@Api(tags = "管理端-帖子接口")
@RestController
@RequestMapping("/manage/posts/")
public class PostsController {

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


    @Autowired
    private PostsClient postsClient;
    @Autowired
    private PostsVisibleRangeClient postsVisibleRangeClient;
    @Autowired
    private AuthorizeQueryAccount queryAccount;
    @Autowired
    private TpPlanActivityClient tpPlanActivityClient;


    @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(InternationalEnums.POSTSCONTROLLER1.getCode());
        }

        if (title == null || title.trim().equals("") || title.length() > 50) {
            return Response.fail(InternationalEnums.POSTSCONTROLLER2.getCode());
        }
        if (null == classifyId || classifyId.equals(0)) {
            return Response.fail(InternationalEnums.POSTSCONTROLLER3.getCode());
        }
        if (null == content || content.trim().equals("") || content.length() > 15000) {
            return Response.fail(InternationalEnums.POSTSCONTROLLER4.getCode());
        }
        if (!CollectionUtils.isEmpty(vo.getPostsAppendixVos())) {
            if (vo.getPostsAppendixVos().size() > 9) {
                return Response.fail(InternationalEnums.POSTSCONTROLLER5.getCode());
            }
        }
        postsClient.save(vo);
        return Response.ok("操作成功！");
    }

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

        return Response.ok(postsClient.get(vo));
    }

    /**
     * 帖子的指定范围回显
     *
     * @param postsId
     * @return
     */
    @GetMapping("/getVisibleRange")
    @ApiOperation(value = "帖子的指定范围回显", response = PostsVisibleRangeVo.class)
    public Response getVisibleRange(@ApiParam("帖子id必填") @RequestParam("postsId") Long postsId) {

        List<com.yizhi.forum.application.vo.forum.PostsVisibleRangeVo> visibleRanges = postsVisibleRangeClient.getVisibleRange(postsId);
        //实时获取用户真实姓名或部门名称
        if (!CollectionUtils.isEmpty(visibleRanges)) {
            List<Long> orgIds = new ArrayList<>(visibleRanges.size());
            List<Long> accountIds = new ArrayList<>(visibleRanges.size());
            visibleRanges.forEach(a -> {
                if (ForumConstans.ORG.equals(a.getAccountType())) {
                    orgIds.add(a.getAccountId());
                } else if (ForumConstans.ACCOUNT.equals(a.getAccountType())) {
                    accountIds.add(a.getAccountId());
                }
            });
            Map<Long, AccountVO> accountVOMap = queryAccount.queryAccountByIds(accountIds);
            Map<Long, OrgVO> orgVOMap = queryAccount.queryOrgByIds(orgIds);
            visibleRanges.forEach(a -> {
                String accountName = null;
                String accountFullName = null;
                String workNum = null;
                if (ForumConstans.ORG.equals(a.getAccountType())) {
                    if (orgVOMap != null) {
                        OrgVO orgVO = orgVOMap.get(a.getAccountId());
                        if (orgVO != null) {
                            accountName = orgVO.getName();
                        }
                    }
                } else if (ForumConstans.ACCOUNT.equals(a.getAccountType())) {
                    if (accountVOMap != null) {
                        AccountVO accountVO = accountVOMap.get(a.getAccountId());
                        if (accountVO != null) {
                            accountName = accountVO.getName();
                            accountFullName = accountVO.getFullName();
                            workNum = accountVO.getWorkNum();
                        }
                    }
                }
                a.setAccountName(accountName);
                a.setAccountFullName(accountFullName);
                a.setWorkNum(workNum);
            });
        }
        return Response.ok(visibleRanges);
    }

    @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 (vo.getTerminalType() == null || vo.getType() == null || vo.getVisibleRange() == null) {
            return Response.fail(InternationalEnums.POSTSCONTROLLER1.getCode());
        }

        if (title == null || title.trim().equals("") || title.length() > 50) {
            return Response.fail(InternationalEnums.POSTSCONTROLLER2.getCode());
        }
        if (null == classifyId || classifyId.equals(0)) {
            return Response.fail(InternationalEnums.POSTSCONTROLLER3.getCode());
        }
        if (null == content || content.trim().equals("") || content.length() > 15000) {
            return Response.fail(InternationalEnums.POSTSCONTROLLER4.getCode());
        }
        if (!CollectionUtils.isEmpty(vo.getPostsAppendixVos())) {
            if (vo.getPostsAppendixVos().size() > 9) {
                return Response.fail(InternationalEnums.POSTSCONTROLLER5.getCode());
            }
        }
        return Response.ok(postsClient.update(vo) == 1 ? "操作成功！" : "操作失败");
    }

    @PostMapping("/upOrDown")
    @ApiOperation(value = "帖子上下架")
    public Response upOrDown(@ApiParam("vo") @RequestBody PostsParamsVo vo) {
        if (ForumConstans.DOWN.equals(vo.getType())) {
            Boolean canDown = tpPlanActivityClient.checkBizCanDown(14, vo.getId());
            if (!canDown){
                return Response.fail(InternationalEnums.POSTSCONTROLLER6.getCode());
            }
        }

        if (postsClient.upOrDown(vo) == 1) {
            return Response.ok("操作成功！");
        } else {
            return Response.fail(InternationalEnums.TPPLANCONTROLLER6.getCode());
        }
    }


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

        if (postsClient.topOrHighlight(vo) == 1) {
            return Response.ok("操作成功！");
        } else {
            return Response.fail(InternationalEnums.TPPLANCONTROLLER6.getCode());
        }

    }

    /**
     * 获取管理端帖子分页列表
     *
     * @param vo
     * @return
     */
    @PostMapping("/getPage")
    @ApiOperation(value = "获取管理端帖子分页列表", response = PostsManageVo.class)
    public Response getPage(@ApiParam("vo") @RequestBody PostsParamsVo vo) {
        Map<Long, UserInfoVO> userMap = null;
        Page<PostsManageVo> page = new Page<>(vo.getPageNo(), vo.getPageSize());

        if (!StringUtils.isEmpty(vo.getAuthorName())) {
            UserInfoVO userInfoVO = new UserInfoVO();
            userInfoVO.setName(vo.getAuthorName());
            userInfoVO.setCompanyId(ContextHolder.get().getCompanyId());
            userMap = queryAccount.selectUserInfo(userInfoVO);
            if (userMap != null && userMap.size() > 0) {
                vo.setAuthors(new ArrayList<>(userMap.keySet()));
            } else {
                return Response.ok(page);
            }
        }
        page = postsClient.getPage(vo);
        List<PostsManageVo> postsManageVos = page.getRecords();
            //用户名赋值
            if (!CollectionUtils.isEmpty(postsManageVos)) {
                if (!StringUtils.isEmpty(vo.getAuthorName())) {
                    for (PostsManageVo a : postsManageVos) {
                        if (userMap != null) {
                            UserInfoVO accountVO = userMap.get(a.getAuthor());
                            if (accountVO != null) {
                                a.setAuthorName(accountVO.getName());
                            }
                        }
                    }
                } else {
                    List<Long> accountIds = new ArrayList<>(postsManageVos.size());
                    postsManageVos.forEach(a -> {
                        accountIds.add(a.getAuthor());
                    });
                    Map<Long, AccountVO> accountVOMap = queryAccount.queryAccountByIds(accountIds);
                    if (accountVOMap != null) {
                        postsManageVos.forEach(a -> {
                            AccountVO accountVO = accountVOMap.get(a.getAuthor());
                            if (accountVO != null) {
                                a.setAuthorName(accountVO.getName());
                            }
                        });
                    }
                }
            }

        return Response.ok(page);
    }
}
