

package com.weather.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.weather.modules.security.user.SecurityUser;
import com.weather.modules.security.user.UserDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 公共字段，自动填充值
 *
 * @author 123
 */
@Slf4j
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_DATE = "createDate";
    private final static String CREATOR = "creator";
    private final static String UPDATE_DATE = "updateDate";
    private final static String UPDATER = "updater";
    private final static String DEPT_ID = "deptId";

    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetail user = SecurityUser.getUser();
        Date date = new Date();

        //创建者（用户ID为空时跳过填充，避免写入无效数据）
        if (user.getId() != null) {
            strictInsertFill(metaObject, CREATOR, Long.class, user.getId());
        } else {
            log.warn("insertFill: 用户ID为空，跳过creator/deptId/updater字段填充");
        }
        //创建时间
        strictInsertFill(metaObject, CREATE_DATE, Date.class, date);

        //创建者所属部门
        if (user.getDeptId() != null) {
            strictInsertFill(metaObject, DEPT_ID, Long.class, user.getDeptId());
        }

        //更新者
        if (user.getId() != null) {
            strictInsertFill(metaObject, UPDATER, Long.class, user.getId());
        }
        //更新时间
        strictInsertFill(metaObject, UPDATE_DATE, Date.class, date);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = SecurityUser.getUserId();
        //更新者（用户ID为空时跳过填充）
        if (userId != null) {
            strictUpdateFill(metaObject, UPDATER, Long.class, userId);
        }
        //更新时间
        strictUpdateFill(metaObject, UPDATE_DATE, Date.class, new Date());
    }
}