package com.chinaweal.aiccs.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.user.entity.UserBase;
import com.chinaweal.youfool.framework.springboot.util.WebUtil;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import org.apache.ibatis.reflection.MetaObject;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 本地用户元数据信息处理
 *
 * @author lroyia
 * @since 2026/3/19 11:27
 **/
public class LocalUserMetaObjectHandler implements MetaObjectHandler {

    /**
     * 修改时间
     */
    private final String updateTime = "updateTime";
    /**
     * 插入时间
     */
    private final String createTime = "createTime";

    /**
     * 创建人
     */
    private final String createBy = "createBy";
    /**
     * 更新人
     */
    private final String updateBy = "updateBy";

    @Override
    public void insertFill(MetaObject metaObject) {
        String username = UserBase.currentUsername();
        username = username != null ? username : "";
        if (StringUtils.isBlank(username)) {
            username = getUsernameBySSO();
        }

        setFieldValByName(createTime, LocalDateTime.now(), metaObject);
        setFieldValByName(updateTime, LocalDateTime.now(), metaObject);
        setFieldValByName(createBy, username, metaObject);
        setFieldValByName(updateBy, username, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username = UserBase.currentUsername();
        username = username != null ? username : "";
        if (StringUtils.isBlank(username)) {
            username = getUsernameBySSO();
        }
        setFieldValByName(updateTime, LocalDateTime.now(), metaObject);
        setFieldValByName(updateBy, username, metaObject);
    }

    private String getUsernameBySSO() {
        try {
            HttpServletRequest request = WebUtil.getRequest();
            AICUser user = SSOUtil.getUser(request);
            return user == null ? StringUtils.EMPTY : user.getName();
        } catch (Exception e) {
            return StringUtils.EMPTY;
        }
    }
}