package com.tuoheng.system.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.utils.StringUtils;
import com.tuoheng.common.common.BaseQuery;
import com.tuoheng.common.common.BaseServiceImpl;
import com.tuoheng.system.entity.City;
import com.tuoheng.system.mapper.CityMapper;
import com.tuoheng.system.query.CityQuery;
import com.tuoheng.system.service.ICityService;
import com.tuoheng.system.vo.city.CityInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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

    @Autowired
    private CityMapper cityMapper;

    @Override
    public List<City> getCityList() {
        List<City> list = cityMapper.selectList(new QueryWrapper<>());

        // 获取所有一级节点
        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());

    }

    /**
     * 获取城市列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(BaseQuery query) {
        CityQuery cityQuery = (CityQuery) query;
        // 查询条件
        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() <= 4) {
                item.setHasChildren(true);
            }
        });
        return JsonResult.success(cityList);
    }

    @Override
    public String getCityNameByCode(String cityCode, String delimiter) {
        List<String> nameList = new ArrayList<>();
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("citycode", cityCode);
        queryWrapper.eq("mark", 1);
        queryWrapper.last("limit 1");
        City cityInfo = cityMapper.selectOne(queryWrapper);
        if (cityInfo == null) {
            return null;
        }
        Integer cityId = cityInfo.getId();
        while (cityId > 0) {
            City cateInfo = cityMapper.selectById(cityId);
            if (cateInfo != null) {
                nameList.add(cateInfo.getName());
                cityId = cateInfo.getPid();
            } else {
                cityId = null;
            }
        }
        // 使用集合工具实现数组翻转
        Collections.reverse(nameList);
        return org.apache.commons.lang3.StringUtils.join(nameList.toArray(), delimiter);
    }

    @Override
    public CityInfoVo getCityInfoByCode(String cityCode, String delimiter) {
        CityInfoVo cityInfoVo = new CityInfoVo();
        List<String> nameList = new ArrayList<>();
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("citycode", cityCode);
        queryWrapper.eq("mark", 1);
        queryWrapper.last("limit 1");
        City cityInfo = cityMapper.selectOne(queryWrapper);
        if (cityInfo == null) {
            return null;
        }
        Integer cityId = cityInfo.getId();
        while (cityId > 0) {
            City cateInfo = cityMapper.selectById(cityId);
            if (cateInfo != null) {
                nameList.add(cateInfo.getName());
                cityId = cateInfo.getPid();
            } else {
                cityId = null;
            }
        }
        // 使用集合工具实现数组翻转
        Collections.reverse(nameList);
        String cityArea = org.apache.commons.lang3.StringUtils.join(nameList.toArray(), delimiter);
        cityInfoVo.setCityArea(cityArea);
        if(StringUtils.isNotEmpty(nameList) && nameList.size()>0){
            cityInfoVo.setProvinceName(nameList.get(0));
        }
        if(StringUtils.isNotEmpty(nameList) && nameList.size()>1){
            cityInfoVo.setCityName(nameList.get(1));
        }
        if(StringUtils.isNotEmpty(nameList) && nameList.size()>2){
            cityInfoVo.setDistrictName(nameList.get(2));
        }
        if(StringUtils.isNotEmpty(nameList) && nameList.size()>3){
            cityInfoVo.setStreetName(nameList.get(3));
        }
        if(StringUtils.isNotEmpty(nameList) && nameList.size()>4){
            cityInfoVo.setVillageName(nameList.get(4));
        }
        return cityInfoVo;
    }

}
