package com.ag.log;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.ag.base.BaseService;
import com.ag.base.DefaultBussniessImpl;
import com.ag.log.pojo.SysOperLog;
import com.ag.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 *
 * 请求日志切面
 * @author fengjun
 */
@Aspect
@Component
public class RequestLogAspect extends BaseService {
    @Autowired
    private DefaultBussniessImpl bizDao;

    /**
    * @Description:  记录请求日志
    * @return: void
    * @Author: fengjun
    * @Date: 2022/4/15
    */
    @Before("@annotation(RequestLog)")
    public void doBefore(JoinPoint joinPoint){
        String bean = joinPoint.getArgs()[3].toString();
        //如果日志类不需要记录
        if ("UserDefineLogService".equals(bean)) {
            return;
        }
        String method = joinPoint.getArgs()[4].toString();
        JSONObject jsonObject = new JSONObject();
        org.json.JSONObject params = (org.json.JSONObject) joinPoint.getArgs()[0];

        String[] ignore = {"sys.date", "sys.id", "selectUseRole", "xwl", "sys.theme", "sys.dispname", "sys.roles",
                "mapMenuRes", "debugSuffix", "sys.editTheme", "bean", "method", "sys.lang","basicsLust",
                "sys.tenancyId", "sys.TENANCY_ID", "subsList", "sys.userLang","sys.useLang", "sys.logined", "useRole",
                "org.springframework.web.context.request.RequestContextListener.REQUEST_ATTRIBUTES",
                "roleIds", "sys.userIpAddress", "sys.ip", "sys.menuid","menuid", "sys.roleList"};
        Set<String> ignoreSet = new HashSet<>(Arrays.asList(ignore));
        for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {
            if(StrUtil.startsWith(stringObjectEntry.getKey(), "org.springframework.")){
                continue;
            }
            if (!ignoreSet.contains(stringObjectEntry.getKey())) {
                jsonObject.put(stringObjectEntry.getKey(), stringObjectEntry.getValue());
            }
        }
        SysOperLog sysOperLog = new SysOperLog();
        sysOperLog.setId(IdUtil.simpleUUID());
        sysOperLog.setBean(bean);
        sysOperLog.setMethod(method);
        sysOperLog.setIp(super.getUserIpAddress(params));
        String param = JSON.toJSONString(jsonObject);
        if (param.length()>1999){
            param.substring(0, 1999);
        }
        sysOperLog.setParams(param);
        sysOperLog.setCreatedBy(super.getSysUserName(params));
//        sysOperLog.setCreatedOn(DateUtil.date());
        //bizDao.save(sysOperLog);
        //MapSqlParameterSource in = new MapSqlParameterSource();

        String sql = "INSERT INTO sys_oper_log (id, bean, method, created_by, created_on, ip, params) VALUES(?, ?, ?, ?, ?, ?, ?)";
        bizDao.getJdbcTemplate().execute(sql,
                new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()){
                    protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
                        ps.setString(1, sysOperLog.getId());
                        ps.setString(2, sysOperLog.getBean());
                        ps.setString(3, sysOperLog.getMethod());
                        ps.setString(4, sysOperLog.getCreatedBy());
                        ps.setTimestamp(5, new java.sql.Timestamp(DateUtil.date().getTime()));
                        ps.setString(6, sysOperLog.getIp());
                        lobCreator.setClobAsString(ps, 7, sysOperLog.getParams());
                    }
                });

        /*DefineLogConfig config = new DefineLogConfig();
        config.setBean(bean);
        config.setMethod(method);
        List<DefineLogConfig> configs = bizDao.findByEqCriteria(config, DefineLogConfig.class, "BEAN", "METHOD");
        if (CollectionUtil.isEmpty(configs)){
            return;
        }
        config = configs.get(0);
        JSONObject reqParam = (JSONObject)joinPoint.getArgs()[0];

        JSONObject datatable = JSON.parseArray(reqParam.getString(config.getControlName())).getJSONObject(0);
        JSONArray createArray = JSON.parseArray(datatable.getString("create"));
        JSONArray updateArray = JSON.parseArray(datatable.getString("update"));
        JSONArray deleteArray = JSON.parseArray(datatable.getString("destroy"));
*/


    }

}
