package com.yeejoin.amos.boot.module.jyjc.biz.typeHandler;

import com.yeejoin.amos.boot.biz.common.typeHandler.TypeHandler;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

import static com.yeejoin.amos.boot.module.common.api.constant.TZSCommonConstant.*;

/**
 * 行政区划处理器
 */
@Component
@RequiredArgsConstructor
public class RegionCodeTypeHandler implements TypeHandler<String> {

    private final RedisUtils redisUtils;
    private final Map<String, String> CODE_NAME_MAP = new ConcurrentHashMap<>();

    @Override
    public String handle(String regionCode) {
        return StringUtils.isNotBlank(regionCode) ? CODE_NAME_MAP.computeIfAbsent(regionCode, (k) -> {
            List<LinkedHashMap> list1 = (List<LinkedHashMap>) redisUtils.get(PROVINCE);
            List<LinkedHashMap> list2 = (List<LinkedHashMap>) redisUtils.get(CITY);
            List<LinkedHashMap> list3 = (List<LinkedHashMap>) redisUtils.get(REGION);
            List<LinkedHashMap> list4 = (List<LinkedHashMap>) redisUtils.get(STREET);
            Optional<LinkedHashMap> op = Stream.of(list1, list2, list3, list4).flatMap(Collection::stream).filter(item -> String.valueOf(item.get("regionCode")).trim().equals(regionCode)).findFirst();
            return op.map(linkedHashMap -> linkedHashMap.get("regionName").toString()).orElse("");
        }) : "";
    }
}
