package com.repair.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.repair.common.utils.AesUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中！
public class MyMetaObjectHandler implements MetaObjectHandler {
    //创建用户和更新用户填充0的时候则说明不是账号操作的

    // 插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        HttpServletRequest request = getHttpServletRequest();
        String user_id = request.getHeader("user_head") == null ? "0" : AesUtils.decrypt(request.getHeader("user_head"));
        log.info("start insert fill.....");
        // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("createUser", user_id , metaObject);
        this.setFieldValByName("updateUser", user_id , metaObject);
        this.setFieldValByName("deleted", 0 , metaObject);
    }

    // 更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        HttpServletRequest request = getHttpServletRequest();
        String user_id = request.getHeader("user_head") == null ? "0" : AesUtils.decrypt(request.getHeader("user_head"));
        log.info("start update fill.....");
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateUser", user_id, metaObject);
    }

    private HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }
}
