package com.yccrc.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yccrc.common.core.domain.model.LoginUser;
import com.yccrc.common.utils.SecurityUtils;

import lombok.extern.slf4j.Slf4j;

import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
@Slf4j
public class CustomMetaObjectHandler  implements MetaObjectHandler {
    public static final String COMMON_FIELD_CREATEDATE = "createTime";

    public static final String COMMON_FIELD_UPDATEDATE = "updateTime";
    public static final String COMMON_FIELD_CREATEBY = "createBy";
    public static final String COMMON_FIELD_UPDATEBY = "updateBy";

    @Override
    public void insertFill(MetaObject metaObject) {
    	LoginUser loginUser= null;
    	try {
    		loginUser= SecurityUtils.getLoginUser();
    	}catch(Exception e) {}
       
       if(loginUser!=null){
           setFieldValByName(COMMON_FIELD_CREATEBY, loginUser.getUsername(), metaObject);
       }
        Object fieldValue = getFieldValByName(COMMON_FIELD_CREATEDATE, metaObject);
        if (fieldValue == null) { //如果设置了就以设置的为准
            setFieldValByName(COMMON_FIELD_CREATEDATE, new Date(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
    	LoginUser loginUser= null;
    	try {
    		loginUser= SecurityUtils.getLoginUser();
    	}catch(Exception e) {}
    	
        if(loginUser!=null){
            setFieldValByName(COMMON_FIELD_UPDATEBY, loginUser.getUsername(), metaObject);
        }

        Object testType = getFieldValByName(COMMON_FIELD_UPDATEDATE, metaObject);
        if (testType == null) {
        	
            setFieldValByName(COMMON_FIELD_UPDATEDATE, new Date(), metaObject);
        }
    }
}
