/*
 * Copyright (c) 2018-2022 Caratacus, (caratacus@qq.com).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.sunxung.factoring.component.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sunxung.factoring.component.util.ThreadLocalUtil;
import com.sunxung.factoring.entity.sys.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * 通用填充类 适用于mybatis plus
 *
 * @author Caratacus
 */
@Component
public class CommonMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建者
     */
    private final String userCreate = "userCreate";

    /**
     * 修改者
     */
    private final String userModified = "userModified";

    /**
     * 修改时间
     */
    private final String gmtModified = "gmtModified";

    @Override
    public void insertFill(MetaObject metaObject) {
        User user = ThreadLocalUtil.getUser();
        if (user != null) {
            this.strictInsertFill(metaObject, userCreate, String.class, ThreadLocalUtil.getUser().getLoginName());
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        User user = ThreadLocalUtil.getUser();
        if (user != null) {
            this.strictUpdateFill(metaObject, userModified, String.class, ThreadLocalUtil.getUser().getLoginName());
        }
        this.strictUpdateFill(metaObject, gmtModified, Date.class, new Date());
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        // if (metaObject.getValue(fieldName) == null) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }
        //  }
        return this;
    }
}
