package com.tax.user.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.tax.user.model.SysRule;
import com.yxcheng.token.common.cache.RedisService;
import com.yxcheng.token.common.model.RuleModel;
import com.yxcheng.token.constants.RedisContants;
import com.yxcheng.token.utils.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @ProjectName: tax-sys
 * @Package: com.tax.user.utils
 * @ClassName: RuleUtils
 * @Author: ddx
 * @Description: ${description}
 * @Date: 2020-09-03 17:52
 * @Version: 1.0
 */
public class RuleUtils {

    protected static Logger logger = LoggerFactory.getLogger(RuleUtils.class);

    private static RedisService redisService = SpringUtil.getBean(RedisService.class);

    public static List<SysRule> getRuleList(String userName) {
        List<SysRule> ruleList = Lists.newArrayList();
        if(redisService.exists(RedisContants.getCheckRulesByUser(userName))) {
            String ruleListStr = redisService.get(RedisContants.getCheckRulesByUser(userName));
            ruleList = JSON.parseArray(ruleListStr, SysRule.class);
        }
        return ruleList;
    }

    public static boolean checkFunction(String userName, String functionCode) {
        boolean isHaveFunction = false;
        if(redisService.exists(RedisContants.CHECK_FUNCTION + userName + RedisContants.DELIMITER + functionCode)) {
            isHaveFunction = true;
        }
        return isHaveFunction;
    }

    public static boolean checkFunctionTaxno(RuleModel model) {
        boolean isHaveFunctionTaxno = false;
        if(redisService.exists(RedisContants.getCheckTaxnosByUser(model.getUserName(), model.getFunctionCode(), model.getTaxno()))) {
            isHaveFunctionTaxno = true;
        }
        return isHaveFunctionTaxno;
    }


    public static boolean checkIps(RuleModel model) {
        boolean isHaveFunctionIps = false;
        if(redisService.exists(RedisContants.CHECK_RULE_IP + model.getUserName())) {
            List<String> ips = JSON.parseArray(redisService.get(RedisContants.CHECK_RULE_IP + model.getUserName()), String.class);
            if(ips.contains("*") || ips.contains(model.getIpAddr())) {
                isHaveFunctionIps = true;
            }
        }
        return isHaveFunctionIps;
    }
}
