package com.tykj.dev.device.user.cache;

import com.tykj.dev.device.user.subject.entity.Area;
import com.tykj.dev.device.user.subject.entity.AreaExhibition;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * AreaCache.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2020/9/22 at 5:33 下午
 */
@Data
public class AreaCache {

    private Map<String, Area> nameMap;

    private Map<Integer, Area> idMap;


    public AreaCache(List<Area> areaList) {
        nameMap = areaList.stream().collect(Collectors.toMap(Area::getName, Function.identity()));
        idMap = areaList.stream().collect(Collectors.toMap(Area::getId, Function.identity()));
    }

    public Area findFatherByName(String name) {
        Area area = nameMap.get(name);
        return idMap.get(area.getFatherId());
    }

    public Area findByName(String name) {
        return nameMap.get(name) == null ? new Area(0, "省直属", 9999, "9999", 0, "") : nameMap.get(name);
    }

    public Area findById(Integer id) {
        return idMap.get(id) == null ? new Area(0, "省直属", 9999, "9999", 0, "") : idMap.get(id);
    }
    public List<Area> findAll(){
        return new ArrayList<>(idMap.values());
    }



    public AreaCache refresh(List<Area> areaList) {
        nameMap = areaList.stream().collect(Collectors.toMap(Area::getName, Function.identity()));
        idMap = areaList.stream().collect(Collectors.toMap(Area::getId, Function.identity()));
        return this;
    }
}
