package com.hdkj.lt.si.feign;

import com.hdkj.lt.base.constants.RocketMQConstants;
import com.hdkj.lt.core.mq.client.RocketMQTemplate;
import com.hdkj.lt.core.mq.config.RocketMQProperties;
import com.hdkj.lt.core.mq.model.RocketMQMessageEntity;
import com.hdkj.lt.feign.ICityFeederTopoApiClient;
import com.hdkj.lt.si.service.svg.ICityFeederTopoService;
import com.hdkj.hussar.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

import static cn.hutool.core.date.DatePattern.PURE_DATE_PATTERN;

/**
 * @author Annie
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class CityFeederTopoApiClient implements ICityFeederTopoApiClient {

    private final ICityFeederTopoService cityFeederTopoService;
    private final RocketMQProperties rocketMQProperties;
    private final RocketMQTemplate rocketMQTemplate;

    @Override
    public ApiResponse<List<String>> getCityFeederSvg() {
        return ApiResponse.success(cityFeederTopoService.getCityFeederSvg());
    }

    @Override
    public ApiResponse<Object> doCityFeederTopo(List<String> list) {
        Boolean flag = cityFeederTopoService.doCityFeederTopo(list);
        if (flag) {
            return ApiResponse.success();
        }
        return ApiResponse.fail("处理拓扑数据失败");
    }

    @GetMapping(API_MAPPING_SERVICE_TOPO_SEND_MSG)
    public ApiResponse<String> sendMessage2LineFile(String topoVersion) {
        try {
            String body = Optional.ofNullable(topoVersion).orElse(LocalDate.now().format(DateTimeFormatter.ofPattern(PURE_DATE_PATTERN)));
            if (rocketMQProperties.getEnabled()) {
                RocketMQMessageEntity messageEntity = RocketMQMessageEntity.builder()
                        .topicId(RocketMQConstants.TOPIC_ID_DIST_LINE_MAPPING_FILE_TICKET)
                        .cacheKey(RocketMQConstants.TOPIC_ID_DIST_LINE_MAPPING_FILE_TICKET)
                        .tag("1")
                        .body(body).build();
                rocketMQTemplate.sendAsyncMessage(messageEntity);
            }
            return ApiResponse.success("发送MQ异步消息处理线路SVG成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ApiResponse.fail(ex.getMessage());
        }
    }
}
