package com.ruoyi.platform.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充公共字段
 */
@Slf4j
@Component
public class BaseMetaObjectHandler implements MetaObjectHandler {


    private static final String ID = "id";

    /**
     * 创建人员
     */
    private static final String CREATE_BY = "createBy";

    /**
     * 创建时间
     */
    private static final String CREATE_TIME = "createTime";


    /**
     * 更新人员
     */
    private static final String UPDATE_BY = "updateBy";

    /**
     * 更新时间
     */
    private static final String UPDATE_TIME = "updateTime";

    /**
     * 删除标记
     */
    private static final String STATE = "state";



    /**
     * 新增
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        setFieldValByName(CREATE_BY, loginUser.getUsername(), metaObject);
        // 创建时间
        setFieldValByName(CREATE_TIME, new Date(), metaObject);
        setFieldValByName(UPDATE_BY, loginUser.getUsername(), metaObject);
        setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        // 删除标记
        setFieldValByName(STATE, 1, metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        // 更新用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        setFieldValByName(UPDATE_BY, loginUser.getUsername(), metaObject);
        setFieldValByName(UPDATE_TIME, new Date(), metaObject);
    }
}

