package com.tzy.common.utils;

import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Data
@ToString
public class AddressResolutionUtil {
    public static String regex = "(?<province>[^省]+省|.+自治区|香港|澳门|[^市]+市)?(?<city>[^盟]+盟|.+[^行政区]+行政区|.+[^自治州]+自治州|[^特别行政区]+特别行政区|[^市]+市|.*?地区|.*?行政单位|.+盟|市辖区|[^县]+县|.+香港岛|.*?半岛|.*?岛)(?<county>[^县]+县|[^市]+市|[^镇]+镇|[^区]+区|[^乡]+乡|.+旗|.+场|.+海域|.*?半岛|.*?岛)?(?<address>.*)";
    public static String province_regex = "(?<province>[^省]+省|.+自治区|香港|澳门|[^市]+市)";
    public String province=null,city=null,county=null,detailAddress=null;
    /**
     * 解析地址
     * @author lin
     * @param address
     * @return
     */
    public static AddressResolutionUtil addressResolution(String address){
        AddressResolutionUtil addressResolutionUtil = new AddressResolutionUtil();
        if(StringUtils.isNotEmpty(address)){
            address = BeanUtil.checkChar(BeanUtil.regSpecial, address);
            Matcher m= Pattern.compile(regex).matcher(address);
            List<Map<String,String>> table=new ArrayList<Map<String,String>>();
            Map<String,String> row=null;
            while(m.find()){
                row=new LinkedHashMap<String,String>();
                addressResolutionUtil.province=m.group("province");
                row.put("province", addressResolutionUtil.province==null?"":addressResolutionUtil.province.trim());
                addressResolutionUtil.city=m.group("city");
                row.put("city", addressResolutionUtil.city==null?"":addressResolutionUtil.city.trim());
                addressResolutionUtil.county=m.group("county");
                row.put("county", addressResolutionUtil.county==null?"":addressResolutionUtil.county.trim());
                addressResolutionUtil.detailAddress=m.group("address");
                row.put("address", addressResolutionUtil.detailAddress==null?"":addressResolutionUtil.detailAddress.trim());
                table.add(row);
            }
        }
        return addressResolutionUtil;
    }
    /**
     * 解析地址
     * @author lin
     * @param province
     * @return
     */
    public static String provinceResolution(String province){
        if(StringUtils.isNotEmpty(province)){
            Matcher m= Pattern.compile(province_regex).matcher(province);
            while(m.find()){
                province=m.group("province");
            }
        }
        return province
                .replaceAll("省","")
                .replaceAll("市","")
                .replaceAll("自治区","")
                ;
    }

    private static List<String> noAuthProvinces = Arrays.asList(new String[]{"香港","澳门","台湾","澳門","台灣"});

    public static boolean checkProvinceInNoAuth(String province){
        if(StringUtils.isEmpty(province)){
            return true;
        }
        return noAuthProvinces.contains(province.trim());
    }

}
