package com.ruoyi.ibs.grid.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.ibs.custmap.domain.entity.DeptAddress;
import com.ruoyi.ibs.custmap.service.DeptAddressService;
import com.ruoyi.ibs.grid.domain.dto.BaiduResponseDTO;
import com.ruoyi.ibs.grid.domain.vo.AddressResultVO;
import com.ruoyi.ibs.grid.service.AddressAnalyseService;
import com.ruoyi.ibs.grid.service.BaiduApiService;
import com.ruoyi.ibs.grid.util.GPSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 javax.annotation.Resource;

@Api(tags = "地址解析接口")
@RestController
@RequestMapping("/address/analyse")
public class AddressAnalyseController extends BaseController {
    @Resource
    private AddressAnalyseService adminDivisionService;

    @Resource
    private BaiduApiService baiduApiService;

    @Resource
    private DeptAddressService deptAddressService;

    @ApiOperation("百度地点检索")
    @GetMapping("/placeSearch")
    @Log(title = "百度地点检索")
    public AjaxResult placeSearch(@RequestParam String address) {
        String region;
        BaiduResponseDTO geocoding = baiduApiService.geocoding(address);
        if (geocoding.getStatus() != 0) {
            DeptAddress deptAddress = deptAddressService.selectDeptAddressById();
            region = deptAddress.getCity();
        } else {
            AddressResultVO addressResultVO = adminDivisionService.pointInGeometry(geocoding.getResult().getLocation().getLng(), geocoding.getResult().getLocation().getLat());
            region = addressResultVO.getCity();
        }
        JsonNode jsonNode = baiduApiService.placeSearch(region, address);
        if (jsonNode.get("status").equals("2")) {
            throw new ServiceException("请求参数非法");
        } else if (jsonNode.get("status").equals("4")) {
            throw new ServiceException("服务当日调用次数已达上线");
        } else if (jsonNode.get("status").equals("5")) {
            throw new ServiceException("ak不存在或非法");
        } else if (jsonNode.get("status").equals("8")) {
            throw new ServiceException("数据解析失败，参数中包含特殊符号");
        }
        return AjaxResult.success(jsonNode.get("results"));
    }

    @ApiOperation("经纬度转换")
    @GetMapping("/gps")
    public AjaxResult addressStandardize(@RequestParam Double lng, @RequestParam Double lat) {
        return AjaxResult.success(GPSUtil.gcj02ToBd09(lng, lat));
    }

}
