package com.xhkjedu.sexam.listener;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.sexam.mapper.paper.EPaperMapper;
import com.xhkjedu.sexam.mapper.paperstudent.EPaperStudentQuestionMapper;
import com.xhkjedu.sexam.model.paper.EPaper;
import com.xhkjedu.sexam.model.paperstudent.EPaperStudentQuestion;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 消息到达消费者监听类
 */
@Component
@Slf4j
public class MessageConsumer {

    @Resource
    private EPaperStudentQuestionMapper ePaperStudentQuestionMapper;

    @Resource
    private EPaperMapper ePaperMapper;

    /*
     * 学生答案图片合并完处理转换状态
     *
     * @param [message]
     * @return void
     * @author ywx
     * @date 2022/5/9 13:44
     */
    @RabbitHandler
    @RabbitListener(queues = "${rabbitmq.examImgMergeHandleQueue}")
    public void imgMergeHandleQueue(Message message) {
        try {
            String msg = new String(message.getBody(), "UTF-8");
            System.out.println(LocalDateTime.now() + "学生试题答案合并接收消息内容：" + msg);
            EPaperStudentQuestion psq = JSON.parseObject(msg, EPaperStudentQuestion.class);
            if (psq.getConverted() != 1) {//合并失败不修改学生答案
                psq.setStuanswer(null);
            } else {
                psq.setStuanswer(JSON.toJSONString(new String[]{psq.getStuanswer()}));
            }
            ePaperStudentQuestionMapper.updateByPrimaryKeySelective(psq);
        } catch (Exception e) {
            log.error("学生试题答案合并失败：" + e.getMessage());
        }
    }

    /**
     * @Description 修改试卷答题卡pdf
     * @Param [message]
     * @Return void
     * @Author wn
     * @Date 2022/8/2 14:00
     **/
    @RabbitHandler
    @RabbitListener(queues = "${rabbitmq.examBaseToPdfHandleQueue}")
    public void baseToPdfHandleQueue(Message message) {
        try {
            String msg = new String(message.getBody(), "UTF-8");
            System.out.println(LocalDateTime.now() + "答题卡图片合并接收消息内容：" + msg);
            EPaper paper = JSON.parseObject(msg, EPaper.class);
            ePaperMapper.updatePaperScantronpdf(paper);
        } catch (Exception e) {
            log.error("答题卡图片合并失败：" + e.getMessage());
        }
    }
}
