package cn.com.ty.lift.enterprise.config;

import cn.com.ty.lift.common.constants.ApiConstants;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author bieao
 * @date 2019/12/23
 * @description 公共字段配置
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    private static final String CREATOR_ID = "creatorId";
    private static final String CREATE_DATE = "createDate";
    private static final String UPDATE_ID = "updateId";
    private static final String UPDATE_DATE = "updateDate";

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        //获取当前登陆用户id
        Long userId = getUserId();

        setFieldValByName(CREATOR_ID, userId, metaObject);
        setFieldValByName(CREATE_DATE, now, metaObject);
        setFieldValByName(UPDATE_ID, userId, metaObject);
        setFieldValByName(UPDATE_DATE, now, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //获取当前登陆用户id
        Long userId = getUserId();
        LocalDateTime now = LocalDateTime.now();
        setFieldValByName(UPDATE_ID, userId, metaObject);
        setFieldValByName(UPDATE_DATE, now, metaObject);
    }

    private long getUserId() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(servletRequestAttributes)) {
            return 10000L;
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Object userId = request.getHeader(ApiConstants.CURRENT_USER_ID);
        if (ObjectUtil.isNotEmpty(userId)) {
            return Long.parseLong(Objects.toString(userId));
        }
        return 10000L;
    }
}
