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

import cn.estsh.i3plus.core.api.iservice.busi.ISysMessageService;
import cn.estsh.i3plus.core.apiservice.mq.I3CoreQueueConfig;
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.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ImppEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.HqlPack;
import cn.estsh.i3plus.pojo.platform.bean.SysMessage;
import cn.estsh.i3plus.pojo.platform.bean.SysRefUserMessage;
import cn.estsh.i3plus.pojo.platform.repository.SysMessageRepository;
import cn.estsh.i3plus.pojo.platform.repository.SysRefUserMessageRepository;
import cn.estsh.i3plus.pojo.platform.repository.SysUserRepository;
import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ImppRedis;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @Description : 消息服务接口实现
 * @Reference :
 * @Author : yunhao
 * @Date : 2018-10-25 18:02
 * @Modify :
 **/
@Service
public class SysMessageService implements ISysMessageService {

    public static final Logger LOGGER = LoggerFactory.getLogger(SysMessageService.class);

    @Autowired
    private SysMessageRepository sysMessageRDao;

    @Autowired
    private SysRefUserMessageRepository sysRefUserMessageRDao;

    @Autowired
    private SysUserRepository sysUserRDao;

    /**
     * rabbitMQ队列
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @ApiOperation(value = "添加消息")
    public SysMessage insertSysMessage(SysMessage sysMessage) {
        return sysMessageRDao.insert(sysMessage);
    }

    @Override
    @ApiOperation(value = "添加消息")
    public List<SysMessage> insertSysMessage(List<SysMessage> list) {
        return sysMessageRDao.saveAll(list);
    }


    @Override
    @ApiOperation(value = "删除消息")
    public void deleteSysMessageById(Long id) {
        LOGGER.info("消息 SYS_MESSAGE id:{}",id);
        sysRefUserMessageRDao.deleteByProperty("messageId",id);
        sysMessageRDao.deleteById(id);
    }

    @Override
    @ApiOperation(value = "修改消息")
    public void updateSysMessage(SysMessage sysMessage){
        LOGGER.info("消息 SYS_MESSAGE :{}",sysMessage);
        sysMessageRDao.update(sysMessage);
    }

    @Override
    @ApiOperation(value = "查询全部信息")
    public List<SysMessage> listSysMessage(){
        LOGGER.info("消息 SYS_MESSAGE list");
        return sysMessageRDao.list();
    }

    @Override
    @ApiOperation(value = "根据id查询消息")
    public SysMessage getSysMessageById(Long id) {
        LOGGER.info("消息 SYS_MESSAGE id:{}",id);
        return sysMessageRDao.getById(id);
    }

    @Override
    @ApiOperation(value = "系统消息复杂查询，分页，排序")
    public ListPager querySysMessageByPager(SysMessage sysMessage, Pager pager) {
        LOGGER.info("消息 SYS_MESSAGE SysMessage:{}，Pager:{}",sysMessage,pager);
        if(sysMessage == null) {
            pager = PagerHelper.getPager(pager, sysMessageRDao.listCount());
            return new ListPager(sysMessageRDao.listPager(pager),pager);
        }else {
            String hqlPack = CoreHqlPack.packHqlSysMessage(sysMessage);
            pager = PagerHelper.getPager(pager, sysMessageRDao.findByHqlWhereCount(hqlPack));
            return new ListPager(sysMessageRDao.findByHqlWherePage(hqlPack + sysMessage.orderBy(),pager),pager);
        }
    }

    @Override
    @ApiOperation(value = "批量删除消息")
    public void deleteSysMessageByIds(Long[] ids) {
        LOGGER.info("消息 SYS_MESSAGE ids:{}", ids);
        sysMessageRDao.deleteByIds(ids);
    }

    @Override
    @ApiOperation(value = "添加用户消息关系")
    public SysRefUserMessage insertSysRefUserMessage(SysRefUserMessage refUserMessage) {
        return sysRefUserMessageRDao.insert(refUserMessage);
    }

    @Override
    @ApiOperation(value = "添加用户消息关系")
    public List<SysRefUserMessage> insertSysRefUserMessage(List<SysRefUserMessage> refList) {
        return sysRefUserMessageRDao.saveAll(refList);
    }

    @Override
    @ApiOperation(value = "添加消息并发送")
    public void doSendSysMessage(SysMessage sysMessage) {
        // 判断消息类型推送到对应的队列
        if(ImppEnumUtil.MESSAGE_TYPE.MAIL.getValue() == sysMessage.getMessageType().intValue()){
            rabbitTemplate.convertAndSend(PlatformConstWords.IMPP_MESSAGE_MAIL_QUEUE,sysMessage);
        }else{
            rabbitTemplate.convertAndSend(PlatformConstWords.IMPP_MESSAGE_LETTER_QUEUE,sysMessage);
            rabbitTemplate.convertAndSend(PlatformConstWords.IMPP_MESSAGE_LETTER_QUEUE_BAK,sysMessage);
        }
    }

    @Override
    @ApiOperation(value = "分页查询用户消息表")
    public ListPager querySysRefUserMessageByPager(SysRefUserMessage sysRefUserMessage, Pager pager) {
        if(sysRefUserMessage == null) {
            pager = PagerHelper.getPager(pager, sysRefUserMessageRDao.listCount());
            return new ListPager(sysRefUserMessageRDao.listPager(pager),pager);
        }else {
            String hqlPack = CoreHqlPack.packHqlSysRefUserMessage(sysRefUserMessage);
            pager = PagerHelper.getPager(pager, sysRefUserMessageRDao.findByHqlWhereCount(hqlPack));
            return new ListPager(sysRefUserMessageRDao.findByHqlWherePage(hqlPack + sysRefUserMessage.orderBy(),pager),pager);
        }
    }

    @Override
    @ApiOperation(value = "根据用户id和消息状态和查询用户消息表")
    public List findSysRefUserMessageByUserIdAndStatus(Long userId, Integer status) {
        return sysRefUserMessageRDao.findByProperty(new String[]{"receiverId","messageStatus","messageTypeRdd"},
                new Object[]{userId,status,ImppEnumUtil.MESSAGE_TYPE.LETTER.getValue()});
    }

    @Override
    @ApiOperation(value = "根据id查询用户消息")
    public SysMessage getSysMessageByRefUserMessageId(Long id) {
        SysRefUserMessage sysRefUserMessage = sysRefUserMessageRDao.getById(id);
        if (sysRefUserMessage == null){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("数据不存在")
                    .build();
        }
        sysRefUserMessage.setMessageStatus(ImppEnumUtil.MESSAGE_STATUS.READ.getValue());
        sysRefUserMessageRDao.update(sysRefUserMessage);

        return sysMessageRDao.getById(sysRefUserMessage.getMessageId());
    }

    @Override
    public void updateSysRefUserMessageStatusByIds(Long[] ids, Integer status) {
        StringBuffer where = new StringBuffer();
        HqlPack.getInPack(String.join(",", StringTool.getArrayString(ids)), "id", where);
        sysRefUserMessageRDao.updateByHqlWhere(where.toString(), "messageStatus", status);
    }

    @Override
    public void deleteSysRefUserMessageStatusByIds(Long[] ids) {
        sysRefUserMessageRDao.deleteByIds(ids);
    }

    @Resource(name="redisRes")
    private ImppRedis redisRes;
}
