package com.fs.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.fs.common.core.domain.BaseEntity;
import com.fs.common.core.domain.entity.SysUser;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MP注入处理器
 *
 * @author hh
 * @date 2021/4/25
 */
@Slf4j
public class InjectionMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject object) {
        try {
            if (object != null && object.getOriginalObject() instanceof BaseEntity) {
                BaseEntity entity = (BaseEntity) object.getOriginalObject();
                try {
                    SysUser user = SecurityUtils.getLoginUser().getUser();
                    entity.setCreateBy(user.getUserId().toString());
                    entity.setUpdateBy(user.getUserId().toString());
                }catch (Exception ignored){

                }
                entity.setCreateTime(new Date());
                entity.setUpdateTime(new Date());
            }
        } catch (Exception e) {
            throw new BaseException("新增自动注入异常 => " + e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject object) {
        try {
            if (object != null && object.getOriginalObject() instanceof BaseEntity) {
                BaseEntity entity = (BaseEntity) object.getOriginalObject();
                try {
                    SysUser user = SecurityUtils.getLoginUser().getUser();
                    entity.setUpdateBy(user.getUserId().toString());
                }catch (Exception ignored){

                }
                entity.setUpdateTime(new Date());
            }
        } catch (Exception e) {
            throw new BaseException("修改自动注入异常 => " + e.getMessage());
        }
    }

}
