package com.czg.controller.user;

import com.czg.account.service.GeoService;
import com.czg.account.vo.DistrictVo;
import com.czg.resp.CzgResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * geo位置管理
 * @author Administrator
 */
@RestController
@RequestMapping("/user/geo")
public class UserGeoController {
    @Resource
    private GeoService geoService;

    /**
     * 经纬度换取位置信息
     * @param lat 经度
     * @param lng 纬度
     * @return 位置西悉尼
     */
    @GetMapping("/geocode")
    public CzgResult<?> getAddress(@RequestParam @NotEmpty String lat, @RequestParam @NotEmpty String lng) {
        return CzgResult.success(geoService.getAddress(lat, lng));
    }

    /**
     * 根据市换取所有下属行政区
     */
    @GetMapping("/district")
    public CzgResult<List<DistrictVo>> district(String keywords) throws JsonProcessingException {
        String districtJson = geoService.district(keywords,null);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(districtJson);
        JsonNode districts = jsonNode.get("districts");
        String text = districts.toString();
        List<DistrictVo> cityInfoList = mapper.readValue(text, mapper.getTypeFactory().constructCollectionType(List.class, DistrictVo.class));
        DistrictVo allCity = new DistrictVo();
        allCity.setName("全城");
        cityInfoList.addFirst(allCity);
        return CzgResult.success(cityInfoList);
    }
}
