package com.sw.mes.config.drabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.drabbitmq.config.ExchangeType;
import com.common.drabbitmq.consumer.job.handler.annotation.MqJob;
import com.common.drabbitmq.utils.MqUtil;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.utils.NumberUtil;
import com.sw.mes.enumvalue.EnumValuesEap;
import com.sw.mes.outside.dto.SendEapSignalDto;
import com.sw.mes.outside.service.EapService;
import com.sw.mes.rabbitmq.constants.RoutingKey;
import com.sw.mes.rabbitmq.enums.ExchangeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.UUID;

import static com.common.drabbitmq.config.Constant.INITIALIZE_CONSUMER;

/**
 * @author zhaowenjie
 * Drabbitmq 插件使用教程：https://o96mr2hsra.feishu.cn/wiki/wikcnFLEPGmCD1ixf6hbbTszKib
 */
@Slf4j
@Configuration
public class DrabbitmqConfig {
    private static MqUtil mqUtil;

    @Autowired
    private EapService eapService;

    private static DictionaryItemService dictionaryItemService;

    @Autowired
    public DrabbitmqConfig(MqUtil mqUtil, DictionaryItemService dictionaryItemService) {
        DrabbitmqConfig.mqUtil = mqUtil;
        DrabbitmqConfig.dictionaryItemService = dictionaryItemService;
    }

    private final static String MQJOB_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION = "automatic_delayed_start_of_material_preparation";
    public final static String QUEUE_NAME_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION = "queueName_automatic_delayed_start_of_material_preparation";
    public final static String EXCHANGE_NAME_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION = "exchangeName_automatic_delayed_start_of_material_preparation";
    private final static String ROUTING_KEY_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION = "routingKey_automatic_delayed_start_of_material_preparation";

    /**
     * 初始化队列与发布集群消费者
     */
    @MqJob(INITIALIZE_CONSUMER)
    public void init() {
        // 初始化生产者，消费者
        mqUtil.addQueue(mqUtil.setDefaultRabbitModuleInfo(QUEUE_NAME_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION, EXCHANGE_NAME_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION, ROUTING_KEY_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION, MQJOB_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION, ExchangeType.DELAY));
        // 添加生产者
        mqUtil.addLocalConsumer(QUEUE_NAME_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION, MQJOB_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION, 1, 2, false);
    }

    /**
     * 消费者执行的任务（备料（开炉）任务）
     *
     * @param messageContent 消息内容
     */
    @MqJob(MQJOB_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION)
    public void automaticDelayedStartOfMaterialPreparation(String messageContent) {
        SysLog sysLog = new SysLog();
        sysLog.setName("自动备料");
        sysLog.setRequestId(UUID.randomUUID().toString());
        sysLog.setCreateTime(new Date());
        sysLog.setCreateUserName(BaseContextHandler.getUsername());
        try {
            SendEapSignalDto sendEapSignalDto = JSON.parseObject(messageContent, SendEapSignalDto.class);
            Result result = eapService.sendEapSignal(sendEapSignalDto, EnumValuesEap.SignalSource.EAP.getKey());
            sysLog.setStatus(result.getCode());
            sysLog.setResult(JSON.toJSONString(result));
            if (result.getCode() == ResultCode.SUCCESS.getCode()) {
                log.info("【成功】自动备料处理：" + JSON.toJSONString(result));
            } else {
                log.info("【失败】自动备料处理：" + JSON.toJSONString(result));

            }
        } catch (Exception e) {
            sysLog.setStatus(400);
            sysLog.setResult("【异常】自动开炉处理：" + e.getMessage());
            sysLog.setContent(messageContent);
            log.info("【异常】自动开炉处理：", e);
        }
        mqUtil.sendMessage(RoutingKey.SYS_LOG_KEY, ExchangeEnum.SYS_LOG_EXCHANGE.getName(), JSONObject.toJSONString(sysLog));
    }

    /**
     * 发送备料（开炉）任务的消息
     * 停炉时调用
     *
     * @param equipmentCode 设备号
     */
    public static void sendAutomaticDelayedStartOfMaterialPreparation(String equipmentCode) {
        DictionaryItem dictionaryItem = dictionaryItemService.findByThemeValueAndNameAndEnable("automaticFurnace", "start", true);
        if (dictionaryItem != null && "true".equals(dictionaryItem.getValue())) {
            try {
                SendEapSignalDto sendEapSignalDto = new SendEapSignalDto();
                sendEapSignalDto.setSignal(EnumValuesEap.EapSignalType.开炉.getKey());
                sendEapSignalDto.setEquipmentCode(equipmentCode);
                mqUtil.sendMessage(DrabbitmqConfig.ROUTING_KEY_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION, DrabbitmqConfig.EXCHANGE_NAME_AUTOMATIC_DELAYED_START_OF_MATERIAL_PREPARATION, JSON.toJSONString(sendEapSignalDto), NumberUtil.String2Integer(dictionaryItem.getExtendValue(), 3) * 60 * 1000);
            } catch (Exception e) {
                log.info("mq消息发送失败：" + e.getMessage());
            }
        }
    }
}
