package cn.iocoder.yudao.framework.common.util.validation;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * 校验工具类
 *
 * @author 捷道源码
 */
public class ValidationUtils {

    private static final Pattern PATTERN_URL = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");

    private static final Pattern PATTERN_XML_NCNAME = Pattern.compile("[a-zA-Z_][\\-_.0-9_a-zA-Z$]*");

    public static boolean isMobile(String mobile) {
        if (StrUtil.length(mobile) > 11) {
            return false;
        }
        // TODO 芋艿，后面完善手机校验
        return true;
    }

    public static boolean isMobileCode(String mobileCode) {
        String[] mc = mobileCode.split(StrUtil.COLON);
        if (mc.length != 2) {
            return false;
        }
        String code = mc[0]; // 国家区号
        String mobile = mc[1]; // 手机号

        if (!mobile.matches("^[0-9]*$") || !code.matches("^[0-9]*$")){
            // 纯数字校验
            return false;
        }
        switch (code) {
            case "86":
                // 中国
                if (!mobile.matches("1[23456789]\\d{9}")
                        || StrUtil.length(mobile) != 11) {
                    return false;
                }
                break;
            case "225":
                // 科特迪瓦
                if (StrUtil.length(mobile) > 11) {
                    // 电话号码不能大于11位
                    return false;
                }
                break;
            default:
                if (mobile.startsWith("0") || StrUtil.length(mobile) > 11) {
                    // 电话号码开始值不能为0 且不能大于11位
                    return false;
                }
        }
        // TODO 芋艿，后面完善手机校验
        return true;
    }


    public static boolean isURL(String url) {
        return StringUtils.hasText(url)
                && PATTERN_URL.matcher(url).matches();
    }

    public static boolean isXmlNCName(String str) {
        return StringUtils.hasText(str)
                && PATTERN_XML_NCNAME.matcher(str).matches();
    }

    public static void validate(Validator validator, Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (CollUtil.isNotEmpty(constraintViolations)) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }

}
