package com.usky.iot.controller.web;

import com.alibaba.nacos.common.utils.StringUtils;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.HttpUtils;
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.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zyj
 * @date 2023/9/14 15:02
 */
@RestController
@RequestMapping("weather")
public class WeatherController {
    private static final String ALI_WEATHER_HEADER_KEY = "Authorization";
    private static final String ALI_WEATHER_APPCODE = "0f2b7fce6e104ba8835358b7b59b4fb6";
    private static final String ALI_WEATHER_HEADER_VALUE = "APPCODE " + ALI_WEATHER_APPCODE;

    private String weather = "";

    private Date date = null;

    /**
     * 公共天气信息
     * @param area
     * @return
     */
    @GetMapping("getInfo")
    public ApiResult<String> get(@RequestParam(value = "area") String area) {
        if (StringUtils.isBlank(weather)) {
            weather = getWeatherApi(area);
            date = new Date();
        } else {
            if ((System.currentTimeMillis() - date.getTime()) >= (1000 * 60 * 60 * 5)) {
                weather = getWeatherApi(area);
                date = new Date();
            }
        }

        return ApiResult.success(weather);
    }

    public String getWeatherApi(String area) {
        try {
            String ALI_WEATHER_API_URL = "https://weather01.market.alicloudapi.com/area-to-weather?area="+area;
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put(ALI_WEATHER_HEADER_KEY, ALI_WEATHER_HEADER_VALUE);
            headerMap.put("Content-Type","application/json;charset=UTF-8");
            return HttpUtils.get(ALI_WEATHER_API_URL, headerMap);
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
    }
}
