package org.dromara.zhishu.util;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.ss.formula.functions.T;
import org.aspectj.lang.ProceedingJoinPoint;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.zhishu.domain.bo.RunningLogFileBo;
import org.dromara.zhishu.domain.vo.ProductForm;
import org.dromara.zhishu.service.IRunningLogFileService;

import java.math.BigDecimal;
import java.util.Map;

public class RunningLogUtils {

    private static IRunningLogFileService runningLogFileService;

    private RunningLogUtils(){}

    public static void init(IRunningLogFileService service) {
        runningLogFileService = service;
    }


    public static Object runningLog(ProceedingJoinPoint joinPoint, Map data , String content,String fileType){
        //日志记录 用户id
        String userId = data.get("userId").toString();
        String methodName = joinPoint.getSignature().getName();
        // 1.根据文件类型获取文件最大顺序
        String maxOrder =  runningLogFileService.selectMaxFileOrderByFileTypeAndCreateBy(fileType,userId);
        content = "【"+fileType + "】" + content;
        Object result  = "";
        try{
            /**
             * 调用日志方法
             */
            maxOrder = RunningLogUtils.editRunning(fileType,"【日志开始,方法名称:"+methodName+"】"+content,maxOrder,userId);
            maxOrder = RunningLogUtils.editRunning(fileType,"【执行参数】"+ JsonUtils.toJsonString(data),maxOrder,userId);
            // 执行方法
            result = joinPoint.proceed();
            maxOrder = RunningLogUtils.editRunning(fileType,"【返回参数】"+JsonUtils.toJsonString(result),maxOrder,userId);

//            //获取成功日志文件
//            //获取当前日期
//            String successNum = EasyExcelUtil.readFileContentString(UrlUtil.getUrl()+"log/"+DateUtils.dataYMD()+"_successNumLog.txt");
//            successNum = successNum.replaceAll("\r\n", "");
//            if(StringUtils.isEmpty(successNum)){
//                successNum = "1";
//            }else{
//                successNum = new BigDecimal(successNum).add(new BigDecimal(1)).toString();
//            }
//            //记录成功数据日志
//            EasyExcelUtil.writeJsonToFile("log/"+DateUtils.dataYMD()+"_successNumLog.txt",successNum);

        }catch (Throwable e){
            String msgAll = ExceptionUtils.getStackTrace(e);
            maxOrder = RunningLogUtils.editRunning(fileType,"【系统异常】【异常方法】"+methodName,maxOrder,userId);
            maxOrder = RunningLogUtils.editRunning(fileType,"【系统异常】【异常内容】"+msgAll,maxOrder,userId);
//            //获取失败日志文件
//            String errorNum = EasyExcelUtil.readFileContentString(UrlUtil.getUrl()+"log/"+DateUtils.dataYMD()+"_errorNumLog.txt");
//            errorNum = errorNum.replaceAll("\r\n", "");
//            if(StringUtils.isEmpty(errorNum)){
//                errorNum = "1";
//            }else{
//                errorNum = new BigDecimal(errorNum).add(new BigDecimal(1)).toString();
//            }
//            //记录失败日志
//            EasyExcelUtil.writeJsonToFile("log/"+DateUtils.dataYMD()+"_errorNumLog.txt",errorNum);
        } finally {
            maxOrder = RunningLogUtils.editRunning(fileType,"【日志结束,方法名称:"+methodName+"】"+content,maxOrder,userId);

        }
        return result;
    }

    /**
     * 编写运行日志
     * @param fileTyle   文件类型
     * @param context    日志内容
     * @param maxOrder   文件最大顺序
     */
    public static String editRunning(String fileTyle,String context,String maxOrder,String userId){
        /**
         * 处理日志
         * 时间+日志信息
         */
        context = "【"+DateUtils.getTime() + "】" + context;
        /**
         * 执行文件
         */
        String path = UrlUtil.getUrl() + "log/";
        String fileName = fileTyle + "_" + userId + "_";

        if(StringUtils.isEmpty(maxOrder)){
            maxOrder = "1";

            //生成新的文件名
            fileName += maxOrder;
            //新增数据
            RunningLogFileBo bo = new RunningLogFileBo();
            bo.setFileName(fileName+".txt");
            bo.setFileType(fileTyle);
            bo.setFileOrder(maxOrder);
            bo.setCreateBy(Long.parseLong(userId));
            runningLogFileService.insertByBo(bo);
        }else{
            // 2.根据 "文件类型+最大顺序" 生成文件名获取文件
            fileName += maxOrder;
            // 3.判断文件大小，达到最大大小，则生成新的文件
            String pathMark = path + fileName + ".txt";

            if(FileUtil.isFileSizeExceeds(pathMark)){
                //超过2M 则生成新文件
                maxOrder = new BigDecimal(maxOrder).add(new BigDecimal(1)).toString();
                //生成新的文件名
                fileName = fileTyle + "_" + userId + "_" + maxOrder;
                //新增数据
                RunningLogFileBo bo = new RunningLogFileBo();
                bo.setFileName(fileName+".txt");
                bo.setFileType(fileTyle);
                bo.setFileOrder(maxOrder);
                bo.setCreateBy(Long.parseLong(userId));
                runningLogFileService.insertByBo(bo);
            }
        }
        path = path+fileName+".txt";
        //处理好文件名称，写入文件
        FileUtil.processTxtFile(path,context);

        return maxOrder;
    }
}
