package com.wms.service.business.serviceImplements;

import com.alibaba.fastjson2.JSON;
import com.wms.constants.enums.ConfigMapKeyEnum;
import com.wms.constants.enums.ResponseCode;
import com.wms.entity.app.ResponseEntity;
import com.wms.entity.app.wcs.WcsDisposeVehicleRequest;
import com.wms.entity.table.WmsLog;
import com.wms.service.LogService;
import com.wms.service.business.IWcsService;
import com.wms.utils.HttpUtils;
import com.wms.utils.WmsUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

import static com.wms.config.InitLocalConfig.configMap;
import static com.wms.utils.StringUtils.convertJsonString;

/**
 * Wcs服务实现类
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WcsServiceImplements implements IWcsService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());// 日志
    private final LogService logService;// 日志服务

    /**
     * Wms请求释放箱子
     */
    @Override
    public void sendWcsDisposeVehicle(WcsDisposeVehicleRequest request) throws Exception {
        // 发送任务
        String url = configMap.get(ConfigMapKeyEnum.URL_WCS_DISPOSE_VEHICLE.getConfigKey());
        if (url != null) {
            logger.info("向WCS发送释放箱子请求，地址：{}，请求详情：{}", url, convertJsonString(request));
            ResponseEntity result = JSON.parseObject(HttpUtils.sendHttpPostWithoutToken(url, convertJsonString(request)), ResponseEntity.class);
            try {
                logService.save(new WmsLog(WmsUtils.generateId("LOG_"), "向WCS发送释放箱子请求", ConfigMapKeyEnum.URL_WCS_DISPOSE_VEHICLE.getConfigKey(), convertJsonString(request), convertJsonString(result), url, LocalDateTime.now(), "WMS"));
            } catch (Exception e) {
                logger.error("插入日志错误");
            }
            if (result != null && Objects.equals(ResponseCode.OK.getCode(), result.getCode())) {
                logger.info("Wms请求释放箱子成功");
            } else {
                logger.error("Wms请求释放箱子发生错误：{}", convertJsonString(result));
                throw new Exception("Wms请求释放箱子发生错误");
            }
        } else {
            logger.error("WCS释放箱子地址为空");
            throw new Exception("WCS释放箱子地址为空");
        }
    }
}
