package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LanguageService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    public String getCurrentLanguage (HttpServletRequest request) {
        // 根据请求头获取语言类型，默认英文en(小程序调用时未传)
        String language = request.getHeader("Accept-Language");
        if (StringUtils.isNotEmpty(language)) {
            language = language.split(",")[0];
            if (language.contains("zh")) {
                language = "zh";
            } else if (language.contains("en")){
                language = "en";
            }
            // 后续增加语言往这里加判断
        } else {
            language = "en";
        }

        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            SysUser sysUser = userService.selectUserById(loginUser.getUserId());
            if (sysUser != null && StringUtils.isNotEmpty(sysUser.getLanguage())) {
                language = sysUser.getLanguage();
            }
        }

        return language;
    }

}
