package com.tofly.common.oauth.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.auth.ToflyUser;
import com.tofly.common.oauth.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * @author Administrator
 * @date 2019/10/14  9:10
 * 增加handler，在新增和插入操作时，自动加入创建者，创建时间，修改时间等
 */
@Component
public class MybatisPlusHandler implements MetaObjectHandler {

    /**
     * 当新增时
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {


        ToflyUser toflyUser= SecurityUtils.getUser();
        this.setFieldValByName(CommonConstants.createTimeField, DateUtil.getCurrentTime(), metaObject);
        this.setFieldValByName(CommonConstants.creatLastTimeField, DateUtil.getCurrentTime(), metaObject);
        this.setFieldValByName(CommonConstants.updateTimeField, DateUtil.getCurrentTime(), metaObject);
        this.setFieldValByName(CommonConstants.changeDateField, DateUtil.getCurrentTime(), metaObject);
        this.setFieldValByName(CommonConstants.createDateField, DateUtil.getCurrentTime(), metaObject);
        this.setFieldValByName(CommonConstants.CREATEDATE, DateUtil.getCurrentTime(), metaObject);
        if(toflyUser!=null){
            this.setFieldValByName(CommonConstants.createUserIdField, toflyUser.getUserid(), metaObject);
            this.setFieldValByName(CommonConstants.CREATORID, toflyUser.getUserid(), metaObject);
            if(metaObject.hasGetter(CommonConstants.UserIdField) && metaObject.getValue(CommonConstants.UserIdField)==null){
                this.setFieldValByName(CommonConstants.UserIdField, toflyUser.getUserid(), metaObject);
            }
            this.setFieldValByName(CommonConstants.updateUserIdField, toflyUser.getUserid(), metaObject);
            this.setFieldValByName(CommonConstants.changeUserIdField, toflyUser.getUserid(), metaObject);
        }
    }

    /**
     * 当修改时
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        ToflyUser toflyUser= SecurityUtils.getUser();
        this.setFieldValByName(CommonConstants.updateTimeField, DateUtil.getCurrentTime(), metaObject);
        this.setFieldValByName(CommonConstants.updateLastTimeField, DateUtil.getCurrentTime(), metaObject);
        this.setFieldValByName(CommonConstants.changeDateField, DateUtil.getCurrentTime(), metaObject);
        if(toflyUser!=null){
            this.setFieldValByName(CommonConstants.updateUserIdField, toflyUser.getUserid(), metaObject);
            this.setFieldValByName(CommonConstants.changeUserIdField, toflyUser.getUserid(), metaObject);
        }

    }
}
