package com.ruoyi.framework.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class Global {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public String reg_head = "HBAPP://";
    public String reg_split = "/";
    public String cmd_reg = "REG";        //1 设备软件 设备信息 => 生成 注册二维码(REG)
    public String cmd_active = "ACTIVE";     //2 小程序扫码 点注册 => 生成 激活二维码(ACTIVE)
    public String cmd_dev = "DEV";        //3 小程序扫码 点激活 => 生成 设备二维码(DEV) => 打印出来 贴上机器上
    public String c_device_typpe = "device_type";

    private RedisCache redisCache = new RedisCache();

    @Autowired
    public void setRedisCache(RedisCache aRedisCache) {
        redisCache = aRedisCache;
    }

    @Autowired
    private ISysDictDataService sysDictService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private TokenService tokenService;

    //获取多语言后缀的
    /**
     * 根据用户名获取用户语言
     * @param userName
     * @return 返回空字符串或_en
     */
    public String getLanguage(String userName) {
        try {
            SysUser sysUser = userService.selectUserByUserName(userName);
            if (sysUser != null) {
                String langStr = sysUser.getLanguage();
                if (StringUtils.isNotNull(langStr) && StringUtils.isNotEmpty(langStr) && (langStr.equals("zh") == false)) {
                    return "_" + langStr;
                }
            }// end if
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * 获取当前用户语言，适用于已登录时获取语言
     * @return 返回空字符串或en
     */
    public String getCurrentLanguage() {
        try {
            String userName = SecurityUtils.getUsername();
            Long userId = SecurityUtils.getUserId();
            SysUser sysUser = userService.selectUserById(userId);
            if (sysUser != null) {
                String langStr = sysUser.getLanguage();
                if (StringUtils.isNotNull(langStr) && StringUtils.isNotEmpty(langStr) && (langStr.equals("zh") == false)) {
                    return langStr;
                }
            }// end if
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取当前环境语言，包括请求头及用户信息中的语言，可适用于未登录时获取语言
     * @param request
     * @return 返回zh或en
     */
    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;
    }

    public List<String> getDictDataValueList(String dictType) {
        List<String> dataList = new ArrayList<>();
        //查所有语言字典
        SysDictData queryBean = new SysDictData();
        queryBean.setDictType(dictType);
        queryBean.setStatus("0");
        List<SysDictData> dictDataList = dictDataService.selectDictDataList(queryBean);
        for (SysDictData sysDictData : dictDataList) {
            dataList.add(sysDictData.getDictValue());
        }
        return dataList;
    }

    // 过滤特殊字符
    public String repSpace(String str) {
        //只允许字母和数字
//        String regEx ="[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}';',\\[\\].<>?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String newStr = m.replaceAll("").trim();
        newStr = newStr.replaceAll("\u0000", "");
        newStr = newStr.replaceAll("\u0001", "");
        newStr = newStr.replaceAll("\u0002", "");
        newStr = newStr.replaceAll("\u0003", "");
        newStr = newStr.replaceAll("\u0004", "");
        newStr = newStr.replaceAll("\u0005", "");
        newStr = newStr.replaceAll("\u0006", "");
        newStr = newStr.replaceAll("\u0007", "");
        newStr = newStr.replaceAll("\u0008", "");
        newStr = newStr.replaceAll("\u0009", "");
        newStr = newStr.replaceAll("\u00a0", "");
        return newStr;
    }
}
