package com.prolog.eis.service.wms;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.prolog.eis.dto.outbound.WmsOutCbReqDto;
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 org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
@PrologInterface(key = "wmsOutBack", name = "WMS出库回告", type = InterfaceType.Send)
public class WmsOutBackService implements StandardInterface<List<WmsOutCbReqDto>, RestMessage> {

    @Value("${wms.wms-out-back}")
    private String eis2wmsOutBack;
    @Autowired
    private RestTemplate newRestTemplate;

    @Override
    public RestMessage execute(List<WmsOutCbReqDto> dataObject){
        try {
            RestMessage restMessage = newRestTemplate.postForObject(eis2wmsOutBack, dataObject, RestMessage.class);
            if (!restMessage.isSuccess()) {
                throw new Exception("请求wms失败" + restMessage.getMessage());
            }
            return restMessage;
        } catch (Exception e) {
            throw new RetryException(e.getMessage());
        }
    }

    @Override
    public SimpleLog toLog(List<WmsOutCbReqDto> 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 List<WmsOutCbReqDto> toDataObject(SimpleLog simpleLog) {
        if (simpleLog != null) {
            try {
                List<WmsOutCbReqDto> dataObject = JsonUtils.parseJsonString(simpleLog.getData(), new TypeReference<List<WmsOutCbReqDto>>() {
                });
                return dataObject;
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return null;
    }
}
