package com.ruoyi.common.utils;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.HOURS;

/**
 * 地图工具类
 */
@Component
public class AMAPUtils {

    //WEB端KEY
    public final static String AMAP_WEB_KEY = "GRGBZ-MOXAD-ICL4Y-P336E-BNM2Q-42FLP";

    //JSON格式返回数据
    public final static String OUTPUT_TYPE = "JSON";

    /**
     * 地理编码 API 服务地址（获取经纬度） Get请求方式
     * key 秘钥（必填）
     * city 城市名（建议填写）
     * address 详细地址（必填）
     * 官方文档 https://lbs.qq.com/service/webService/webServiceGuide/webServiceGeocoder
     */
    public final static String LON_LAT_URL = "https://apis.map.qq.com/ws/geocoder/v1/?address=";

    @Resource
    private RedisCache redisCache;

    /**
     * web端，商家获取地理经纬度
     * @param city 城市名称
     * @param address 详细地址
     * @return
     */
    public AjaxResult getShopLonLat(String city, String area, String address){

        //请求参数
        String searchValue = city+area+address;
        //redis，查询
        if (redisCache.isExist("MAP_LNG_LAT_"+searchValue)){
            //方法返回
            AjaxResult ajaxResult = new AjaxResult();
            Map<String, String> cacheMap = redisCache.getCacheMap("MAP_LNG_LAT_" + searchValue);
            String longitude = MapUtils.getString(cacheMap, "longitude");
            String latitude = MapUtils.getString(cacheMap, "latitude");
            ajaxResult.put("code",200);
            ajaxResult.put("longitude",longitude);
            ajaxResult.put("latitude",latitude);
            return ajaxResult;
        }

        String resUrl = LON_LAT_URL+searchValue+"&key="+AMAP_WEB_KEY;

        //结果字符串，JSON格式
        String resultStr = HttpUtil.get(resUrl);
        JSONObject jsonObject = JSON.parseObject(resultStr);
        String status = jsonObject.getString("status");

        //方法返回
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("code",500);
        if ("0".equals(status)){
            //成功
            JSONObject geocodes = jsonObject.getJSONObject("result");
            if (ObjectUtils.isNotEmpty(geocodes)){
                JSONObject location = geocodes.getJSONObject("location");
                ajaxResult.put("code",200);
                ajaxResult.put("longitude",location.getString("lng"));
                ajaxResult.put("latitude",location.getString("lat"));

                Map<String, String> stringStringHashMap = new HashMap<>();
                stringStringHashMap.put("longitude",location.getString("lng"));
                stringStringHashMap.put("latitude",location.getString("lat"));
                //缓存
                redisCache.setCacheMap("MAP_LNG_LAT_"+searchValue,stringStringHashMap);
                //设置有效期
                redisCache.expire("MAP_LNG_LAT_"+searchValue,24*60*60, TimeUnit.SECONDS);
            }
        }else {
            String message = jsonObject.getString("message");
            ajaxResult.put("msg",message);
        }
        return ajaxResult;

    }

    /**
     * 用户所在城市限号
     * https://api.binstd.com/vehiclelimit/query GET
     * @param city 城市代号（拼音）
     * @param date 日期 默认为今天 格式为：2015-12-02
     * @return
     */
    public AjaxResult getLimitNumber(String city, String date){
        String cityPinyin = PinyinUtil.getPinyin(city).replace(" ","");

        String redisKey = "LIMIT_NUM"+":"+date+":"+cityPinyin;
        //redis，查询
        if (redisCache.isExist(redisKey)){
            String s = redisCache.getCacheObject(redisKey).toString();

            return AjaxResult.success(JSONObject.parse(s));
        }else {
            //请求api
            String s = HttpUtil.get("https://api.binstd.com/vehiclelimit/query?" +
                    "appkey=7bd6e233948bd496&" +
                    "city="+cityPinyin+"&" +
                    "date="+date);
            JSONObject jsonObject = JSONObject.parseObject(s);
            if ("0".equals(jsonObject.getString("status")) && "ok".equals(jsonObject.getString("msg"))){
                JSONObject result = jsonObject.getJSONObject("result");
                //redis缓存
                redisCache.setCacheObject(redisKey,result,24,HOURS);
                return AjaxResult.success(result);
            }

        }

        return AjaxResult.error();
    }

}
