package com.rehome.jpahefengweather.service;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rehome.jpahefengweather.dto.*;
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.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 ScheduledHefengWeatherService {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Value("${rehome.resources-path}")
    private String resourcesPath;

    @Resource
    private CityService cityService;

    @Resource
    private HefengWeatherService hefengWeatherService;


    /**
     * @date 2022-03-14 15:57
     * @description: 定时任务, 调用 和风天气平台 天气预报-实时天气 获取城市列表接口
     * 城市列表 下载地址：https://github.com/qwd/LocationList
     * 和风天气接口文档：https://dev.qweather.com/docs/start/
     * //天气图标用法: https://icons.qweather.com/usage/
     * @Param: null
     */
    //@Scheduled(cron = "0 44 17 * * *")//每个小时执行一次
    public void scheduled() {
        log.info("scheduled");
        log.info("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (this.resourcesPath != null) {
            log.info(this.resourcesPath);
            try {
                File excelFile = new File(this.resourcesPath + File.separator + "China-City-List-latest.xlsx");
                if (excelFile.exists()) {
                    log.info("文件存在");
                    WriteExcel writeExcel = new WriteExcel(this.resourcesPath, "writeExcel.xlsx");
                    //writeExcel.testWriteExcel();

                    ReadExcelXls readExcelXls = new ReadExcelXls(this.resourcesPath, "China-City-List-latest.xls");
                    //readExcelXls.testReadExcel();

                    ReadCityExcelXls readCityExcelXls = new ReadCityExcelXls(this.resourcesPath, "China-City-List-latest.xls");
                    //readCityExcelXls.testReadExcel();
//                    List<CityList> excelList = readCityExcelXls.getCityLists();
//                    this.CityService.saveCitys(excelList);

//                    ReadExcelXlsx readExcelXlsx = new ReadExcelXlsx(this.resourcesPath,"China-City-List-latest.xlsx");
//                    readExcelXlsx.testReadExcel();

                    ReadCityExcelXlsx readCityExcelXlsx = new ReadCityExcelXlsx(this.resourcesPath, "China-City-List-latest.xlsx");
                    //readCityExcelXlsx.testReadExcel();
                    List<HefengCity> excelReadCityExcelXlsx = readCityExcelXlsx.getCityLists();
                    if(excelReadCityExcelXlsx!=null&&excelReadCityExcelXlsx.size()>0){
                        this.cityService.saveCityList(excelReadCityExcelXlsx);
                        Map<String,String> provinceCodeMap = new HashMap<>();
                        for (HefengCity hefengCity :excelReadCityExcelXlsx) {
                            provinceCodeMap.put(hefengCity.getAdm1NameEn(),hefengCity.getAdm1NameZh());
                        }
                        log.info(new Gson().toJson(provinceCodeMap));
                        log.info(String.valueOf(provinceCodeMap.size()));
                        List<HefengProvince> provinceList = new ArrayList<>();
                        for (String key : provinceCodeMap.keySet()) {
                            String provinceName = provinceCodeMap.get(key);
                            HefengProvince province = new HefengProvince();
                            province.setCode(key);
                            province.setName(provinceName);
                            Date now = new Date();
                            province.setCreateDate(now);
                            province.setLastUpdateDate(now);
                            provinceList.add(province);
                        }
                        if(provinceList.size()>0){
                            this.cityService.saveProvinceList(provinceList);
                        }
                        List<HefengCity> listCityByProvince = this.cityService.findCityByProvinceCode("Guangdong");
                        log.info("----------");
                        log.info(new Gson().toJson(listCityByProvince));
                        log.info("广东省城市总数："+String.valueOf(listCityByProvince.size()));
                        log.info("和风天气省份和城市数据同步成功");
                    }
                } else {
                    log.info("文件不存在");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    /**
     * @date 2022-03-16 09:41
     * @description: 定时任务, 从和风天气平台 调用api 天气预报-实时天气 获取实时天气预报，OkHttpClient异步获取，工具类封装网络请求
     * @Param: null
     */
    //@Scheduled(cron = "0 0 10,14,18,20,22 * * *")//每天10，14，18，20，22点各执行一次，一天总共执行五次
    //@Scheduled(cron = "0 0 0,8,12,16 * * *")//每天0，8，12，16点各执行一次，一天总共执行四次
    @Scheduled(cron = "0 15 * * * *")//每个小时执行一次
    public void scheduledGetRealtimeWeather() {
        log.info("scheduledGetRealtimeWeather");
        log.info("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        //广东省惠州市惠阳
        String locationNameEn_Huiyang = "Huiyang";
        this.hefengWeatherService.saveHefengWeatherByLocationNameEn(locationNameEn_Huiyang);
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 定时任务, 从和风天气平台 调用api 天气预报-每日天气预报 获取7天天气预报
     * @Param: null
     */
    //@Scheduled(cron = "0 0 9 * * *")//每天9点执行一次
    @Scheduled(cron = "0 15 * * * *")//每个小时执行一次
    public void scheduledGetForecastWeather() {
        log.info("scheduledGetForecastWeather");
        log.info("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        //广东省惠州市惠阳
        String locationNameEn_Huiyang = "Huiyang";
        this.hefengWeatherService.saveHefengFutureWeatherByLocationNameEn(locationNameEn_Huiyang);
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 定时任务, 从和风天气获取城市列表
     * @Param: null
     */
    //@Scheduled(cron = "*/5 * * * * *")//每天0，8，16点各执行一次，一天总共执行三次
    public void getCityList() {
        log.info("scheduledGetWeather");
        log.info("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        try {
            String url = "http://192.168.1.18:8080/jpahefengweather/weather/getCityList";
            // 初始化 OkHttpClient
            OkHttpClient client = new OkHttpClient();
            // 初始化请求体
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            //log.info(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 定时任务, 从和风天气获取实时天气预报，OkHttpClient同步获取
     * @Param: null
     */
    //@Scheduled(cron = "*/10 * * * * *")//每天0，8，16点各执行一次，一天总共执行三次
    public void getNowWeatherEntity() {
        log.info("scheduledGetWeather");
        log.info("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        try {
            String url = "http://192.168.1.18:8080/jpahefengweather/weather/getNowWeatherEntity";
            // 初始化 OkHttpClient
            //OkHttpClient client = new OkHttpClient();
            // 初始化 OkHttpClient
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .build();
            Map<String, String> param = new HashMap();
            String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            param.put("weatherDate", now);
            param.put("locationId", "101010100");
            Gson gson = new Gson();
            MediaType JSON = MediaType.parse("application/json;charset=utf-8");
            RequestBody requestBody = RequestBody.create(JSON, gson.toJson(param));
            //请求参数体
            RequestBody requestBody1 = new FormBody.Builder()
                    .add("weatherDate", now)
                    .add("locationId", "101010100")
                    .build();
            // 初始化请求体
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .build();
            // 得到返回Response
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            log.info(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 定时任务, 从和风天气获取实时天气预报,OkHttpClient异步获取
     * @Param: null
     */
    //@Scheduled(cron = "*/10 * * * * *")//每天0，8，16点各执行一次，一天总共执行三次
    public void getNowWeatherDto() {
        log.info("scheduledGetWeather");
        log.info("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String url = "http://192.168.1.18:8080/jpahefengweather/weather/getNowWeatherDto";
        // 初始化 OkHttpClient
        //OkHttpClient client = new OkHttpClient();
        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        Map<String, String> param = new HashMap();
        String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        param.put("weatherDate", now);
        param.put("locationId", "101010100");
        Gson gson = new Gson();
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, gson.toJson(param));
        //请求参数体
        RequestBody requestBody1 = new FormBody.Builder()
                .add("weatherDate", now)
                .add("locationId", "101010100")
                .build();
        // 初始化请求体
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        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();
                log.info(body);
            }
        });
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 定时任务, 获取本地保存的实时天气预报，只获取最新一条数据
     * @Param: null
     */
    //@Scheduled(cron = "*/10 * * * * *")//每天0，8，16点各执行一次，一天总共执行三次
    public void getNowWeatherDtoOne() {
        log.info("scheduledGetWeather");
        log.info("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String url = "http://192.168.1.18:8080/jpahefengweather/weather/getNowWeatherDtoOne";
        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        Map<String, String> param = new HashMap();
        String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        param.put("weatherDate", now);
        param.put("locationId", "101010100");
        Gson gson = new Gson();
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, gson.toJson(param));
        //请求参数体
        RequestBody requestBody1 = new FormBody.Builder()
                .add("weatherDate", now)
                .add("locationId", "101010100")
                .build();
        //post方式提交的数据
        FormBody formBody = new FormBody.Builder()
                .add("name", "android基础")
                .add("price", "50")
                .build();
        // 初始化请求体
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        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();
                log.info(body);
            }
        });
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 定时任务, 从本地获取天气预报
     * @Param: null
     */
    //@Scheduled(cron = "0 15 * * * *")//每天0，8，16点各执行一次，一天总共执行三次
    public void getForecastWeatherDto() {
        log.info("scheduledGetWeather");
        log.info("=====>>>>>使用cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String url = "http://192.168.1.18:8080/jpahefengweather/weather/getForecastWeatherDto";
        // 初始化 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        Map<String, String> param = new HashMap();
        String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        param.put("weatherDate", now);
        param.put("locationId", "101010100");
        Gson gson = new Gson();
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, gson.toJson(param));
        // 初始化请求体
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        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();
                log.info(body);
            }
        });
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 获取本地保存的和风天气平台，实时天气和天气预报
     * @Param: null
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void getLocalNowWeatherDto() {
        log.info("getLocalNowWeatherDto");
        String strNow = String.valueOf(System.currentTimeMillis());
        log.info(strNow);
        BaseFindDto dto = new BaseFindDto();
        dto.setLocationId("101280303");
        String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        HefengWeatherResultDto hefengWeatherResultDto=this.hefengWeatherService.getHefengWeatherResultDtoByLocationIdAndDateDto(dto.getLocationId(),currentDate);
        log.info("-----------和风天气获取实时天气和天气预报完成------------");
        log.info(new Gson().toJson(hefengWeatherResultDto));
    }

    /**
     * @date 2022-03-16 09:41
     * @description: 获取本地保存的和风天气平台，天气预报
     * @Param: null
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void getLocalForecastWeatherDto() {
        log.info("getLocalForecastWeatherDto");
        String strNow = String.valueOf(System.currentTimeMillis());
        log.info(strNow);
        String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        BaseFindDto dto = new BaseFindDto();
        dto.setLocationId("101280303");
        List<ForecastWeatherDto> forecastWeatherDtoList=this.hefengWeatherService.findForecastWeatherByLocationIdAndDateDto(dto.getLocationId(),currentDate);
        log.info(new Gson().toJson(forecastWeatherDtoList));
    }
}