package com.jiayue.insu.incloud.config;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
/**
 * mybatis-plus 字段自动填充
 *
 * @author yh
 * @version 1.0
 * @since 2022/5/22 11:29
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        SaTokenInfo tokenInfo;
        try {
            //当执行定时任务时，无登录信息抛出异常
            tokenInfo = StpUtil.getTokenInfo();

        }catch (Exception e){
            tokenInfo = new SaTokenInfo();
            tokenInfo.setLoginId("quartz");
        }

        this.strictInsertFill(metaObject, "creator", String.class,  (String)tokenInfo.getLoginId()); // 起始版本 3.3.0(推荐使用)

        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SaTokenInfo tokenInfo;
        try {
            //当执行定时任务时，无登录信息抛出异常
            tokenInfo = StpUtil.getTokenInfo();

        }catch (Exception e){
            tokenInfo = new SaTokenInfo();
            tokenInfo.setLoginId("quartz");
        }

        this.setFieldValByName("lastModifier", tokenInfo.getLoginId(),metaObject);
        this.setFieldValByName("lastModifyTime",LocalDateTime.now(), metaObject);
    }
}