package com.djhk.uav.weather;



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.djhk.common.api.RemoteDictDataService;
import com.djhk.common.core.domain.R;
import com.djhk.common.core.domain.entity.SysDictData;
import com.djhk.common.core.redis.RedisCache;
import com.djhk.common.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 天气管理 Controller
 *
 * @author qingpengcheng
 * @date 2023-10-20
 */
@RestController
@RequestMapping("/weather")
public class WeatherController {

    @Autowired
    private RedisCache redisService;

    @Autowired
    private RemoteDictDataService remoteDictDataService;

    @PostMapping("/info")
//    @PostConstruct
    public Map<String, JSONObject> createControlJob(String latlng) {

        Map<String,JSONObject> cacheObject = redisService.getCacheObject(latlng + "weather");
        if (StringUtils.isNotEmpty(cacheObject)){
            return cacheObject;
        }else {
        R<List<SysDictData>> dictDataByType = remoteDictDataService.getDictDataByType("weather_key", "inner");
        for (SysDictData entity : dictDataByType.getData()) {
            String url = "https://devapi.qweather.com/v7/weather/24h?location=" + latlng + "&key=" + entity.getDictLabel();
            String data = requestByGetMethod(url);
            JSONObject o = JSONObject.parseObject(data);
            if (Integer.valueOf(o.getString("code")) != 200) {
                continue;
            }
            try {
                String hourly = o.getString("hourly");
                JSONArray array = JSONObject.parseArray(hourly);

                Map<String, JSONObject> map = new HashMap<>();
                map.put(latlng + "one", array.getJSONObject(0));
                map.put(latlng + "two" , array.getJSONObject(2));
                map.put(latlng + "three",array.getJSONObject(4));
                map.put(latlng + "four", array.getJSONObject(6));
                redisService.setCacheObject(latlng + "weather", map, 120L, TimeUnit.MINUTES);

                return map;
            } catch (Exception e) {
                throw new RuntimeException("获取天气异常，请联系管理员！");
            }
        }



        }
        return null;
    }

    /**
     * 请求天气数据
     * @param url
     * @return
     */
    public String requestByGetMethod(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        StringBuilder entityStringBuilder = null;
        try {
            HttpGet get = new HttpGet(url);
            get.setHeader("Accept", "*/*");
            get.setHeader("Accept-Encoding", "gzip, deflate, br");
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(get);
            try {
                HttpEntity entity = httpResponse.getEntity();
                entityStringBuilder = new StringBuilder();
                if (null != entity) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);
                    String line = null;
                    while ((line = bufferedReader.readLine()) != null) {
                        entityStringBuilder.append(line + "/n");
                    }
                }
            } finally {
                httpResponse.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String out = entityStringBuilder.toString();
        return out.substring(0,out.length()-2);
    }

}
