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.dto.TyphoonInfoDto;
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.aspectj.util.FileUtil;
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.ObjectUtils;
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 32 11 * * *")
//    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 15 * * * *")
    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.saveOrUpdateTyphoonInfoByHistorySearch(storm);
                            } else {
                                //数据库有数据
                                if (stormDB.getIsactive().equals("1")) {
                                    if (storm.getIsactive().equals("0")) {
                                        //数据库里面台风数据是活跃状态，第三方平台台风数据已变成不活跃状态，更新数据库台风状态,同时更新台风路径
                                        stormDB.setIsactive(storm.getIsactive());
                                        this.zjsltStormService.saveZjsltStorm(stormDB);
                                        this.saveOrUpdateTyphoonInfoByHistorySearch(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.saveOrUpdateTyphoonInfoByHistorySearch(stormDB);
                                    }
                                } else {
                                    //数据库里面台风数据是不活跃状态，无需做任何事情
                                    this.saveOrUpdateTyphoonInfoByHistorySearch(storm);
                                }
                            }
                        }
                    } else {
//                        ZjsltStorm storm = new ZjsltStorm();
//                        storm.setTfid("202501");
//                        this.saveOrUpdateTyphoonInfoByHistorySearch(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);
                    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);

                        log.info("--------浙江省水利厅台风详情---------");
                        log.info(typhoonInfoArryStr);
                        try {
                            String currentSecond = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
                            String typhoonInfoFileName = "typhoonInfo_" + currentSecond + ".json";
                            String bodyFile = "typhoonInfo_" + currentSecond + "_body.json";
                            FileUtil.writeAsString(new File("/Users/admin/typhoonInfo/" + typhoonInfoFileName), typhoonInfoStr);
                            FileUtil.writeAsString(new File("/Users/admin/typhoonInfo/" + bodyFile), body);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        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
     */
    public void saveOrUpdateTyphoonInfoByHistorySearch(ZjsltStorm storm) {
        log.info("saveOrUpdateTyphoonInfoByHistorySearch");
        String strNow = String.valueOf(System.currentTimeMillis());
        Gson gson = new Gson();

        // 初始化 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);
            String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36";
            // 初始化请求体
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .addHeader("User-Agent", userAgent)
                    .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                    .addHeader("Accept-language", "zh-CN,zh;q=0.9")
                    .addHeader("Connection", "keep-alive")
                    .build();
//            log.info("---------OkHttpClient Request Header-----------------");
//            log.info(gson.toJson(request.headers()));

            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            //log.info(body);
            if (StringUtils.hasText(body)) {
                if (body != null && body.length() > 2) {
                    log.info("--------浙江省水利厅台风详情---------");
                    log.info(body);

                    try {
                        String currentSecond = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
                        String typhoonInfoFileName = "typhoonInfo_" + currentSecond + ".json";
                        String bodyFile = "typhoonInfo_" + currentSecond + "_body.json";
                        FileUtil.writeAsString(new File("/Users/admin/typhoonInfo/" + typhoonInfoFileName), body);
                        FileUtil.writeAsString(new File("/Users/admin/typhoonInfo/" + bodyFile), body);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    TyphoonInfo typhoonInfoDB = this.zjsltStormService.findTyphoonInfoByTfid(storm.getTfid());
                    TyphoonInfo typhoonInfo = new TyphoonInfo();
                    if (typhoonInfoDB == null) {
                        //数据库无数据，保存风路径数据入库
                        typhoonInfo.setTfid(storm.getTfid());
                        typhoonInfo.setStormData(body);
                        typhoonInfo.setCreateDate(new Date());
                        typhoonInfo.setLastUpdateDate(new Date());
                        this.zjsltStormService.saveTyphoonInfo(typhoonInfo);
                    } else {
                        //数据库有数据，更新台风路径数据
                        typhoonInfoDB.setStormData(body);
                        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));
    }

    /**
     * @date 2026-06-21 15:41
     * @description: 根据年份查台风列表
     * @Param: null
     */
    //@Scheduled(cron = "0 0/1 * * * *")
    public void getTyphoonInfoDto() {
        log.info("getTyphoonInfoDto");
        Gson gson = new Gson();
        String tfid = "202501";
        TyphoonInfo typhoonInfo = this.zjsltStormService.findTyphoonInfoByTfid(tfid);
        if(!ObjectUtils.isEmpty(typhoonInfo)){
            TyphoonInfoDto typhoonInfoDto = gson.fromJson(typhoonInfo.getStormData(),TyphoonInfoDto.class);
            log.info("-----------------");
            log.info(gson.toJson(typhoonInfoDto));
        }
    }
}
