package com.cftech.sys.util;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.util.StringUtils;
import com.cftech.sys.model.ExportLog;
import com.cftech.sys.model.Log;
import com.cftech.sys.security.UserUtils;
import org.springframework.http.HttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * Created by user on 2018/8/2.
 */
public class ExportUtils {

    public static void handleLog(ExportLog exportLog,String sql,String outSQl,Map<String,Object> parameter)
    {
        exportLog.setOrisql(sql);
        exportLog.setOutsql(outSQl);
        exportLog.setCompileparams(JSONObject.toJSONString(parameter));
    }


    public static ExportLog generateExportLog(Long userid, HttpServletRequest request)
    {
        ExportLog log = new ExportLog();
        StringBuilder params = new StringBuilder();
        int index = 0;
        log.setType(ExportLog.TYPE_ACCESS);
        log.setCreateBy(String.valueOf(userid));
        log.setRemoteAddr(StringUtils.getRemoteAddr(request));
        log.setUserAgent(request.getHeader("user-agent"));
        log.setRequestUri(request.getRequestURI());
        log.setAppid(UserUtils.getmpaccounts(request));
        log.setMethod(request.getMethod());
        for (Object param : request.getParameterMap().keySet()){
            params.append((index++ == 0 ? "" : "&") + param + "=");
            params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase((String)param, "password")
                    ? "" : request.getParameter((String)param), 100));
        }
        log.setParams(params.toString());
        return log;
    }

    public static String formatSql(String oriSql)
    {
        StringTokenizer whitespaceStripper = new StringTokenizer(oriSql);
        StringBuilder outerBuilder = new StringBuilder();
        while (whitespaceStripper.hasMoreTokens()) {
            outerBuilder.append(whitespaceStripper.nextToken());
            outerBuilder.append(" ");
        }
        return outerBuilder.toString();

    }

//    public static void main(String[]args)
//    {
//        String sql = "select hello, osadad                   dadnasdnalkjndw from               dkadasdjj where dasd ='1' ";
//        System.out.println(sql);
//        sql = formatSql(sql);
//        System.out.println(sql);
//    }


}
