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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 ScheduledZjsltStormService {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ZjsltStormService zjsltStormService;


    /**
     * @date 2022-03-16 09:41
     * @description: 从浙江省水利厅获取历史台风列表数据和对应的台风详情
     * @Param: null
     */
//    @Scheduled(cron = "0 57 1 * * *")
//    public void getZjsltHistoryStormList() {
//        for(int i=1944;i<2026;i++){
//            getZjsltStormList(String.valueOf(i));
//        }
//    }
    /**
     * @date 2022-03-16 09:41
     * @description: 从浙江省水利厅获取台风列表
     * @Param: null
     */
    @Scheduled(cron = "0 23 * * * *")
    public void getZjsltStormList() {
        log.info("getZjsltStormList");
        String strNow = String.valueOf(System.currentTimeMillis());

        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        try {
            Thread.sleep(2000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
            String nowDate = sdf.format(new Date());
            String nowYear = sdfYear.format(new Date());

            Random random = new Random();//以系统自身时间为种子数
            int iRandom = random.nextInt();
            Long nowLong = 13728353350362976L;
            Long nowLongTemp = nowLong + iRandom;
            String url = "https://typhoon.slt.zj.gov.cn/Api/TyphoonList/" + nowYear + "?callback=jQuery" + "1830" + String.valueOf(nowLongTemp) + "_" + strNow + "&_=" + String.valueOf(System.currentTimeMillis());
            log.info(url);
            // 初始化请求体
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            //log.info(body);
            if (StringUtils.hasText(body)) {
                if (body.length() > 0) {
                    Gson gson = new Gson();
                    int startIndex = body.indexOf("[");
                    int endIndex = body.lastIndexOf("]");
//                    log.info(body.indexOf("["));
//                    log.info(body.lastIndexOf("]"));
                    String stormStr = body.substring(startIndex, endIndex + 1);
                    //log.info(stormStr);
                    if (stormStr != null && stormStr.length() > 2) {
                        Type type = new TypeToken<ArrayList<ZjsltStorm>>() {
                        }.getType();
                        List<ZjsltStorm> stormList = gson.fromJson(stormStr, type);
                        //打印测试
                        for (ZjsltStorm storm : stormList) {
                            storm.setYear(nowYear);
                            storm.setCreateDate(new Date());
                            log.info(gson.toJson(storm));
                            ZjsltStorm stormDB = this.zjsltStormService.findByTfid(storm.getTfid());
                            if (stormDB == null) {
                                //数据库无数据，第一次插入，同时从第三方平台拉取台风路径数据入库
                                this.zjsltStormService.saveZjsltStorm(storm);
                                this.saveOrUpdateTyphoonInfo(storm);
                            } else {
                                //数据库有数据
                                if (stormDB.getIsactive().equals("1")) {
                                    if (storm.getIsactive().equals("0")) {
                                        //数据库里面台风数据是活跃状态，第三方平台台风数据已变成不活跃状态，更新数据库台风状态,同时更新台风路径
                                        stormDB.setIsactive(storm.getIsactive());
                                        this.zjsltStormService.saveZjsltStorm(stormDB);
                                        this.saveOrUpdateTyphoonInfo(stormDB);
                                    } else {
                                        //数据库里面台风数据是活跃状态，第三方平台台风数据也是活跃状态
                                        if ((!storm.getEndtime().equals(stormDB.getEndtime())) || (!storm.getEnname().equals(stormDB.getEnname())) || (!storm.getName().equals(stormDB.getName()))) {
                                            //台风列表数据有变化，更新台风列表数据
                                            stormDB.setEndtime(storm.getEndtime());
                                            stormDB.setEnname(storm.getEnname());
                                            stormDB.setName(storm.getName());
                                            this.zjsltStormService.saveZjsltStorm(stormDB);
                                        }
                                        //更新台风路径
                                        this.saveOrUpdateTyphoonInfo(stormDB);
                                    }
                                } else {
                                    //数据库里面台风数据是不活跃状态，无需做任何事情
                                    //this.saveOrUpdateTyphoonInfo(storm);
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 从浙江省水利厅获取台风详情数据，保存或更新台风路径
     * @Param: null
     */
    public void saveOrUpdateTyphoonInfo(ZjsltStorm storm) {
        log.info("saveOrUpdateTyphoonInfo");
        String strNow = String.valueOf(System.currentTimeMillis());

        // 初始化 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());
            Random random = new Random();//以系统自身时间为种子数
            int iRandom = random.nextInt();
            Long nowLong = 25528353350362976L;
            Long nowLongTemp = nowLong + iRandom;
            String url = "https://typhoon.slt.zj.gov.cn/Api/TyphoonInfo/" + storm.getTfid() + "?callback=jQuery" + "1830" + String.valueOf(nowLongTemp) + "_" + strNow + "&_=" + String.valueOf(System.currentTimeMillis());
            log.info(url);
            // 初始化请求体
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            //log.info(body);
            if (StringUtils.hasText(body)) {
                if (body.length() > 0) {
                    Gson gson = new Gson();
                    int startIndex = body.indexOf("[");
                    int endIndex = body.lastIndexOf("]");
//                    log.info(body.indexOf("["));
//                    log.info(body.lastIndexOf("]"));
                    String typhoonInfoArryStr = body.substring(startIndex, endIndex + 1);
                    //log.info(typhoonInfoArryStr);
                    if (typhoonInfoArryStr != null && typhoonInfoArryStr.length() > 2) {
                        int startIndex0 = typhoonInfoArryStr.indexOf("{");
                        int endIndex0 = typhoonInfoArryStr.lastIndexOf("}");
//                        log.info(startIndex0);
//                        log.info(endIndex0);
                        String typhoonInfoStr = typhoonInfoArryStr.substring(startIndex0, endIndex0 + 1);
                        //log.info(typhoonInfoStr);

                        TyphoonInfo typhoonInfoDB = this.zjsltStormService.findTyphoonInfoByTfid(storm.getTfid());
                        TyphoonInfo typhoonInfo = new TyphoonInfo();
                        if (typhoonInfoDB == null) {
                            //数据库无数据，保存风路径数据入库
                            typhoonInfo.setTfid(storm.getTfid());
                            typhoonInfo.setStormData(typhoonInfoStr);
                            typhoonInfo.setCreateDate(new Date());
                            typhoonInfo.setLastUpdateDate(new Date());
                            this.zjsltStormService.saveTyphoonInfo(typhoonInfo);
                        } else {
                            //数据库有数据，更新台风路径数据
                            typhoonInfoDB.setStormData(typhoonInfoStr);
                            typhoonInfoDB.setLastUpdateDate(new Date());
                            this.zjsltStormService.saveTyphoonInfo(typhoonInfoDB);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 从本地数据库获取活跃台风列表
     * @Param: null
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void getTyhoonActivity() {
        log.info("getTyhoonActivity");
        String strNow = String.valueOf(System.currentTimeMillis());
        log.info(strNow);
        List<ZjsltStorm> list = this.zjsltStormService.getTyhoonActivity();
        log.info(String.valueOf(list.size()));
        log.info(new Gson().toJson(list));
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 根据年份查台风列表
     * @Param: null
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void getZjsltStormByYear() {
        log.info("getZjsltStormByYear");
        String strNow = String.valueOf(System.currentTimeMillis());
        log.info(strNow);
        String currentYear = new SimpleDateFormat("yyyy").format(new Date());
        List<ZjsltStorm> list = this.zjsltStormService.findByYear(currentYear);
        log.info(String.valueOf(list.size()));
        log.info(new Gson().toJson(list));
    }
}
