package com.hikvision.building.cloud.neptune.community.biz.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hikvision.building.cloud.neptune.community.biz.Utils.FileUtils;
import com.hikvision.building.cloud.neptune.community.biz.Utils.JSONUtil;
import com.hikvision.building.cloud.neptune.community.biz.constant.Constant;
import com.hikvision.building.cloud.neptune.community.biz.vo.Province;
/**
*
* @author xujian18
* @version 2017年11月13日下午17:47
* @since 2017年11月13日
*/
@Service
public class ProvinceCityService {
@Autowired
private StringRedisTemplate provinceTemplate;
final List<Province> provinces=parseProvince("province/provinces.json");
final List<Province> cities=parseProvince("province/cities.json");
final List<Province> areas=parseProvince("province/areas.json");
public List<Province> findProvinceCityByParentId(String parentId) {
List<Province> all=new ArrayList<>();
List<Province> news=new ArrayList<>();
//缓存没有
String j = provinceTemplate.opsForValue().get(Constant.PROVINCE_CITY_AREA );
if(StringUtils.isBlank(j)){
all.addAll(provinces);
all.addAll(cities);
all.addAll(areas);
if(StringUtils.isBlank(parentId)){
return provinces;
}else{
for(Province p:all){
if(StringUtils.isNotBlank(p.getParent_code())){
if(p.getParent_code().equals(parentId)){
news.add(p);
}
}
}
String json = JSONUtil.toJson(all);
provinceTemplate.opsForValue().set(Constant.PROVINCE_CITY_AREA , json ,1, TimeUnit.DAYS);
return news;
}
}else{
//缓存有
TypeReference<List<Province>> typeReference = new TypeReference<List<Province>>(){};
List<Province> collection = JSONUtil.toCollection(j, typeReference);
for(Province p:collection){
if(StringUtils.isNotBlank(p.getParent_code())){
if(p.getParent_code().equals(parentId)){
news.add(p);
}
}else{
all.add(p);
}
}
if(StringUtils.isBlank(parentId)){
return all;
}else{
return news;
}
}
}
private List<Province> parseProvince(String area) {
String JsonContext = null;
try {
if(System.getProperty("os.name")!=null && System.getProperty("os.name").contains("Windows")){
area = this.getClass().getClassLoader().getResource(area).getPath();
}else{
area = "/neptune-community/" + area;
}
JsonContext = new FileUtils().ReadFile(area);
} catch (IOException e) {
throw new RuntimeException(e);
}
TypeReference<List<Province>> typeReference = new TypeReference<List<Province>>(){};
List<Province> collection = JSONUtil.toCollection(JsonContext,typeReference );
return collection;
}
public static void main(String[] args) {
ProvinceCityService sss = new ProvinceCityService();
System.out.println(sss.areas.size());
System.out.println(sss.cities.size());
System.out.println(sss.provinces.size());
}
}