package com.hdkj.lt.mq.listener;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.hdkj.lt.core.bizms.modle.po.MessageRetryLog;
import com.hdkj.lt.mq.service.base.MessageRetryLogService;
import com.hdkj.lt.mq.service.fault.FaultFhzgReasoningPlatformService;
import com.hdkj.lt.mq.service.plan.FhzgReasoningPlatformService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class RocketConsumerFhzgPlanPowerCutListener implements MessageListener {

    @Autowired
    FhzgReasoningPlatformService fhzgReasoningPlatformService;

    @Autowired
    FaultFhzgReasoningPlatformService faultFhzgReasoningPlatformService;
    @Autowired
    MessageRetryLogService messageRetryLogService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            log.info("===== 解析计划平台的数据，生成停电范围 =====");
            message.getTopic();
            String type = message.getTag(); // 1-计划停电，2-故障停电
            String value = new String(message.getBody(), StandardCharsets.UTF_8);
            // 调用业务层操作
            this.executeFunc(value, type);
            return Action.CommitMessage;
        } catch (Exception e) {
            MessageRetryLog messageRetryLog = MessageRetryLog.builder().messageId(message.getTopic())
                    .errorLog(e.getMessage()).messageBody(new String(message.getBody(), StandardCharsets.UTF_8))
                    .tag(message.getTag()).step(1).build();
            messageRetryLogService.saveLog(messageRetryLog);
            e.printStackTrace();
            return Action.ReconsumeLater;
        }
    }

    /**
     * 执行mq消费方法
     */
    private void executeFunc(String value, String type) {
        if (StringUtils.equals("1", type)) {
            Long planId = Long.valueOf(value); // 处理参数信息
            // 解析计划转供范围结果操作
            fhzgReasoningPlatformService.getPowerOutAreaList(planId);
        } else if (StringUtils.equals("2", type)) {
            Long faultId = Long.valueOf(value); // 处理参数信息
            // 解析故障转供范围信息
            faultFhzgReasoningPlatformService.getAnalyzeParam(faultId);
        } else {
            log.info("===== 解析转供范围计算计算推演平台结果-暂无订阅对应操作 =====");
        }
    }

}
