package com.sys.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cku.core.BaseDAOMapper;
import com.cku.core.BaseService;
import com.cku.core.PageBeanResult;
import com.sys.dao.AreaMapper;
import com.sys.dao.CityMapper;
import com.sys.dao.ProvinceMapper;
import com.sys.model.Area;
import com.sys.model.AreaTreeResponse;
import com.sys.model.City;
import com.sys.model.Province;

@Service("areaService")
public class AreaServiceImpl extends BaseService<Area> {
	@Autowired
	public AreaMapper areaMapper;

	@Autowired
	public CityMapper cityMapper;

	@Autowired
	public ProvinceMapper provinceMapper;

	@Override
	protected BaseDAOMapper<Area> getDAO() {
		return this.areaMapper;
	}

	public PageBeanResult<Area> getList(String cityCode) {

		List<Area> list = areaMapper.selectByCityId(cityCode);

		PageBeanResult<Area> prResult = new PageBeanResult<Area>();
		prResult.list = list;
		prResult.totalCount = (long) list.size();

		return prResult;
	}

	public PageBeanResult<AreaTreeResponse> findAreaTree() {

		List<Province> provinceList = provinceMapper.selectAll();
		List<City> cityList = cityMapper.selectAll();
		List<Area> areaList = areaMapper.selectAll();

		Map<String, List<AreaTreeResponse>> areaMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(areaList)) {
			areaMap.putAll(areaList.stream().map(a -> {
				return new AreaTreeResponse(a.getAreaId(), a.getArea(), a.getCityId(), 3, null);
			}).collect(Collectors.groupingBy(AreaTreeResponse::getParentValue)));
		}

		Map<String, List<AreaTreeResponse>> cityMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(cityList)) {
			List<AreaTreeResponse> cityResp = cityList.stream().map(a -> {
				return new AreaTreeResponse(a.getCityId(), a.getCity(), a.getProvinceId(), 2, new ArrayList<>());
			}).collect(Collectors.toList());

			cityResp.forEach(c -> {
				c.setChildren(areaMap.get(c.getValue()));
			});
			cityMap.putAll(cityResp.stream().collect(Collectors.groupingBy(AreaTreeResponse::getParentValue)));
		}

		List<AreaTreeResponse> provinceResp = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(provinceList)) {

			provinceResp = provinceList.stream().map(a -> {
				return new AreaTreeResponse(a.getProvinceId(), a.getProvince(), null, 1, new ArrayList<>());
			}).collect(Collectors.toList());

			provinceResp.stream().forEach(p -> {
				p.setChildren(cityMap.get(p.getValue()));
			});
		}

		PageBeanResult<AreaTreeResponse> prResult = new PageBeanResult<>();
		prResult.list = provinceResp;
		prResult.totalCount = (long) provinceResp.size();
		return prResult;
	}

}
