package com.yihu.wlyy.service.common.district;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.yihu.wlyy.entity.address.City;
import com.yihu.wlyy.entity.address.Province;
import com.yihu.wlyy.entity.address.Street;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.repository.address.CityDao;
import com.yihu.wlyy.repository.address.ProvinceDao;
import com.yihu.wlyy.repository.address.StreetDao;
import com.yihu.wlyy.repository.address.TownDao;
import com.yihu.wlyy.service.BaseService;

/**
 * 省市区三级业务处理类
 * @author George
 *
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class DistrictService extends BaseService {
	
	@Autowired
	private ProvinceDao provinceDao;
	@Autowired
	private CityDao cityDao;
	@Autowired
	private TownDao townDao;
	@Autowired
	private StreetDao streetDao;

	/**
	 * 查询省市区三级目录
	 * @param type 1一级目录，2二级目录，3三级目录，4街道目录
	 * @param code 目录标识
	 * @return
	 */
	public List<?> findByType(int type, String code) {
		switch (type) {
		case 1:
			return findProvince();
		case 2:
			return findCity(code);
		case 3:
			return findTown(code);
		case 4:
			return findStreet(code);
		}
		return null;
	}

	/**
	 * 查询所有的省份信息
	 * @return
	 */
	public List<Province> findProvince() {
		List<Province> list = new ArrayList<Province>();
		Iterable<Province> iterable = provinceDao.findAll(new Sort(Direction.ASC, "id"));
		if (iterable != null) {
			Iterator<Province> it = iterable.iterator();
			while (it != null && it.hasNext()) {
				list.add(it.next());
			}
		}
		return list;
	}

	/**
	 * 查询省份下的城市信息
	 * @param province 省编码
	 * @return
	 */
	public List<City> findCity(String province) {
		List<City> list = new ArrayList<City>();
		Iterable<City> iterable = cityDao.findByProvince(province);
		if (iterable != null) {
			Iterator<City> it = iterable.iterator();
			while (it != null && it.hasNext()) {
				list.add(it.next());
			}
		}
		return list;
	}

	/**
	 * 查询城市下的区县信息
	 * @param city 城市编码
	 * @return 
	 */
	public List<Town> findTown(String city) {
		List<Town> list = new ArrayList<Town>();
		Iterable<Town> iterable = townDao.findByCity(city);
		if (iterable != null) {
			Iterator<Town> it = iterable.iterator();
			while (it != null && it.hasNext()) {
				list.add(it.next());
			}
		}
		return list;
	}
	
	/**
	 * 查询城市下的街道信息
	 * @param town 区县编码
	 * @return 
	 */
	public List<Street> findStreet(String town) {
		List<Street> list = new ArrayList<Street>();
		Iterable<Street> iterable = streetDao.findByTown(town);
		if (iterable != null) {
			Iterator<Street> it = iterable.iterator();
			while (it != null && it.hasNext()) {
				list.add(it.next());
			}
		}
		return list;
	}
}
