package com.prolog.eis.service.pms;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.prolog.eis.dto.pms.InBoundCarryTaskReq;
import com.prolog.eis.dto.pms.PmsCarryTaskReq;
import com.prolog.eis.dto.pms.PmsResult;
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;

/**
 * @desc:
 * @author: zhangJie
 * @date: 2023/7/11 10:48
 */
@Service
@Slf4j
@PrologInterface(key = "pmsCarryTask", name = "pms搬运任务", type = InterfaceType.Send)
public class PmsCarryTaskService implements StandardInterface<PmsCarryTaskReq, PmsResult> {

    @Value("${pms.pms-carryTask}")
    private String eis2pmsCarryTask;

    @Autowired
    private RestTemplate newRestTemplate;

    @Override
    public PmsResult execute(PmsCarryTaskReq pmsCarryTaskReq)  {
        try {
            PmsResult pmsResult = newRestTemplate.postForObject(eis2pmsCarryTask, pmsCarryTaskReq, PmsResult.class);
            if (!pmsResult.isSuccess()) {
                throw new Exception("请求pms失败" + pmsResult.getMessage());
            }
            return PmsResult.success();
        } catch (Exception e) {
            log.error("容器【{}】请求pms搬运失败：" + e.getMessage(),pmsCarryTaskReq.getContainerNo(), e);
            throw new RetryException(e.getMessage());
        }
    }

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

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