package com.yd.csf.service.config;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.yd.auth.core.dto.AuthUserDto;
import com.yd.auth.core.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

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

@Slf4j
@Configuration
public class CsfMybatisPlusConfig {

    /**
     * 分页插件配置（必须）
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 使用正确的枚举值 DbType.MYSQL
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 自动填充字段配置（如创建人、更新人等）
     */
    /**
     * 自动填充字段配置（如创建人、更新人等）
     */
    @Bean
    @Primary
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                AuthUserDto authUserDto = null;
                try {
                    authUserDto = SecurityUtil.getCurrentLoginUser();
                } catch (Exception e) {
                    log.info("获取Security上下文当前用户的登录信息失败，{}", e.getMessage());
                }
                log.info("metaObjectHandler insertFill 获取用户信息：{}", JSON.toJSONString(authUserDto));
                if (authUserDto != null) {
                    // 仅当字段为空时才填充
                    if (getFieldValByName("creatorId", metaObject) == null) {
                        this.strictInsertFill(metaObject, "creatorId", String.class, authUserDto.getUserBizId());
                    }
                    if (getFieldValByName("creatorName", metaObject) == null) {
                        this.strictInsertFill(metaObject, "creatorName", String.class, authUserDto.getRealName());
                    }
                    if (getFieldValByName("createTime", metaObject) == null) {
                        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
                    }
                    if (getFieldValByName("updaterId", metaObject) == null) {
                        this.strictInsertFill(metaObject, "updaterId", String.class, authUserDto.getUserBizId());
                    }
                    if (getFieldValByName("updaterName", metaObject) == null) {
                        this.strictInsertFill(metaObject, "updaterName", String.class, authUserDto.getRealName());
                    }
                    if (getFieldValByName("updateTime", metaObject) == null) {
                        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
                    }
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                AuthUserDto authUserDto = null;
                try {
                    authUserDto = SecurityUtil.getCurrentLoginUser();
                } catch (Exception e) {
                    log.info("获取Security上下文当前用户的登录信息失败，{}", e.getMessage());
                }
                log.info("metaObjectHandler updateFill 获取用户信息：{}", JSON.toJSONString(authUserDto));
                if (authUserDto != null) {
                    // 仅当字段为空时才填充
                    if (getFieldValByName("updaterId", metaObject) == null) {
                        this.strictUpdateFill(metaObject, "updaterId", String.class, authUserDto.getUserBizId());
                    }
                    if (getFieldValByName("updaterName", metaObject) == null) {
                        this.strictUpdateFill(metaObject, "updaterName", String.class, authUserDto.getRealName());
                    }
                    if (getFieldValByName("updateTime", metaObject) == null) {
                        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
                    }
                }
            }
        };
    }
}
