package com.engine.organization.util;

import com.alibaba.fastjson.JSON;
import com.engine.core.impl.Service;
import com.engine.organization.entity.LoggerContext;
import com.engine.organization.entity.logview.bo.FieldBaseEquator;
import com.engine.organization.transmethod.LogViewTransMethod;
import org.apache.commons.collections.CollectionUtils;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author:dxfeng
 * @createTime: 2022/07/04
 * @version: 1.0
 */
public class OrganizationWrapper extends Service {

    /**
     * 记录操作日志
     *
     * @param clazz  调用类
     * @param value  对象名称
     * @param params 传参
     * @param before 原始对象
     * @param after  更新后对象
     */
    public void writeOperateLog(Class clazz, String value, String params,
                                Object before, Object after) {
        Method method = clazz.getEnclosingMethod();
        LoggerContext loggerContext;
        if (null != before) {
            String formatJson = LogViewTransMethod.getFormatJson(params);
            if (null != after) {
                FieldBaseEquator fieldBaseEquator = new FieldBaseEquator();
                List<String> diffFields = fieldBaseEquator.getDiffFields(before, after);
                if (CollectionUtils.isEmpty(diffFields)) {
                    return;
                }
                StringBuilder message = new StringBuilder();
                for (int i = 0; i < diffFields.size(); i++) {
                    message.append(i + 1).append(".").append(diffFields.get(i)).append("<br/>");
                }
                loggerContext = LoggerContext.builder().operatorId(user.getUID()).value(value).clientIp(user.getLoginip()).paramsStr(formatJson).operatorName(user.getLastname()).message(message.toString()).build();

            } else {
                loggerContext = LoggerContext.builder().operatorId(user.getUID()).value(value).clientIp(user.getLoginip()).paramsStr(formatJson).operatorName(user.getLastname()).message(JSON.toJSONString(before)).build();
            }
            LogAspect logAspect = new LogAspect(clazz, method, loggerContext);
            logAspect.start();
        }
    }


    /**
     * @param clazz   调用类
     * @param value   对象名称
     * @param params  传参
     * @param message 日志描述信息
     */
    public void writeOperateLog(Class clazz, String value, String params,
                                String message) {
        writeOperateLog(clazz, value, params, message, null);
    }


}
