package org.cs.mgr.sys.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.cs.core.service.impl.BaseService;
import org.cs.mgr.sys.dao.IAreaDao;
import org.cs.mgr.sys.model.Area;
import org.cs.mgr.sys.service.IAreaService;
import org.cs.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @ClassName: AreaService
 * @Description: TODO
 * @author: cosco gt.fan@msn.cn
 * @date: 2017年3月31日 下午6:08:10
 */
@Service("areaService")
public class AreaService extends BaseService<Area> implements IAreaService {

	@Autowired
	private IAreaDao areaDao;

	@Override
	public List<Area> getProvice() {
		// TODO Auto-generated method stub
		return this.areaDao.getProvice();
	}

	@Override
	public List<Area> getCityOrCountry(String code) {
		// TODO Auto-generated method stub
		if (StringUtil.isBlank(code)) {
			return null;
		} else {
			return this.areaDao.getCityOrCountry(code);
		}
	}

	@Override
	public List<Area> getCityOrCountryByName(String name) {
		// TODO Auto-generated method stub
		if (StringUtil.isBlank(name)) {
			return null;
		} else {
			return this.areaDao.getCityOrCountryByName(name);
		}
	}

	@Override
	public JSONArray getPCCJson() {
		//省
		List<Area> area0list = this.findAll(null);
		Collections.sort(area0list, new Comparator<Area>() {
			@Override
			public int compare(Area o1, Area o2) {
				return o1.getCode().compareTo(o2.getCode());
			}
		});
		List<Area> area1list = new ArrayList<Area>();
		area1list.addAll(area0list);
		List<Area> area2list = new ArrayList<Area>();
		area2list.addAll(area0list);
		JSONArray allarea = new JSONArray();
		JSONObject provice = null;
		for (Area area : area0list) {
			if(null != area && area.getPid() == 0)
			{
				String key = area.getCode();
				provice = new JSONObject();
				provice.put("code", key);
				provice.put("name", area.getName());
				provice.put("nodes", "");
				//市
				JSONArray cities = new JSONArray();
				JSONObject city = null;
				for (Area ciarea : area1list) 
				{
					if(ciarea.getPid() == area.getId())
					{
						String key2 = ciarea.getCode();
						city = new JSONObject();
						city.put("code", key2);
						city.put("name", ciarea.getName());
						city.put("nodes", "");
						JSONArray countries = new JSONArray();
						JSONObject country = null;
						//区
						for (Area coarea : area2list) 
						{
							if(coarea.getPid() == ciarea.getId())
							{
								String key3 = coarea.getCode();
								country = new JSONObject();
								country.put("code", key3);
								country.put("name", coarea.getName());
								countries.add(country);
							}
						}
						city.put("nodes", countries);
						cities.add(city);
					}
				}
				provice.put("nodes", cities);
				allarea.add(provice);
			}
		}
		return allarea;
	}

}
