package cn.datax.common.mybatis.config;

import cn.datax.common.utils.SecurityUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

public class DataMetaObjectHandler implements MetaObjectHandler {

	@Override
	public void insertFill(MetaObject metaObject) {
		boolean bolCreateTime = metaObject.hasSetter("createTime");
		Object createdTime = getFieldValByName("createdTime", metaObject);
		if(bolCreateTime){
			if (null == createdTime) {
				this.setInsertFieldValByName("createTime", LocalDateTime.now(), metaObject);
			}
		}

		boolean bolUpdateTime = metaObject.hasSetter("updateTime");
		Object updateTime = getFieldValByName("updateTime", metaObject);
		if(bolUpdateTime){
			if (null == updateTime) {
				this.setInsertFieldValByName("updateTime", LocalDateTime.now(), metaObject);
			}
		}

		boolean bolStatus = metaObject.hasSetter("status");
		Object status = getFieldValByName("status", metaObject);
		if(bolStatus){
			if (null == status) {
				this.setInsertFieldValByName("status", 1, metaObject);
			}
		}

		String userId = getUserId();
		if(StrUtil.isNotBlank(userId)){
			boolean bolCreateBy = metaObject.hasSetter("createBy");
			Object createBy = getFieldValByName("createBy", metaObject);
			if(bolCreateBy) {
				if (null == createBy) {
					this.setInsertFieldValByName("createBy", userId, metaObject);
				}
			}

			boolean bolUpdateBy = metaObject.hasSetter("updateBy");
			Object updateBy = getFieldValByName("updateBy", metaObject);
			if(bolUpdateBy) {
				if (null == updateBy) {
					this.setInsertFieldValByName("updateBy", userId, metaObject);
				}
			}
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		boolean bolUpdateTime = metaObject.hasSetter("updateTime");
		Object updateTime = getFieldValByName("updateTime", metaObject);
		if(bolUpdateTime){
			if (null == updateTime) {
				this.setUpdateFieldValByName("updateTime", LocalDateTime.now(), metaObject);
			}
		}

		String userId = getUserId();
		if(StrUtil.isNotBlank(userId)){
			boolean bolUpdateBy = metaObject.hasSetter("updateBy");
			Object updateBy = getFieldValByName("updateBy", metaObject);
			if(bolUpdateBy) {
				if (null == updateBy) {
					this.setUpdateFieldValByName("updateBy", userId, metaObject);
				}
			}
		}
	}

	private String getUserId() {
		String userId = SecurityUtil.getUserId();
		return userId;
	}
}
