package com.prolog.eis.service.wcs;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.prolog.eis.dto.wcs.WcsCarryTaskDto;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.utils.JsonUtils;
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 = "WcsCarryTaskService", name = "交叉带分拣机mcs搬运任务发送", type = InterfaceType.Send)
public class WcsCarryTaskService implements StandardInterface<WcsCarryTaskDto, RestMessage> {

    @Value("${wcs.wcs-carry-task}")
    private String wcsUrl;
    @Autowired
    private RestTemplate newRestTemplate;

    @Override
    public RestMessage execute(WcsCarryTaskDto dataObject) throws Exception {
        RestMessage wmsResult = newRestTemplate.postForObject(wcsUrl, dataObject, RestMessage.class);
        if (!wmsResult.isSuccess()) {
            log.error("发送wcs任务失败" + wmsResult.getMessage());
            throw new Exception("发送wcs任务失败" + wmsResult.getMessage());
        }
        return wmsResult;
    }

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

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