package com.hdkj.lt.mq.listener;

import com.alibaba.fastjson.JSON;
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.google.common.collect.Lists;
import com.hdkj.lt.feign.ILineSvgFileApiClient;
import com.hdkj.lt.modle.dto.file.LineSvgFileBase;
import com.hdkj.lt.modle.dto.file.LineSvgFileGetDTO;
import com.hdkj.lt.modle.dto.svg.SvgGenerationDTO;
import com.hdkj.lt.mq.mapper.base.FeederTopoMapper;
import com.hdkj.hussar.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author wcx
 * @Date 2025/7/18 12:21
 * @Version 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RocketConsumerDistLineFileListener implements MessageListener {

    private final ILineSvgFileApiClient lineSvgFileApiClient;
    private final FeederTopoMapper feederTopoMapper;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            log.info("===== 配电线路SVG文件异动更新-开始消费 =====");
            String type = message.getTag();
            String value = new String(message.getBody(), StandardCharsets.UTF_8);
            // 调用业务层操作
            value = value.replaceAll("\"","");
            this.executeFunc(value, type);
            return Action.CommitMessage;
        } catch (Exception e) {
            log.info("===== 配电线路SVG文件异动更新-消费异常 =====");
//            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)) {
            // 获取异动文件信息，重新成图
            LineSvgFileBase lineSvgFileBase = new LineSvgFileBase();
            // 设置单线图和版本获取异动文件信息
            lineSvgFileBase.setTopoVersion(value).setFileType(type);
            List<LineSvgFileGetDTO> fileList = Optional.ofNullable(lineSvgFileApiClient.getLineByVersion(lineSvgFileBase))
                    .filter(e -> ObjectUtils.isNotEmpty(e.getData())).map(ApiResponse::getData).orElse(Lists.newArrayList());

            List<String> lineIds = fileList.stream().map(LineSvgFileGetDTO::getLineId).collect(Collectors.toList());
            log.info("===== 配电线路【{}】SVG异动文件涉及到 {} 条线路 =====", value, lineIds.size());
            if (ObjectUtils.isNotEmpty(lineIds)) {
                List<String> cityShorts = feederTopoMapper.getCityShortListByIds(lineIds);
                // 解析完成后更新有效无效开关表信息
                cityShorts.forEach(cityShort -> {
                    //*ztj ArgTableNameHandler.setArgument(cityShort);
                    feederTopoMapper.updateDisableLlkgConfig(); // 修改联络开关类型，根据配置和系统判断
                    //*ztj ArgTableNameHandler.setArgument(cityShort);
                    feederTopoMapper.deleteDisableLlkgConfig(); // 删除之前是联络，图模变动后非联络
                    //*ztj ArgTableNameHandler.setArgument(cityShort);
                    feederTopoMapper.insertDisableLlkgConfig(); // 补充图模变动后联络开关
                });
            }
            List<String> errorFile = Lists.newArrayList();
            fileList.forEach(e -> {
                try {
                    // 调用动态成图服务（暂定单个成图）
                    SvgGenerationDTO svgGeneration = new SvgGenerationDTO();
                    svgGeneration.setFeederList(Lists.newArrayList(e.getLineId()));
                    lineSvgFileApiClient.lineDynamicSvgSave(svgGeneration);
                } catch (Exception ex) {
                    errorFile.add(String.format("线路ID：【%s】异常信息：%s", e.getLineId(), ex.getMessage()));
                }
            });
            if (ObjectUtils.isNotEmpty(errorFile)) {
                throw new RuntimeException(JSON.toJSONString(errorFile));
            }
        } else {
            log.info("===== 异动文件重新成图监听-暂无订阅对应操作 =====");
        }
    }
}
