
package com.lideeyunji.core.framework.config.log;

import cn.hutool.core.bean.BeanUtil;
import com.lideeyunji.core.framework.entity.LogRequestApiEntity;
import com.lideeyunji.core.framework.entity.LogRequestErrorApiEntity;
import com.lideeyunji.core.framework.mapper.LogApiErrorMapper;
import com.lideeyunji.core.framework.mapper.LogApiMapper;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.core.framework.params.model.LogRequestApiModel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 异步监听日志事件
 *
 * @author Chill
 */
@Component
@Slf4j
@AllArgsConstructor
public class ApiLogListener {


    @Autowired
    private LogApiMapper logApiMapper;

    @Autowired
    private LogApiErrorMapper logApiErrorMapper;

    static List<String> skipModelTitleList=new ArrayList();
    static {
        skipModelTitleList.add("授权管理");
    }


    @Async("asyncPoolTaskExecutor")
    @Order
    @EventListener(ApiLogEvent.class)
    public void saveApiLog(ApiLogEvent event) {
       try{
           LogRequestApiModel apiModel =(LogRequestApiModel)event.getSource();
           String error = apiModel.getError();
           String modelTitle = apiModel.getModelTitle();
           if(Func.isNotEmpty(modelTitle) && skipModelTitleList.contains(modelTitle)){
               return;
           }

           if(Func.isEmpty(error)){//正常日志
               LogRequestApiEntity infoEntity = BeanUtil.copyProperties(apiModel, LogRequestApiEntity.class);
               logApiMapper.insert(infoEntity);
           }else{//错误日志
               LogRequestErrorApiEntity errorEntity = BeanUtil.copyProperties(apiModel, LogRequestErrorApiEntity.class);
               logApiErrorMapper.insert(errorEntity);
           }
       }catch (Exception e){
           e.printStackTrace();
       }

    }

}
