package com.bcxin.Infrastructures.validations;

import cn.hutool.core.util.IdcardUtil;
import com.bcxin.Infrastructures.enums.CredentialType;
import com.bcxin.Infrastructures.exceptions.ArgumentTenantException;
import com.bcxin.Infrastructures.models.CredentialModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class CredentialValidator implements ConstraintValidator<Credential, CredentialModel> {
    /**
     * 年: ((0[1-9])|(10|11|12))
     */
    private static final Pattern pattern = Pattern.compile("(^[1-9]\\d{5}(\\d{2}((0[1-9])|(10|11|12)))(([0-2][1-9])|10|20|30|31)\\d{3}$)|(^[1-9]\\d{5}((18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12)))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)");
    @Override
    public boolean isValid(CredentialModel value, ConstraintValidatorContext context) {

        return validate(value.getType(), value.getNumber());
    }

    public static int getAge(String idNumber) throws IllegalArgumentException {
        Matcher matcher = pattern.matcher(idNumber);
        if (!matcher.matches()) {
            throw new ArgumentTenantException(String.format("身份证(%s)格式不正确!", idNumber));
        }

        String yearMonth = null;
        for (int index = 0; index < matcher.groupCount(); index++) {
            if (index >= 1) {
                try {
                    yearMonth = matcher.group(index);
                    if (StringUtils.hasLength(yearMonth) && (yearMonth.length() == 4 || yearMonth.length() == 6)) {
                        break;
                    }
                } catch (Exception ex) {
                    log.error(String.format("获取身份证(%s)中年月无效", idNumber), ex);
                }
            }
        }

        if (!StringUtils.hasLength(yearMonth) || yearMonth.length() < 4) {
            throw new ArgumentTenantException(String.format("身份证(%s)格式不正确!", idNumber));
        }
        //获取年龄
        try {
            int age = IdcardUtil.getAgeByIdCard(idNumber);
            return age;
        } catch (Exception ex) {
            log.error(String.format("解析身份证(%s)中年龄无效", idNumber), ex);
        }

        throw new ArgumentTenantException(String.format("身份证(%s)格式不正确!", idNumber));
    }

    public static boolean validate(CredentialType credentialType,String number) {
        if (!StringUtils.hasLength(number)) {
            return true;
        }

        if (credentialType == CredentialType.IdCard) {
            Matcher matcher = pattern.matcher(number);

            return matcher.matches();
        }

        return true;
    }
}
