package com.prolog.eis.service.led.impl;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.prolog.eis.dto.led.LedReqDTO;
import com.prolog.eis.utils.WmsHttpUtils;
import com.prolog.framework.common.message.RestMessage;
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.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
@PrologInterface(key = "ledApi", name = "led服务接口", type = InterfaceType.Send)
public class LedApiService implements StandardInterface<LedReqDTO, RestMessage> {

    @Value("${led.url}")
    private String ledUrl;
    @Autowired
    private WmsHttpUtils httpUtils;

    @Override
    public RestMessage execute(LedReqDTO dataObject) {
        try {
            System.out.println("----->请求led服务参数:" + JSONUtil.toJsonStr(dataObject) + "url;" + ledUrl);
            log.info("----->请求led服务参数:{}", JSONUtil.toJsonStr(dataObject));
            RestMessage restMessage = httpUtils.postLed(ledUrl, dataObject);
            if (!restMessage.isSuccess()) {
                System.out.println("----->请求led失败:" + restMessage.getMessage());
            }
            log.info("----->请求led服务参数:{}，返回值：{}", JSONUtil.toJsonStr(dataObject),JSONUtil.toJsonStr(restMessage));
            System.out.println("----->请求led服务参数:" + JSONUtil.toJsonStr(dataObject) + "返回值;" + JSONUtil.toJsonStr(restMessage));
            return restMessage;
        }  catch (RetryException e) {
            throw new RetryException(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("----->请求led失败:" + e.getMessage());
        }
        return null;
    }

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

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