package com.rehome.jpahefengweather.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rehome.jpahefengweather.dto.NmcBaseDto;
import com.rehome.jpahefengweather.entity.*;
import com.rehome.jpahefengweather.service.excel.*;
import com.rehome.jpahefengweather.utils.JwtUtils;
import com.rehome.jpahefengweather.utils.OkHttpUtil;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
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 ScheduledWztfwStormService {

    @Resource
    private WztfStormService wztfStormService;

    /**
     * @date 2022-03-16 09:41
     * @description: 从温州气象台获取台风列表
     * @Param: null
     */
//    @Scheduled(cron = "0 39 15 * * *")
//    public void getWztfHistoryStormList() {
//        for(int i=1945;i<2026;i++){
//            getWztfStormList(String.valueOf(i));
//        }
//        //getWztfStormList(String.valueOf(1944));
//    }

    /**
     * @date 2022-03-16 09:41
     * @description: 从温州气象台获取台风列表
     * @Param: null
     */
    //@Scheduled(cron = "0 15 * * * *")
    public void getWztfStormList() {
        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        try {
            Thread.sleep(1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
            String nowDate = sdf.format(new Date());
            String nowYear = sdfYear.format(new Date());
            //nowYear = String.valueOf(i);

            String url = "http://data.istrongcloud.com/v2/data/complex/" + nowYear + ".json?v=" + String.valueOf(System.currentTimeMillis());
            System.out.println(url);
            // 初始化请求体
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            System.out.println(body);
            if (StringUtils.hasText(body)) {
                if (body.length() > 2) {
                    Gson gson = new Gson();
                    Type type = new TypeToken<ArrayList<WztfStorm>>() {
                    }.getType();
                    List<WztfStorm> stormList = gson.fromJson(body, type);
                    //打印测试
                    for (WztfStorm storm : stormList) {
                        storm.setYear(nowYear);
                        storm.setCreateDate(new Date());
                        //System.out.println(gson.toJson(storm));
                        WztfStorm stormDB = this.wztfStormService.findByTfbh(storm.getTfbh());
                        if (stormDB == null) {
                            //数据库无数据，第一次插入，同时从第三方平台拉取台风路径数据入库
                            this.wztfStormService.saveWztfStorm(storm);
                            this.saveOrUpdateWztfStormInfo(storm);
                        } else {
                            //数据库有数据
                            if (stormDB.getIs_current() == 1) {
                                if (storm.getIs_current() == 0) {
                                    //数据库里面台风数据是活跃状态，第三方平台台风数据已变成不活跃状态，更新数据库台风状态,同时更新台风路径
                                    stormDB.setIs_current(storm.getIs_current());
                                    this.wztfStormService.saveWztfStorm(stormDB);
                                    this.saveOrUpdateWztfStormInfo(stormDB);
                                } else {
                                    //数据库里面台风数据是活跃状态，第三方平台台风数据也是活跃状态
                                    if ((!storm.getEnd_time().equals(stormDB.getEnd_time())) || (!storm.getEname().equals(stormDB.getEname())) || (!storm.getName().equals(stormDB.getName())) || (!storm.getIdent().equals(stormDB.getIdent()))) {
                                        //台风列表数据有变化，更新台风列表数据
                                        stormDB.setEnd_time(storm.getEnd_time());
                                        stormDB.setEname(storm.getEname());
                                        stormDB.setName(storm.getName());
                                        stormDB.setIdent(storm.getIdent());
                                        this.wztfStormService.saveWztfStorm(stormDB);
                                    }
                                    //更新台风路径
                                    this.saveOrUpdateWztfStormInfo(stormDB);
                                }
                            } else {
                                //数据库里面台风数据是不活跃状态，无需做任何事情
                                //this.saveOrUpdateWztfStormInfo(storm);
                            }
                        }
                    }
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 从温州气象台获取台风路径，同时保存或更新台风路径
     * @Param: null
     */
    public void saveOrUpdateWztfStormInfo(WztfStorm storm) {
        System.out.println("saveOrUpdateTyphoonInfo");

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

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
            String nowDate = sdf.format(new Date());
            String nowYear = sdfYear.format(new Date());

            String url = "http://data.istrongcloud.com/v2/data/complex/" + storm.getTfbh() + ".json?v=" + String.valueOf(System.currentTimeMillis());
            System.out.println(url);

            // 初始化请求体
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            //System.out.println(body);
            if (StringUtils.hasText(body)) {
                if (body.length() > 2) {
                    Gson gson = new Gson();
                    int startIndex0 = body.indexOf("{");
                    int endIndex0 = body.lastIndexOf("}");
                    String typhoonInfoStr = body.substring(startIndex0, endIndex0 + 1);
                    //System.out.println(typhoonInfoStr);

                    WztfStormInfo wztfStormInfoDB = this.wztfStormService.findWztfStormInfoByTfbh(storm.getTfbh());
                    WztfStormInfo wztfStormInfo = new WztfStormInfo();
                    if (wztfStormInfoDB == null) {
                        //数据库无数据，保存风路径数据入库
                        wztfStormInfo.setTfbh(storm.getTfbh());
                        wztfStormInfo.setStormData(typhoonInfoStr);
                        wztfStormInfo.setCreateDate(new Date());
                        wztfStormInfo.setLastUpdateDate(new Date());
                        this.wztfStormService.saveWztfStormInfo(wztfStormInfo);
                    } else {
                        //数据库有数据，更新台风路径数据
                        wztfStormInfoDB.setStormData(typhoonInfoStr);
                        wztfStormInfoDB.setLastUpdateDate(new Date());
                        this.wztfStormService.saveWztfStormInfo(wztfStormInfoDB);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
