package com.rehome.jpahefengweather.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rehome.jpahefengweather.JpahefengweatherApplication;
import com.rehome.jpahefengweather.dto.NmcBaseDto;
import com.rehome.jpahefengweather.entity.*;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author huangwenfei
 * @version v1.0.0.0
 * Created DateTime 2021-04-26 14:35
 * @description: 中央气象台天气服务，定时任务
 */
//@Component
public class ScheduledNmcWeatherService {
    @Value("${rehome.resources-path}")
    private String resourcesPath;

    @Resource
    private CityService cityService;
    @Resource
    private NmcCityService nmcCityService;
    @Resource
    private NmcWeatherService nmcWeatherService;
    @Resource
    private NmcStormService nmcStormService;
    @Resource
    private ZjsltStormService zjsltStormService;
    @Resource
    private WztfStormService wztfStormService;


    /**
     * @date 2022-03-16 09:41
     * @description: 从中央气象台获取省份列表
     * @Param: null
     */
    //@Scheduled(cron = "0 29 * * * *")
    public void getNmcWeatherProvince() {
        System.out.println("scheduledGetWeather");
        System.out.println("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        System.out.println(String.valueOf(System.currentTimeMillis()));
        String url = "http://www.nmc.cn/rest/province/all?_=" + String.valueOf(System.currentTimeMillis());
        System.out.println(url);
        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        // 初始化请求体
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        try {
            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            System.out.println(body);
            if (StringUtils.hasText(body)) {
                Gson gson = new Gson();
                List<NmcProvince> provinces = gson.fromJson(body, new TypeToken<List<NmcProvince>>() {
                }.getType());
                ;
                for (NmcProvince province : provinces) {
                    System.out.println(gson.toJson(province));
                    this.nmcCityService.saveProvince(province);
                    getNmcWeatherCityByCode(province.getCode());
                    try {
                        Thread.sleep(500);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(provinces.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @date 2022-03-16 09:41
     * @description: 根据省份code获取城市列表
     * @Param: null
     */
    public void getNmcWeatherCityByCode(String code) {
        String url = "http://www.nmc.cn/rest/province/" + code + "?_=" + String.valueOf(System.currentTimeMillis());
        System.out.println(url);
        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        // 初始化请求体
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        try {
            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            System.out.println(body);
            if (StringUtils.hasText(body)) {
                Gson gson = new Gson();
                List<NmcCity> citys = gson.fromJson(body, new TypeToken<List<NmcCity>>() {
                }.getType());
                ;
                for (NmcCity city : citys) {
                    System.out.println(gson.toJson(city));
                    this.nmcCityService.saveCity(city);
                }
                System.out.println(citys.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @date 2022-03-16 09:41
     * @description: 从中央气象台获取实时天气数据
     * @Param: null
     */
    //@Scheduled(cron = "0 15 * * * *")
    public void getNmcNowWeather() {
        System.out.println("scheduledGetWeather");
        System.out.println("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        System.out.println(String.valueOf(System.currentTimeMillis()));


        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        List<NmcCity> citys = this.nmcCityService.findAllCityList();

        for (NmcCity city : citys) {
            String url = "http://www.nmc.cn/rest/weather?stationid=" + city.getCode() + "&_=" + String.valueOf(System.currentTimeMillis());
            System.out.println(url);
            // 初始化请求体
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();

            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    System.out.println(body);
                    if (StringUtils.hasText(body)) {
                        try {
                            Gson gson = new Gson();
                            NmcBaseDto nmcBaseDto = gson.fromJson(body, NmcBaseDto.class);
                            if (nmcBaseDto != null && nmcBaseDto.getCode() == 0) {
                                Date now = new Date();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                String nowDate = sdf.format(new Date());

                                NmcNowWeather nowWeather = new NmcNowWeather();
                                nowWeather.setCode(city.getCode());
                                nowWeather.setWeather(body);
                                nowWeather.setWeatherDate(nowDate);
                                nowWeather.setLastUpdateDate(now);
                                nowWeather.setCreateDate(now);

                                NmcWeatherService nmcWeatherServiceTemp = JpahefengweatherApplication.context.getBean(NmcWeatherService.class);
                                nmcWeatherServiceTemp.saveNowWeather(nowWeather);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }
}
