package com.cmeeting.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Component
public class MyBatisMetaHandler implements MetaObjectHandler {

    private final String CREATE_TIME = "createTime";
    private final String UPDATE_TIME = "updateTime";
//    private final String ID = "id";

    @Override
    public void insertFill(MetaObject metaObject) {
        // todo zhangks 没生效
        Date now = new Date();
//        boolean hasId = metaObject.hasSetter(ID);
        boolean hasCreateTime = metaObject.hasSetter(CREATE_TIME);
        boolean hasUpdateTime = metaObject.hasSetter(UPDATE_TIME);
//        if (hasId) {
//            Object id = getFieldValByName(ID, metaObject);
//            if (ObjectUtils.isEmpty(id)) {
//                long nextId = IdUtil.getSnowflake(1, 1).nextId();
//                strictInsertFill(metaObject, ID, String.class, String.valueOf(nextId));
//
//            }
//        }
        if (hasCreateTime) {
            Object createTime = getFieldValByName(CREATE_TIME, metaObject);
            if (ObjectUtils.isEmpty(createTime)) {
                strictInsertFill(metaObject, CREATE_TIME, Date.class, now);
            }
        }
        if (hasUpdateTime) {
            Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
            if (ObjectUtils.isEmpty(updateTime)) {
                strictInsertFill(metaObject, UPDATE_TIME, Date.class, now);
            }

        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date now = new Date();
        boolean hasUpdateTime = metaObject.hasSetter(UPDATE_TIME);
        if (hasUpdateTime) {
            setFieldValByName(UPDATE_TIME, now, metaObject);
        }
    }
}
