package com.zsc.edu.gateway.framework.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zsc.edu.gateway.framework.security.SecurityUtil;
import com.zsc.edu.gateway.framework.security.UserDetailsImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * @author Yao
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
        if (userInfo.getUsername() == null) {
            userInfo.setUsername("system");
        }
        if (userInfo.getDeptId() == null) {
            userInfo.setDeptId(2L);
        }
        if (userInfo.getCreateId() == null) {
            userInfo.setCreateId(1L);
        }
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createBy", String.class, userInfo.getUsername());
        this.strictInsertFill(metaObject, "deptId", Long.class, userInfo.getDeptId());
        this.strictInsertFill(metaObject, "createId", Long.class, userInfo.getCreateId());

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
        if (userInfo.getUsername() == null) {
            userInfo.setUsername("system");
        }
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        this.strictUpdateFill(metaObject, "updateBy", userInfo::getUsername, String.class);

    }

}