package com.seer.teach.teacher.util;

import cn.hutool.json.JSONUtil;
import com.seer.teach.teacher.module.entity.ModificationLogEntity;
import com.seer.teach.teacher.service.ModificationLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 修改日志工具类
 *
 * @author Lingma
 * @since 2025-11-26
 */
@Slf4j
@Component
public class ModificationLogUtils {

    private static ModificationLogService modificationLogService;

    @Autowired
    public void setModificationLogService(ModificationLogService modificationLogService) {
        ModificationLogUtils.modificationLogService = modificationLogService;
    }

    /**
     * 记录修改日志
     *
     * @param targetType     目标类型 1-知识点 2-单元 3-教材
     * @param targetId       目标ID
     * @param targetName     目标名称
     * @param operationType  操作类型 1-新增 2-修改 3-删除
     * @param beforeData     修改前数据
     * @param afterData      修改后数据
     * @param operatorId     操作人ID
     */
    public static void logModification(Integer targetType, Integer targetId, String targetName,
                                      Integer operationType, Object beforeData, Object afterData,
                                      Integer operatorId) {
        try {
            ModificationLogEntity logEntity = new ModificationLogEntity();
            logEntity.setTargetType(targetType);
            logEntity.setTargetId(targetId);
            logEntity.setTargetName(targetName);
            logEntity.setOperationType(operationType);
            logEntity.setBeforeData(JSONUtil.toJsonStr(beforeData));
            logEntity.setAfterData(JSONUtil.toJsonStr(afterData));
            logEntity.setOperatorId(operatorId);

            modificationLogService.save(logEntity);
        } catch (Exception e) {
            log.error("记录修改日志失败: ", e);
        }
    }

    public static void logModification(Integer targetType, Integer targetId, String targetName,
                                       Integer operationType,
                                       Integer operatorId,String remark) {
        try {
            ModificationLogEntity logEntity = new ModificationLogEntity();
            logEntity.setTargetType(targetType);
            logEntity.setTargetId(targetId);
            logEntity.setTargetName(targetName);
            logEntity.setOperationType(operationType);
            logEntity.setOperatorId(operatorId);
            logEntity.setRemark(remark);
            modificationLogService.save(logEntity);
        } catch (Exception e) {
            log.error("记录修改日志失败: ", e);
        }
    }
}