package com.sundot.airport.exam.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sundot.airport.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

/**
 * <b>功能名：</b>MyMetaObjectHandler<br>
 * <b>说明：</b> 生成公共字段填充 <br>
 * <b>著作权：</b> Copyright (C) 2020 HUIFANEDU CORPORATION<br>
 * <b>修改履历：</b>
 *
 * @author 2020-10-12 huifan
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");

        // 填充创建人ID
        if (ObjectUtil.isEmpty(metaObject.getValue(getCreateUidFieldName()))) {
            setFieldValByName(getCreateUidFieldName(), getUserUniqueId(), metaObject);
        }

        // 填充修改人ID
        if (ObjectUtil.isEmpty(metaObject.getValue(getUpdateUidFieldName()))) {
            setFieldValByName(getUpdateUidFieldName(), getUserUniqueId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");

        try {
            //MetaObject etMeta = SystemMetaObject.forObject(metaObject.getValue("et"));
            // 填充修改人ID
            if (ObjectUtil.isEmpty(metaObject.getValue(getUpdateUidFieldName()))) {
                setFieldValByName(getUpdateUidFieldName(), getUserUniqueId(), metaObject);
            }
        } catch (Exception e) {
            log.error("修改时 updateUid字段补充失败。。。", e);
        }
    }

    /**
     * 获取创建用户字段的名称（非数据库中字段名称）
     */
    private String getCreateUidFieldName() {
        return "createUid";
    }

    /**
     * 获取更新用户字段的名称（非数据库中字段名称）
     */
    private String getUpdateUidFieldName() {
        return "updateUid";
    }

    /**
     * 获取用户唯一id（注意默认获取的用户唯一id为空）
     */
    private String getUserUniqueId() {
        try {
            //todo 通过新的方式获取当前用户
            return String.valueOf(SecurityUtils.getUserId());
        } catch (Exception e) {
            return "";
        }
    }

}
