package com.fuint.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.fuint.common.dto.AccountInfo;
import com.fuint.common.util.AuthUserUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Objects;

/**
 * MybatisPlus配置
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
@Configuration
@MapperScan({"com.fuint.repository.**.mapper"})
public class MybatisPlusConfig implements MetaObjectHandler {

    /**
     * 分页插件
     *
     * @return PaginationInterceptor
     */
    @Bean
    @ConditionalOnMissingBean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 逻辑删除插件
     *
     * @return LogicSqlInjector
     */
    @Bean
    @ConditionalOnMissingBean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }

    /**
     * 乐观锁插件
     *
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * 插入拦截
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        AccountInfo accountInfo = AuthUserUtil.get();
        if (Objects.nonNull(accountInfo)) {
            this.setFieldValByName("createUserId", String.valueOf(accountInfo.getId()), metaObject);
            this.setFieldValByName("updateUserId", String.valueOf(accountInfo.getId()), metaObject);
        }

    }

    /**
     * 更新数据时拦截
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        AccountInfo accountInfo = AuthUserUtil.get();
        if (Objects.nonNull(accountInfo)) {
            this.setFieldValByName("updateUserId",  String.valueOf(accountInfo.getId()), metaObject);
        }
    }
}
