package com.prolog.eis.service.wms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.prolog.eis.dto.wms.WmsTaskFinishDto;
import com.prolog.eis.utils.HttpUtil;
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;
import java.util.List;

@Service
@Slf4j
@PrologInterface(key = "wmsTaskFinishBack", name = "WMS作业完成回告", type = InterfaceType.Send)
public class WmsTaskFinishBackService implements StandardInterface<List<WmsTaskFinishDto>, RestMessage> {

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

    @Override
    public RestMessage execute(List<WmsTaskFinishDto> dataObject) throws Exception {
        String restMessage = HttpUtil.postMethod(eis2wmsCarryTaskBack, JSON.toJSONString(dataObject));
        RestMessage<JSONObject> wmsResult = JSON.parseObject(restMessage, RestMessage.class);
        if (!wmsResult.isSuccess()) {
            log.error("请求wms失败" + wmsResult.getMessage());
            throw new Exception("请求wms失败" + wmsResult.getMessage());
        }
        return wmsResult;
    }

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