package com.zhiqiyun.open.router.config;

import com.alibaba.fastjson.JSON;
import com.dliyun.oap.framework.annotation.ServiceMethod;
import com.dliyun.oap.framework.context.OapRequestContext;
import com.dliyun.oap.framework.interceptor.AbstractOapInterceptor;
import com.dliyun.oap.framework.response.OapResponse;
import com.zhiqiyun.open.core.models.app.ApiRequestLog;
import com.zhiqiyun.open.core.service.ApiRequestLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author stjdydayou
 */
@Component
@Slf4j
public class RequestLogInterceptor extends AbstractOapInterceptor {

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private ApiRequestLogService apiRequestLogService;

    @Override
    public void beforeService(OapRequestContext orc, Map<String, Object> requestParams) {
        ServiceMethod serviceMethod = orc.getServiceMethodHandler().getHandlerMethod().getAnnotation(ServiceMethod.class);
        log.debug("beforeService ...{}", serviceMethod.method());
    }

    @Override
    public void beforeResponse(OapRequestContext orc, Map<String, Object> requestParams) {
        ServiceMethod serviceMethod = orc.getServiceMethodHandler().getHandlerMethod().getAnnotation(ServiceMethod.class);
        log.debug("beforeResponse ...{}", serviceMethod.method());
        this.threadPoolTaskExecutor.execute(() -> {
            try {
                ApiRequestLog requestLog = new ApiRequestLog();
                requestLog.setId(orc.getRequestId());
                requestLog.setAppKey(orc.getAppKey());
                requestLog.setMethod(orc.getMethod());
                requestLog.setVersion(orc.getVersion());
                requestLog.setRequestBody(JSON.toJSONString(requestParams));
                requestLog.setServiceBeginTime(new Date(orc.getServiceBeginTime()));
                requestLog.setServiceEndTime(new Date(orc.getServiceEndTime()));
                requestLog.setClientIp(orc.getClientIp());
                OapResponse response = orc.getOapResponse();
                if (response != null) {
                    requestLog.setResponseData(JSON.toJSONString(response));
                }
                this.apiRequestLogService.save(requestLog);
            } catch (Exception e) {
                log.warn("save ApiRequestLog error", e);
            }
        });
    }
}
