package com.prolog.upcloud.base.wh.operate.utils;

import cn.hutool.core.util.IdUtil;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.upcloud.base.wh.operate.model.EisLog;
import com.prolog.upcloud.base.wh.operate.service.MqOperateProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

import static com.prolog.constant.EisBusinessConstant.EIS;

@Component
@Slf4j
public class EisLogHelper {

    @Resource
    private MqOperateProducer producer;

    public Object handleAndSaveLog(WmsHandleFunctional func, String params, String url) {
        EisLog eisLog = new EisLog();
        eisLog.setId(IdUtil.fastSimpleUUID());
        eisLog.setInitiator(EIS);
        eisLog.setStatus(1);
        eisLog.setUrl(url);
        eisLog.setRequest(params);
        eisLog.setGmtCreate(new Date());
        Object result;
        try {
            result = func.accept();
        } catch (Exception e) {
            eisLog.setStatus(2);
            eisLog.setGmtModified(new Date());
            eisLog.setResponse(e.getMessage());
            producer.saveEisLog(eisLog);
            log.error("", e);
            throw new PrologException(e.getMessage());
        }
        eisLog.setResponse("接收请求成功");
        eisLog.setGmtModified(new Date());
        producer.saveEisLog(eisLog);
        return result;
    }

    @FunctionalInterface
    public interface WmsHandleFunctional {
        Object accept() throws BizException;
    }
}
