package com.ag.log;

import com.ag.base.BaseService;
import com.ag.base.DefaultBussniessImpl;
import com.ag.log.entity.LogParam;
import com.ag.log.entity.UserDefineLog;
import com.ag.util.StrUtil;
import com.ag.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by yangxh on 2022/4/14.
 */
@Service
public class UserDefineLogService extends BaseService {

    @Autowired
    private DefaultBussniessImpl bizDao;

    @Transactional
    public void saveLog(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
        Assert.isTrue(param.has("bizType") && !StrUtil.isEmpty(param.getString("bizType")), "参数异常，bizType不能为空!");
        Assert.isTrue(param.has("keyword") && !StrUtil.isEmpty(param.getString("keyword")), "参数异常，keyword不能为空!");
        Assert.isTrue(param.has("info") && !StrUtil.isEmpty(param.getString("info")), "参数异常，info不能为空!");
        LogParam logParam = new LogParam(param, param.getString("keyword"), param.getString("bizType"), param.getString("info"));
        saveLog(logParam, "wb");
    }

    private void saveLog(LogParam logParam, String sourceType){
        UserDefineLog userLog = new UserDefineLog();
        userLog.setId(UUIDUtil.getUUID());
        userLog.setKeyword(logParam.getKeyword());
        userLog.setSourceType(sourceType);
        userLog.setBizType(logParam.getBizType());
        userLog.setContext(logParam.getDefineInfo());
        super.setSaveUser(logParam.getReqParam(), userLog);
        userLog.setIp(super.getUserIpAddress(logParam.getReqParam()));
        bizDao.save(userLog);
    }

    @Transactional
    public void saveLog(LogParam logParam){
        Assert.notNull(logParam.getDefineInfo(), "参数异常，记录内容不能为空!");
        Assert.notNull(logParam.getKeyword(), "参数异常，关键字不能为空!");
        Assert.notNull(logParam.getBizType(), "参数异常，业务类型不能为空!");
        try {
            saveLog(logParam, "java");
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
