package cn.datax.common.mybatis.config;

import cn.datax.common.core.DataConstant;
import cn.datax.common.utils.SecurityUtil;
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) {
		this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
		this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
		this.strictInsertFill(metaObject, "status", String.class, DataConstant.EnableState.ENABLE.getKey());
		String userId = getUserId();
		this.strictInsertFill(metaObject, "createBy", String.class, userId);
		this.strictInsertFill(metaObject, "updateBy", String.class, userId);

		boolean bolCreateDept = metaObject.hasSetter("createDept");
		if(bolCreateDept){
			this.strictInsertFill(metaObject, "createDept", String.class, getUserDeptId());
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
		String userId = getUserId();
		this.strictUpdateFill(metaObject, "updateBy", String.class, userId);
	}

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

	private String getUserDeptId() {
		String deptId = SecurityUtil.getUserDeptId();
		return deptId;
	}
}
