package cn.com.capcloud.api.action.service;

import cn.com.capcloud.api.KHCResponseEntity;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;

@Service
public class ExecuteService {

    @Autowired
    private LogService logService;

    public ExecuteService(LogService logService) {
        this.logService = logService;
    }

    @FunctionalInterface
    public interface ApiCall {
        String call() throws Exception;
    }
    public KHCResponseEntity execute(String jsonStr,
                                     HttpServletRequest request,
                                     ApiCall apiCall,
                                     boolean needLog) {
        long startTime = needLog ? System.currentTimeMillis() : 0L;
        try {
            String retStr = apiCall.call();
            KHCResponseEntity result = JackJSON.parseObject(retStr, KHCResponseEntity.class);
            if (needLog) {
                logService.apiLogSave(jsonStr, request, result, startTime);
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException("接口调用失败", e);
        }
    }
}

