package com.ruoyi.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.List;
public class FindUtil {
    private static final String PHONE_REGEX = "1[3-9]\\d{9}";
    private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);
    private static final Pattern ADDR_PATTERN = Pattern.compile("^(?=.*省)(?=.*市)(?=.*,).*$");
    // 匹配省市开头的正则表达式
    private static final Pattern ADDRESS_START_PATTERN =
            Pattern.compile("^([^,]+省|[^,]+自治区|[^,]+直辖市|[^,]+市),[^,]+市(?:,|$)");
    public static int findFirstPhoneNumberIndex(String[] array) {
        for (int i = 0; i < array.length; i++) {
            if (PHONE_PATTERN.matcher(array[i]).matches()) {
                return i;
            }
        }
        return -1; // 未找到
    }
    public static int findFirstAddrIndex(String[] array) {
        for (int i = 0; i < array.length; i++) {
            if (isPDFAddr(array[i])) {
                return i;
            }
        }
        return -1; // 未找到
    }
    public static boolean isPDFAddr(String addr) {
        return ADDR_PATTERN.matcher(addr).matches();
    }


    public static List<String> extractAddresses(String[] fragments) {
        List<String> addresses = new ArrayList<>();
        StringBuilder currentAddress = null;

        for (String fragment : fragments) {
            Matcher matcher = ADDRESS_START_PATTERN.matcher(fragment);
            if (matcher.find()) {
                // 发现新地址开始
                if (currentAddress != null) {
                    addresses.add(currentAddress.toString());
                }
                currentAddress = new StringBuilder(fragment);
            }
            else if (currentAddress != null) {
                // 继续拼接当前地址
                currentAddress.append(fragment);
            }
        }

        // 添加最后一个地址
        if (currentAddress != null) {
            addresses.add(currentAddress.toString());
        }

        return addresses;
    }
}
