package com.changhu.support.mybatisplus.config;

import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.changhu.common.db.enums.DeleteFlag;
import com.changhu.common.utils.UserUtil;
import com.changhu.support.mybatisplus.pojo.entity.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * author: luozhun
 * desc: CustomMetaObjectHandler
 * createTime: 2023/12/1 17:16
 */
@Slf4j
@Configuration
public class CustomMetaObjectHandler implements MetaObjectHandler {

    private final String createBy = LambdaUtil.getFieldName(BaseEntity::getCreateBy);
    private final String updateBy = LambdaUtil.getFieldName(BaseEntity::getUpdateBy);
    private final String createTime = LambdaUtil.getFieldName(BaseEntity::getCreateTime);
    private final String updateTime = LambdaUtil.getFieldName(BaseEntity::getUpdateTime);
    private final String deleteFlag = LambdaUtil.getFieldName(BaseEntity::getDeleteFlag);

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId;
        try {
            userId = UserUtil.getUserId();
        } catch (Exception e) {
            log.warn("无用户数据状态下插入数据：{},原因:{}", metaObject.toString(), e.getMessage());
            userId = UserUtil.ERROR_USER_ID;
        }

        this.strictInsertFill(metaObject, createBy, Long.class, userId);
        this.strictInsertFill(metaObject, updateBy, Long.class, userId);

        LocalDateTime now = LocalDateTime.now();
        this.strictInsertFill(metaObject, createTime, LocalDateTime.class, now);
        this.strictInsertFill(metaObject, updateTime, LocalDateTime.class, now);
        this.strictInsertFill(metaObject, deleteFlag, Integer.class, DeleteFlag.FALSE.getValue());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId;
        try {
            userId = UserUtil.getUserId();
        } catch (Exception e) {
            log.warn("无用户数据状态下更新数据：{},原因:{}", metaObject.toString(), e.getMessage());
            userId = UserUtil.ERROR_USER_ID;
        }

        this.strictUpdateFill(metaObject, updateTime, LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, updateBy, Long.class, userId);
    }
}
