package com.prolog.eis.service.dps;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.prolog.eis.dto.dps.DpsLightLabelCall;
import com.prolog.eis.utils.DpsResult;
import com.prolog.framework.utils.JsonUtils;
import com.prolog.fx.inf.core.Exception.RetryException;
import com.prolog.fx.inf.core.InterfaceType;
import com.prolog.fx.inf.core.StandardInterface;
import com.prolog.fx.inf.core.annotation.PrologInterface;
import com.prolog.fx.inf.core.dto.SimpleLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Service
@Slf4j
@RequiredArgsConstructor
@PrologInterface(key = "dpsLightLabelReported", name = "点亮dps头部标签", type = InterfaceType.Send)
public class DpsLightLabelReported implements StandardInterface<DpsLightLabelCall, DpsResult> {

    @Value("${dps.dps-light-label}")
    private String dpsUrl;
    @Autowired
    private RestTemplate newRestTemplate;

    @Override
    public DpsResult execute(DpsLightLabelCall dataObject) {
        try {
            DpsResult restMessage = newRestTemplate.postForObject(dpsUrl, dataObject, DpsResult.class);
            if (!restMessage.isSuccess()) {
                throw new Exception("请求dps失败" + restMessage.getMsg());
            }
            return restMessage;
        } catch (Exception e) {
            throw new RetryException(e.getMessage());
        }
    }

    @Override
    public SimpleLog toLog(DpsLightLabelCall dataObject) {
        SimpleLog simpleLog = new SimpleLog();
        try {
            simpleLog.setData(JsonUtils.toString(dataObject));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
        return simpleLog;
    }

    @Override
    public DpsLightLabelCall toDataObject(SimpleLog simpleLog) {
        if (simpleLog != null) {
            try {
                return JsonUtils.parseJsonString(simpleLog.getData(), new TypeReference<DpsLightLabelCall>() {});
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return null;
    }
}
