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.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdkj.lt.core.bizms.modle.po.MessageRetryLog;
import com.hdkj.lt.mq.entity.dto.AcceptPlanPowerCutDTO;
import com.hdkj.lt.mq.entity.dto.FeederInfo;
import com.hdkj.lt.mq.entity.po.GridPdOutagePlanBasePO;
import com.hdkj.lt.mq.mapper.plan.GridPdOutagePlanBaseMapper;
import com.hdkj.lt.mq.service.base.MessageRetryLogService;
import com.hdkj.lt.mq.service.plan.AcceptPlanPowerCutService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Slf4j
@Component
public class RocketConsumerOutagePlanListener implements MessageListener {

    @Autowired
    AcceptPlanPowerCutService acceptPlanPowerCutService;

    @Autowired
    MessageRetryLogService messageRetryLogService;

    @Autowired
    GridPdOutagePlanBaseMapper pdOutagePlanBaseMapper;

    @Autowired
    ObjectMapper objectMapper;


    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            log.info("===== 解析计划平台的数据，生成停电范围 =====");
            message.getTopic();
            String type = message.getTag(); // 1-计划停电，2-故障停电
            String value = objectMapper.readValue(message.getBody(), String.class);
            // 调用业务层操作
            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;
        }
    }

    private void executeFunc(String value, String type) throws JsonProcessingException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LambdaUpdateWrapper<GridPdOutagePlanBasePO> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(GridPdOutagePlanBasePO::getPlanId, value);
        GridPdOutagePlanBasePO planBasePO = pdOutagePlanBaseMapper.selectOne(wrapper);
        if (planBasePO.getFeederList() == null) {
            log.warn("计划不存在线路信息");
            return;
        }
        List<FeederInfo> feederInfoList = objectMapper.readValue(planBasePO.getFeederList(), new TypeReference<List<FeederInfo>>() {
        });
        AcceptPlanPowerCutDTO acceptPlanPowerCutDTO = AcceptPlanPowerCutDTO.builder()
                .planId(Long.valueOf(value)).planNo(planBasePO.getOutageNumber())
                .planDesc(planBasePO.getOutageDesc()).planStatus(planBasePO.getPlanStatus())
                .startTime(LocalDateTime.parse(planBasePO.getStartTime(), formatter))
                .endTime(LocalDateTime.parse(planBasePO.getEndTime(), formatter))
                .sourceSystem("01")
                .validFlag(planBasePO.getValidFlag())
                .build();
        acceptPlanPowerCutDTO.setFeederList(feederInfoList);
        acceptPlanPowerCutService.acceptPlanPowerCut(acceptPlanPowerCutDTO);
    }
}
