package com.muyu.common.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.muyu.common.core.context.SecurityContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;
/**
 * @Author: zi run
 * @Date 2024/9/26 16:43
 * @Description 填充公共字段
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    public MyMetaObjectHandler () {
        log.info("元数据填充初始化成功");
    }

    /**
     * 添加时触发
     * @param metaObject 元数据对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String[] setterNames = metaObject.getSetterNames();
        Set<String> setterNamesSet = Arrays.stream(setterNames).collect(Collectors.toSet());
        if (setterNamesSet.contains("createBy")){
            if (metaObject.getValue("createBy") == null) {
                this.setFieldValByName("createBy", SecurityContextHolder.getUserName(), metaObject);
            }
        }
        if (setterNamesSet.contains("createTime")){
            if (metaObject.getValue("createTime") == null) {
                this.setFieldValByName("createTime", new Date(), metaObject);
            }
        }
    }

    /**
     * 修改时触发
     * @param metaObject 元数据对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String[] setterNames = metaObject.getSetterNames();
        Set<String> setterNamesSet = Arrays.stream(setterNames).collect(Collectors.toSet());
        if (setterNamesSet.contains("updateBy")){
            if (metaObject.getValue("updateBy") == null) {
                this.setFieldValByName("updateBy", SecurityContextHolder.getUserName(), metaObject);
            }
        }
        if (setterNamesSet.contains("updateTime")){
            if (metaObject.getValue("updateTime") == null) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        }
    }
}
