package com.yeejoin.amos.boot.module.jg.biz.edit.typeHandler;

import com.yeejoin.amos.boot.biz.common.typeHandler.TypeHandler;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.CommonServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

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

/**
 * 行政区划处理器
 */
@Component("regionCodeTypeHandler")
@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 regionCode != null ? CODE_NAME_MAP.computeIfAbsent(regionCode, (k) -> {
            List<LinkedHashMap> list1 = (List<LinkedHashMap>) redisUtils.get(CommonServiceImpl.PROVINCE);
            List<LinkedHashMap> list2 = (List<LinkedHashMap>) redisUtils.get(CommonServiceImpl.CITY);
            List<LinkedHashMap> list3 = (List<LinkedHashMap>) redisUtils.get(CommonServiceImpl.REGION);
            List<LinkedHashMap> list4 = (List<LinkedHashMap>) redisUtils.get(CommonServiceImpl.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(null);
        }) : null;
    }
}
