package com.tuoheng.admin.service.city;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuoheng.admin.entity.City;
import com.tuoheng.admin.mapper.CityMapper;
import com.tuoheng.admin.query.CityQuery;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 高德城市表 服务实现类
 * </p>
 *
 * @author 拓恒
 * @since 2020-11-03
 */
@Service
public class CityServiceImpl implements ICityService {

    @Autowired
    private CityMapper cityMapper;

    /**
     * 获取城市列表
     * @param cityQuery
     * @return
     */
    @Override
    public JsonResult getList(CityQuery cityQuery) {
        CityQuery query = (CityQuery) cityQuery;
        // 查询条件
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        //父级Id
        if (StringUtils.isNull(cityQuery.getPid())) {
            queryWrapper.eq("pid", 0);
        } else {
            queryWrapper.eq("pid", cityQuery.getPid());
        }
        // 城市名称
        if (!StringUtils.isEmpty(cityQuery.getName())) {
            queryWrapper.like("name", cityQuery.getName());
        }
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByAsc("sort");
        // 查询分页数据
        List<City> cityList = cityMapper.selectList(queryWrapper);
        cityList.forEach(item -> {
            //省、市、区、街道、村
            if (item.getLevel() <= 5) {
                item.setHasChildren(true);
            }
        });
        return JsonResult.success(cityList);
    }


    @Override
    public List<City> getCityList() {
        List<City> list = cityMapper.selectList(new LambdaQueryWrapper<City>()
                .eq(City::getMark, 1));

        // 获取所有一级节点
        List<City> result = list.stream().
                filter(city -> city.getPid() == 0)
                .peek(city -> city.setItemList(getChildren(city, list))).sorted(Comparator.comparingInt(city -> (city.getSort() == null ? 0 : city.getSort())))
                .collect(Collectors.toList());

        return result;
    }


    /**
     * 递归获取有行政区的子集
     *
     * @author zhu_zishuang
     * @date 3/13/21
     */
    private List<City> getChildren(City rootCity, List<City> list) {
        return list.stream().filter(city ->
                city.getPid().equals(rootCity.getId())
        ).peek(city -> {
            // 设置子集
            city.setItemList(getChildren(city, list));
        }).sorted(Comparator.comparingInt(city -> (city.getSort() == null ? 0 : city.getSort()))).collect(Collectors.toList());

    }

}
