package com.hs.admin.listener;

import com.hs.admin.bean.OperateEnum;
import com.hs.admin.bean.SysTask;
import com.hs.admin.dao.SysTaskDao;
import com.hs.admin.service.SchedulerJobService;
import com.hs.admin.util.JsonUtils;
import com.hs.admin.util.LogUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * @author xieheng
 */
@Component
public class MyMessageListener implements MessageListener {
    @Resource
    SchedulerJobService schedulerJobService;
    @Resource
    SysTaskDao sysTaskDao;


    @Override
    public void onMessage(Message message) {
        System.out.println(message.getMessageProperties().getConsumerQueue());
        String data = null;
        try {
            data = new String(message.getBody(),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LogUtil.info(">>>>>客户端进入消费,data=:" + data);
        SysTask sysTask = JsonUtils.jsonToBean(data, SysTask.class);
        String type = sysTask.getType();
        if (type.equals(OperateEnum.PAUSE.getCode())) {
            schedulerJobService.pauseJob(sysTask);
            sysTaskDao.updateJobStatus(sysTask);
        } else if (type.equals(OperateEnum.RESUME.getCode())) {
            schedulerJobService.resumeJob(sysTask);
            sysTaskDao.updateJobStatus(sysTask);
        } else if (type.equals(OperateEnum.DELETE.getCode())) {
            schedulerJobService.deleteJob(sysTask);
            sysTaskDao.deleteByJcbIdAndCid(sysTask.getJcbId(),sysTask.getCid());
        } else if (type.equals(OperateEnum.SEND.getCode())) {
            schedulerJobService.initJob(sysTask);
        }
        LogUtil.info(">>>>>客户端消费成功结束");
    }
}
