package com.tmerclub.cloud.common.security.filter.dubbo;

import com.alibaba.fastjson2.JSON;
import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.platform.vo.UriPermissionVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.i18n.LanguageEnum;
import com.tmerclub.cloud.common.security.AuthTokenContext;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.security.PmsContext;
import io.seata.core.constants.DubboConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;
import java.util.Objects;


/**
 * @author lanhai
 */
@Activate(group = DubboConstants.PROVIDER)
public class UserInfoProviderFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoConsumerFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) {
        UidInfoBO uidInfoBO = (UidInfoBO) invocation.getObjectAttachment(Constant.DUBBO_USER_KEY);
        Object lang = invocation.getObjectAttachment(Constant.DUBBO_LANG_KEY);
        Object token = invocation.getObjectAttachment(Constant.DUBBO_TOKEN_KEY);
        Object premsObject = invocation.getObjectAttachment(Constant.DUBBO_PREMS_KEY);
        if (Objects.nonNull(lang)) {
            // 设置国际化语言
            Locale locale = new Locale(LanguageEnum.valueOf(Integer.parseInt(lang.toString())).getLanguage());
            LocaleContextHolder.setLocale(locale);
        }
        if (premsObject != null) {
            PmsContext.set(JSON.parseArray(premsObject.toString(), UriPermissionVO.class));
        }
        if (token != null) {
            AuthTokenContext.setToken(token.toString());
        }
        if (uidInfoBO != null) {
            AuthUserContext.set(uidInfoBO);
        }
        Result invoke = invoker.invoke(invocation);
        return invoke;
    }
}
