package com.prolog.eis.service.wms;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.prolog.eis.dto.inbound.WmsCarryTaskBackReqDto;
import com.prolog.eis.dto.inbound.WmsInBackReqDto;
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;

@Service
@Slf4j
@PrologInterface(key = "wmsCarryTaskBack", name = "WMS借道任务回告", type = InterfaceType.Send)
public class WmsCarryTaskBackService implements StandardInterface<WmsCarryTaskBackReqDto, RestMessage> {

    @Value("${wms.wms-carry-task-back}")
    private String eis2wmsCarryTaskBack;
    @Autowired
    private RestTemplate newRestTemplate;

    @Override
    public RestMessage execute(WmsCarryTaskBackReqDto dataObject) throws Exception {
        try {
            RestMessage wmsResult = newRestTemplate.postForObject(eis2wmsCarryTaskBack, dataObject, RestMessage.class);
            if (!wmsResult.isSuccess()) {
                log.error("请求wms失败" + wmsResult.getMessage());
                throw new Exception("请求wms失败" + wmsResult.getMessage());
            }
            return wmsResult;
        } catch (Exception e) {
            throw new RetryException(e.getMessage());
        }
    }

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