package com.yeejoin.amos.api.openapi.controller.event;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.api.openapi.constant.Constant;
import com.yeejoin.amos.api.openapi.face.model.BizTokenModel;
import com.yeejoin.amos.api.openapi.face.model.OpenapiLogModel;
import com.yeejoin.amos.api.openapi.face.service.OpenapiLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.cache.Redis;
import org.typroject.tyboot.component.event.RestEvent;
import org.typroject.tyboot.component.event.RestEventHandler;

/**
 * 
 * <pre>
 * 第三方API对接日志处理
 * </pre>
 *
 * @author gwb
 * @version $Id: OpenapiLogEventHandler.java, v 0.1 2021年11月10日 下午5:38:32 gwb Exp $
 */
@Component("openapiLogEventHandler")
public class OpenapiLogEventHandler extends RestEventHandler {

    static ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OpenapiLogService openapiLogService;
    
    @Override
    protected void handleEvent(RestEvent restEvent) throws Exception {

    	OpenapiLogModel openapiLogModel = new OpenapiLogModel();
        openapiLogModel.setMethodLabel(restEvent.getMethodLabel());
        openapiLogModel.setMethodName(restEvent.getMethodName());
        openapiLogModel.setParams(objectMapper.writeValueAsString(restEvent.getParams()));
        openapiLogModel.setResult(objectMapper.writeValueAsString(restEvent.getSource()));
        openapiLogModel.setRemoteIp(restEvent.getRequestContextModel().getRequestIP());
        String token = restEvent.getRequestContextModel().getToken();
        openapiLogModel.setToken(token);
        openapiLogModel.setTraceId(restEvent.getRequestContextModel().getTraceId());
        openapiLogModel.setAgencyCode(restEvent.getRequestContextModel().getAgencyCode());
        openapiLogModel.setAppCode(restEvent.getRequestContextModel().getAppKey());
        
    	String tokenKey = Redis.genKey(Constant.TOKEN_PREFIX,token);
    	BizTokenModel bizTokenModel = (BizTokenModel) redisTemplate.opsForValue().get(tokenKey);
    	openapiLogModel.setAppId(bizTokenModel.getAppId());
        openapiLogService.createWithModel(openapiLogModel);
    }
}
