package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysMessageService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ImppEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.SysMessage;
import cn.estsh.i3plus.pojo.platform.bean.SysRefUserMessage;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description : 消息管理服务
 * @Reference :
 * @Author : yunhao
 * @Date : 2018-10-25 19:03
 * @Modify :
 **/
@RestController
@RequestMapping(PlatformConstWords.BASE_URL)
@Api(description = "消息管理服务")
public class SysMessageController extends CoreBaseController {
    public static final Logger LOGGER = LoggerFactory.getLogger(SysMessageController.class);

    @Autowired
    private ISysMessageService sysMessageService;

    @PostMapping(value = "/sys-message/insert")
    @ApiOperation(value = "新增消息",notes = "新增消息")
    public ResultBean insertSysMessage(SysMessage sysMessage){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 条件校验
            ValidatorBean.beginValid(sysMessage)
                    .notNull("messageTitle",sysMessage.getMessageTitle())
                    .notNull("messageContent",sysMessage.getMessageContent())
                    .checkNotZero("messageType",sysMessage.getMessageType())
                    .notNull("messageReceiversId",sysMessage.getMessageReceiversId());

            // 设置发件人名称
            sysMessage.setMessageSenderId(getSessionUser().getUser().getId());
            sysMessage.setMessageSenderNameRdd(getSessionUser().getUserName());
            sysMessage.setMessageSendTime(sdf.format(new Date()));
            sysMessage.setMessageContentType(ImppEnumUtil.MESSAGE_TYPE_CONTENT.HTML.getValue());
            sysMessage.setMessageReceiverType(ImppEnumUtil.MESSAGE_RECEIVER_TYPE.INTERNAL.getValue());

            sysMessageService.doSendSysMessage(sysMessage);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping("/sys-message/delete/{id}")
    @ApiOperation(value = "根据id删除消息",notes = "根据id删除消息")
    public ResultBean deleteSysMessageById(@PathVariable("id") String id){
        try {
            // 条件校验
            ValidatorBean.checkNotNull(id,"id不能为空");

            sysMessageService.deleteSysMessageById(Long.parseLong(id));
            return  ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping("/sys-message/update")
    @ApiOperation(value = "修改信息",notes = "修改信息")
    public ResultBean updateSysMessage(SysMessage sysMessage){
        try {
            // 登录用户
            SessionUser user = AuthUtil.getSessionUser();

            // 条件校验
            ValidatorBean.beginValid(sysMessage)
                    .notNull("messageTitle",sysMessage.getMessageTitle())
                    .notNull("messageContent",sysMessage.getMessageContent())
                    .checkNotZero("messageType",sysMessage.getMessageType());

            sysMessageService.updateSysMessage(sysMessage);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/sys-message/list")
    @ApiOperation(value = "查询全部消息",notes = "查询全部消息")
    public ResultBean findSysMessageAll(){
        try {
            List<SysMessage> sysMessageList = sysMessageService.listSysMessage();
            return  ResultBean.success("操作成功").setResultList(sysMessageList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/sys-message/get/{id}")
    @ApiOperation(value = "根据id查询消息",notes = "根据id查询消息")
    public ResultBean getSysMessageById(@PathVariable("id") String idStr){
        try {
            SysMessage sysMessage = sysMessageService.getSysMessageById(Long.parseLong(idStr));
            if (sysMessage != null) {
                return  ResultBean.success("操作成功").setResultObject(sysMessage).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/sys-message/query")
    @ApiOperation(value = "消息复杂查询，分页，排序",notes = "消息复杂查询，分页，排序")
    public ResultBean querySysMessageByPager(SysMessage sysMessage, Pager pager){
        try {
            ListPager sysMessageListPager = sysMessageService.querySysMessageByPager(sysMessage,pager);
            return  ResultBean.success("操作成功").setListPager(sysMessageListPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping("/sys-message/batch-delete")
    @ApiOperation(value = "批量删除消息",notes = "批量删除消息")
    public ResultBean deleteSysMessageByIds(String[] ids){
        try{
            // 条件判断
            ids = ConvertBean.modelSafeArrayNumber(ids,true);
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }
            sysMessageService.deleteSysMessageByIds(StringTool.getArrayLong(ids));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/user-message/query-inbox")
    @ApiOperation(value = "查询用户收件箱，分页，排序")
    public ResultBean queryInboxByPager(SysRefUserMessage sysRefUserMessage,Pager pager){
        try {
            // 设置消息类型为站内信
            sysRefUserMessage.setMessageTypeRdd(ImppEnumUtil.MESSAGE_TYPE.LETTER.getValue());
            sysRefUserMessage.setReceiverId(getSessionUser().getUser().getId());

            ListPager userMessageList = sysMessageService.querySysRefUserMessageByPager(sysRefUserMessage,pager);
            return  ResultBean.success("操作成功").setListPager(userMessageList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/user-message/query-outbox")
    @ApiOperation(value = "查询用户发件箱，分页，排序")
    public ResultBean querySysRefUserMessageByPager(SysMessage sysMessage,Pager pager){
        try {
            // 发件人为当前用户
            sysMessage.setMessageType(ImppEnumUtil.MESSAGE_TYPE.LETTER.getValue());
            sysMessage.setMessageSenderId(getSessionUser().getUser().getId());

            ListPager sysMessageListPager = sysMessageService.querySysMessageByPager(sysMessage,pager);
            return  ResultBean.success("操作成功").setListPager(sysMessageListPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/user-message/find-unread")
    @ApiOperation(value = "查看用户未读站内信")
    public ResultBean findUnreadUserMessage(){
        try {
            List userMessageList = sysMessageService.findSysRefUserMessageByUserIdAndStatus(getSessionUser().getUser().getId(),
                        ImppEnumUtil.MESSAGE_STATUS.UNREAD.getValue());
            return  ResultBean.success("操作成功").setResultList(userMessageList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/user-message/get/{id}")
    @ApiOperation(value = "根据id查询消息",notes = "根据id查询消息")
    public ResultBean getUserMessageById(@PathVariable("id") String idStr){
        try {
            ValidatorBean.checkNotNull(idStr,"id");

            SysMessage userMessage =sysMessageService.getSysMessageByRefUserMessageId(Long.parseLong(idStr));
            if (userMessage != null) {
                return  ResultBean.success("查询成功").setResultObject(userMessage).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping("/user-message/batch-status")
    @ApiOperation(value = "批量切换消息状态",notes = "批量切换消息状态")
    public ResultBean updateSysMessageStatusByIds(String[] ids,Integer status){
        try{
            // 条件判断
            ValidatorBean.checkNotZero(status,"状态不能为空");
            ids = ConvertBean.modelSafeArrayNumber(ids,true);
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要操作的资源。")
                        .build();
            }
            sysMessageService.updateSysRefUserMessageStatusByIds(StringTool.getArrayLong(ids),status);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/user-message/delete-inbox/{id}")
    @ApiOperation(value = "根据id删除用户消息")
    public ResultBean deleteUserMessageById(@PathVariable("id") String idStr){
        try {
            sysMessageService.deleteSysRefUserMessageStatusByIds(new Long[]{Long.parseLong(idStr)});
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/user-message/batch-delete-inbox")
    @ApiOperation(value = "根据id批量删除用户消息")
    public ResultBean deleteUserMessageByIds(String[] idsStr){
        try {
            sysMessageService.deleteSysRefUserMessageStatusByIds(StringTool.getArrayLong(idsStr));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/user-message/insert")
    @ApiOperation(value = "用户新增消息",notes = "用户新增消息")
    public ResultBean insertUserMessage(SysMessage sysMessage){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 条件校验
            ValidatorBean.beginValid(sysMessage)
                    .notNull("messageTitle",sysMessage.getMessageTitle())
                    .notNull("messageContent",sysMessage.getMessageContent())
                    .notNull("messageReceiversId",sysMessage.getMessageReceiversId());

            // 设置发件人名称
            sysMessage.setMessageType(ImppEnumUtil.MESSAGE_TYPE.LETTER.getValue());
            sysMessage.setMessageSenderId(getSessionUser().getUser().getId());
            sysMessage.setMessageSenderNameRdd(getSessionUser().getUserName());
            sysMessage.setMessageSendTime(sdf.format(new Date()));
            sysMessage.setMessageContentType(ImppEnumUtil.MESSAGE_TYPE_CONTENT.HTML.getValue());
            sysMessage.setMessageReceiverType(ImppEnumUtil.MESSAGE_RECEIVER_TYPE.INTERNAL.getValue());

            sysMessageService.doSendSysMessage(sysMessage);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

}
