package com.yeejoin.amos.knowledgebase.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.service.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.StringUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.doc.TycloudResource;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.List;
import java.util.Map;

@RestController
@TycloudResource(module = "knowledgebase", value = "interactionrecord")
@RequestMapping(value = "/v1/message")
@Api(tags = "knowledgebase-推送消息")
public class MessageResource {

    private final String paramUsers = "target";
    private final String paramTitle = "docTitle";
    private final String paramContent = "content";
    private final String paramDocSeq = "docSeq";
    private final String paramWay = "way";
    private final Logger logger = LogManager.getLogger(MessageResource.class);
    @Autowired
    private MessageService messageService;


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询用户的消息列表.")
    @RequestMapping(value = "/list/owner", method = RequestMethod.GET)
    public ResponseModel list(@RequestParam(value = "messageType", required = false) String messageType) {
        if (ValidationUtil.isEmpty(messageType)) {
            messageType = null;
        }
        return ResponseHelper.buildResponse(messageService.queryByOwner(RequestContext.getExeUserId(), messageType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据id查询消息详情.")
    @RequestMapping(value = "/{sequenceNbr}", method = RequestMethod.GET)
    public ResponseModel queryOne(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(messageService.queryById(sequenceNbr));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "阅读消息.")
    @RequestMapping(value = "/status/read/{ids}", method = RequestMethod.PUT)
    public ResponseModel readMessage(@PathVariable(value = "ids") String ids) {
        return ResponseHelper.buildResponse(messageService.readMessage(StringUtil.String2LongList(ids)));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "阅读全部消息.")
    @RequestMapping(value = "/status/read/all", method = RequestMethod.PUT)
    public ResponseModel readAllMessageByUserId() {
        return ResponseHelper.buildResponse(messageService.readAllMessageByUserId(RequestContext.getExeUserId()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "要点推送.")
    @RequestMapping(value = "/essential", method = RequestMethod.POST)
    public ResponseModel pushEssential(@RequestBody Map<String, Object> body) {
        if (body.containsKey(paramUsers) && body.containsKey(paramContent) && body.containsKey(paramDocSeq)) {
            Object usersObj = body.get(paramUsers);
            Object contentObj = body.get(paramContent);
            Object docSeqObj = body.get(paramDocSeq);
            Object titleObj = body.get(paramTitle);
            if (ValidationUtil.isEmpty(usersObj)
                    || !(usersObj instanceof List)
                    || ValidationUtil.isEmpty(contentObj)
                    || ValidationUtil.isEmpty(docSeqObj)
                    || ValidationUtil.isEmpty(titleObj)) {
                throw new BadRequest("参数不能为空");
            }
            try {
                List<Map<String, Object>> users = (List<Map<String, Object>>) body.get(paramUsers);
                String title = titleObj.toString();
                String content = contentObj.toString();
                Long docSeq = Long.valueOf(docSeqObj.toString());
                return ResponseHelper.buildResponse(messageService.pushEssential(users, title, content, docSeq));
            } catch (ClassCastException e) {

            }
        }
        throw new BadRequest("参数格式有误");
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "战例分享.")
    @RequestMapping(value = "/doccontent", method = RequestMethod.POST)
    public ResponseModel shareDoc(@RequestBody Map<String, Object> body) {
        if (body.containsKey(paramUsers) && body.containsKey(paramContent) && body.containsKey(paramWay)) {
            Object usersObj = body.get(paramUsers);
            Object contentObj = body.get(paramContent);
            Object wayObj = body.get(paramWay);
            if (ValidationUtil.isEmpty(usersObj)
                    || !(usersObj instanceof List)
                    || ValidationUtil.isEmpty(contentObj)
                    || !(contentObj instanceof List)
                    || ValidationUtil.isEmpty(wayObj)) {
                throw new BadRequest("参数不能为空");
            }
            try {
                List<Map<String, Object>> users = (List<Map<String, Object>>) usersObj;
                List<Map<String, Object>> content = (List<Map<String, Object>>) contentObj;
                String way = wayObj.toString();
                return ResponseHelper.buildResponse(messageService.shareDoc(users, content, way));
            } catch (ClassCastException e) {
                logger.error(e.getMessage());
            }
        }
        throw new BadRequest("参数格式有误");
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "分页查询查询用户的消息列表.")
    @RequestMapping(value = "/list/page", method = RequestMethod.GET)
    public ResponseModel<Page> list(
            @RequestParam(value = "current", required = true) int current,
            @RequestParam(value = "size", required = true) int size,
            @RequestParam(value = "messageType", required = false) String messageType) {
        if (size < 0 && current < 1) {
            throw new BadRequest("参数有误");
        }
        List<Map> list = messageService.queryByPage(RequestContext.getExeUserId(), current,size,messageType);
        Integer total = messageService.queryByPageCount(RequestContext.getExeUserId(),messageType);
        //构建分页参数
        Page page = new Page();
        page.setCurrent(current);
        page.setSize(size);
        page.setRecords(list);
        page.setTotal(total);
        return ResponseHelper.buildResponse(page);
    }
}
