package com.project.zcustom.config;

import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.project.zcustom.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * MybatisPlus 字段注入
 *
 * @author Tellsea
 * @date 2022/9/1
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATE_BY = "createBy";
    public static final String CREATE_TIME = "createTime";
    public static final String UPDATE_BY = "updateBy";
    public static final String UPDATE_TIME = "updateTime";
    public static final String DELETED = "delFlag";

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
//            this.setFieldValByName(CREATE_BY, SecurityUtils.getLoginUserAnonymous(),metaObject);
            this.setFieldValByName(CREATE_TIME,formatDate(metaObject.getSetterType(CREATE_TIME)),metaObject);
//            this.setFieldValByName(UPDATE_BY, SecurityUtils.getLoginUserAnonymous(),metaObject);
            this.setFieldValByName(UPDATE_TIME,formatDate(metaObject.getSetterType(UPDATE_TIME)),metaObject);
            this.setFieldValByName(DELETED, "0",metaObject);
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
//            this.setFieldValByName(UPDATE_BY, SecurityUtils.getLoginUserAnonymous(),metaObject);
            this.setFieldValByName(UPDATE_TIME,formatDate(metaObject.getSetterType(UPDATE_TIME)),metaObject);
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    /**
     * 处理特殊日期
     * @param setterType 参数类型
     * @return 日期类型
     */
    private Object formatDate(Class<?> setterType){
        if (Date.class.equals(setterType)){
            return new Date();
        } else if (LocalDateTime.class.equals(setterType)) {
            return LocalDateTime.now();
        } else if (Long.class.equals(setterType)) {
            return System.currentTimeMillis();
        }
        return null;
    }

}
