package com.rehome.jpahefengweather.service.Impl;


import com.google.gson.Gson;
import com.rehome.jpahefengweather.dao.ForecastWeatherRepository;
import com.rehome.jpahefengweather.dao.HefengFutureWeatherRepository;
import com.rehome.jpahefengweather.dao.HefengRealtimeWeatherRepository;
import com.rehome.jpahefengweather.dao.NowWeatherRepository;
import com.rehome.jpahefengweather.dto.*;
import com.rehome.jpahefengweather.entity.*;
import com.rehome.jpahefengweather.service.CityService;
import com.rehome.jpahefengweather.service.HefengWeatherService;
import com.rehome.jpahefengweather.utils.OkHttpUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class HefengWeatherServiceImpl implements HefengWeatherService {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private NowWeatherRepository nowWeatherRepository;
    @Resource
    private ForecastWeatherRepository forecastWeatherRepository;
    @Resource
    private HefengRealtimeWeatherRepository hefengRealtimeWeatherRepository;
    @Resource
    private HefengFutureWeatherRepository hefengFutureWeatherRepository;

    @Resource
    private CityService cityService;


    @Override
    public List<NowWeather> findNowWeatherByLocationIdAndDate(String locationId, String date) {
        return this.nowWeatherRepository.findByLocationIdAndWeatherDateOrderByIdDesc(locationId,date);
    }

    @Override
    public List<NowWeather> findNowWeatherByLocationIdAndDateOrderByCreateDateDesc(String locationId, String date) {
        return this.nowWeatherRepository.findByLocationIdAndWeatherDateOrderByIdDesc(locationId,date);
    }

    @Override
    public void saveNowWeather(NowWeather nowWeather) {
        this.nowWeatherRepository.save(nowWeather);
    }

    @Override
    public void saveHefengWeatherByLocationNameEn(String locationNameEn) {
        List<HefengCity> cityList = this.cityService.findByLocationNameEn(locationNameEn);
        log.info(new Gson().toJson(cityList));
        log.info("查询实时天气总数："+String.valueOf(cityList.size()));
        if (cityList != null && cityList.size() > 0) {
            Date now = new Date();
            log.info(String.valueOf(cityList.size()));
            for (int i = 0; i < cityList.size(); i++) {
                HefengCity city = cityList.get(i);
                Map<String, String> params = new HashMap<>();
                //我的帐号: c67db396fcdb416c959933d29e30db3d
                //克金帐号: 3522d7d5736947d7a63e8d7d95316406
                //params.put("key", "c67db396fcdb416c959933d29e30db3d");
                params.put("location", city.getLocationId());
                String realtimeWeatherData = OkHttpUtil.get("https://m573jftdb9.re.qweatherapi.com/v7/weather/now", params);
                log.info(realtimeWeatherData);
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (realtimeWeatherData!=null&&realtimeWeatherData.trim().length()>0) {
                    SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
                    SimpleDateFormat sdfYearMonth = new SimpleDateFormat("yyyy-MM");
                    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
                    NowWeather nowWeather = new NowWeather();
                    nowWeather.setWeatherDate(sdfDate.format(now));
                    nowWeather.setLocationId(city.getLocationId());
                    nowWeather.setWeather(realtimeWeatherData);
                    nowWeather.setCreateDate(now);
                    nowWeather.setLastUpdateDate(now);
                    nowWeather.setProvince(city.getAdm1NameZh());
                    nowWeather.setCity(city.getAdm2NameZh());
                    nowWeather.setLocationNameZh(city.getLocationNameZh());
                    this.saveNowWeather(nowWeather);

                    Gson gson = new Gson();
                    HefengRealtimeWeatherDto hefengRealtimeWeatherDto = gson.fromJson(realtimeWeatherData,HefengRealtimeWeatherDto.class);
                    if((!ObjectUtils.isEmpty(hefengRealtimeWeatherDto))&&"200".equals(hefengRealtimeWeatherDto.getCode())){
                        log.info("----------");
                        log.info(gson.toJson(hefengRealtimeWeatherDto));
                        HefengRealtimeWeather realtimeWeather = hefengRealtimeWeatherDto.getNow();
                        if(!ObjectUtils.isEmpty(realtimeWeather)){
                            realtimeWeather.setLocationId(city.getLocationId());
                            realtimeWeather.setProvince(city.getAdm1NameZh());
                            realtimeWeather.setCity(city.getAdm2NameZh());
                            realtimeWeather.setLocationNameZh(city.getLocationNameZh());
                            realtimeWeather.setCreateTime(now);

                            realtimeWeather.setFxLink(hefengRealtimeWeatherDto.getFxLink());
                            realtimeWeather.setYear(sdfYear.format(now));
                            realtimeWeather.setYearAndMonth(sdfYearMonth.format(now));
                            realtimeWeather.setDate(sdfDate.format(now));
                            hefengRealtimeWeatherRepository.save(realtimeWeather);
                        }
                    }
                } else {
                    log.info("-->");
                }
            }
        }
    }

    @Override
    public void saveHefengFutureWeatherByLocationNameEn(String locationNameEn) {
        List<HefengCity> cityList = this.cityService.findByLocationNameEn(locationNameEn);
        log.info(new Gson().toJson(cityList));
        log.info("查询天气预报总数："+String.valueOf(cityList.size()));
        if (cityList != null && cityList.size() > 0) {
            Date now = new Date();
            log.info(String.valueOf(cityList.size()));
            for (int i = 0; i < cityList.size(); i++) {
                HefengCity city = cityList.get(i);
                Map<String, String> params = new HashMap<>();
                //c67db396fcdb416c959933d29e30db3d
                //params.put("key", "c67db396fcdb416c959933d29e30db3d");
                params.put("location", city.getLocationId());
                String futureWeatherData = OkHttpUtil.get("https://m573jftdb9.re.qweatherapi.com/v7/weather/7d", params);
                log.info(futureWeatherData);
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (futureWeatherData!=null&&futureWeatherData.trim().length()>0) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    ForecastWeather forecastWeather = new ForecastWeather();
                    forecastWeather.setWeatherDate(sdf.format(now));
                    forecastWeather.setLocationId(city.getLocationId());
                    forecastWeather.setWeather(futureWeatherData);
                    forecastWeather.setLastUpdateDate(now);
                    forecastWeather.setCreateDate(now);
                    forecastWeather.setProvince(city.getAdm1NameZh());
                    forecastWeather.setCity(city.getAdm2NameZh());
                    forecastWeather.setLocationNameZh(city.getLocationNameZh());
                    this.saveForecastWeather(forecastWeather);

                    Gson gson = new Gson();
                    HefengFutureWeatherDto hefengFutureWeatherDto = gson.fromJson(futureWeatherData, HefengFutureWeatherDto.class);
                    if((!ObjectUtils.isEmpty(hefengFutureWeatherDto))&&"200".equals(hefengFutureWeatherDto.getCode())){
                        log.info("----------");
                        log.info(gson.toJson(hefengFutureWeatherDto));
                        List<HefengFutureWeather> dailyHefengFutureWeather = hefengFutureWeatherDto.getDaily();
                        if(!ObjectUtils.isEmpty(dailyHefengFutureWeather)){
                            for(HefengFutureWeather daily:dailyHefengFutureWeather){
                                HefengFutureWeather dailyDB = this.hefengFutureWeatherRepository.findByLocationIdAndFxDate(city.getLocationId(),daily.getFxDate());
                                if(dailyDB==null){
                                    daily.setLocationId(city.getLocationId());
                                    daily.setProvince(city.getAdm1NameZh());
                                    daily.setCity(city.getAdm2NameZh());
                                    daily.setLocationNameZh(city.getLocationNameZh());
                                    daily.setCreateTime(now);

                                    daily.setUpdateTime(now);
                                    daily.setFxLink(hefengFutureWeatherDto.getFxLink());
                                    hefengFutureWeatherRepository.save(daily);
                                    log.info("-----和风天气预报数据保存成功-----");
                                    log.info(gson.toJson(daily));
                                }else{
                                    daily.setId(dailyDB.getId());
                                    daily.setLocationId(city.getLocationId());
                                    daily.setProvince(city.getAdm1NameZh());
                                    daily.setCity(city.getAdm2NameZh());
                                    daily.setLocationNameZh(city.getLocationNameZh());

                                    daily.setCreateTime(dailyDB.getCreateTime());
                                    daily.setUpdateTime(now);
                                    daily.setFxLink(hefengFutureWeatherDto.getFxLink());
                                    hefengFutureWeatherRepository.save(daily);
                                    log.info("-----和风天气预报数据更新成功-----");
                                    log.info(gson.toJson(daily));
                                }
                            }
                        }
                    }
                } else {
                    log.info("-->");
                }
            }
        }
    }

    @Override
    public List<ForecastWeather> findForecastWeatherByLocationIdAndDate(String locationId, String date) {
        return this.forecastWeatherRepository.findByLocationIdAndWeatherDate(locationId,date);
    }

    @Override
    public List<ForecastWeather> findForecastWeatherByLocationIdAndDateOrderByCreateDateDesc(String locationId, String date) {
        return this.forecastWeatherRepository.findByLocationIdAndWeatherDateOrderByIdDesc(locationId,date);
    }

    @Override
    public void saveForecastWeather(ForecastWeather forecastWeather) {
        this.forecastWeatherRepository.save(forecastWeather);
    }

    @Override
    public NowWeatherDto findNowWeatherByLocationIdAndDateDto(String locationId) {
        SimpleDateFormat sdFormat=new SimpleDateFormat("yyyy-MM-dd");
        String now = sdFormat.format(new Date());
        List<NowWeather> nowWeatherList = this.nowWeatherRepository.findByLocationIdAndWeatherDateOrderByIdDesc(locationId,now);
        if(nowWeatherList!=null&&nowWeatherList.size()>0){
            NowWeather nowWeather=nowWeatherList.get(0);
            Gson gson = new Gson();
            NowWeatherDto nowWeatherDto = gson.fromJson(nowWeather.getWeather(),NowWeatherDto.class);
            return nowWeatherDto;
        }
        return null;
    }

    @Override
    public List<NowWeatherDto> findHistoryWeatherByLocationIdAndDateDto(String locationId, String date) {
        List<NowWeather> weathers = this.findNowWeatherByLocationIdAndDateOrderByCreateDateDesc(locationId,date);
        if(weathers!=null&&weathers.size()>0){
            List<NowWeatherDto> dtos = new ArrayList<>();
            for (NowWeather weather:weathers) {
                Gson gson = new Gson();
                NowWeatherDto nowWeatherDto = gson.fromJson(weather.getWeather(),NowWeatherDto.class);
                dtos.add(nowWeatherDto);
            }
            return dtos;
        }
        return new ArrayList<>();
    }

    @Override
    public List<ForecastWeatherDto> findForecastWeatherByLocationIdAndDateDto(String locationId, String date) {
        List<ForecastWeather> weathers = this.findForecastWeatherByLocationIdAndDateOrderByCreateDateDesc(locationId,date);
        if(weathers!=null&&weathers.size()>0){
            List<ForecastWeatherDto> dtos = new ArrayList<>();
            for (ForecastWeather weather:weathers) {
                Gson gson = new Gson();
                ForecastWeatherDto forecastWeatherDto = gson.fromJson(weather.getWeather(),ForecastWeatherDto.class);
                dtos.add(forecastWeatherDto);
            }
            return dtos;
        }
        return new ArrayList<>();
    }

    @Override
    public HefengWeatherResultDto getHefengWeatherResultDtoByLocationIdAndDateDto(String locationId, String date) {
        NowWeatherDto nowWeatherDto=this.findNowWeatherByLocationIdAndDateDto(locationId);
        //System.out.println(new Gson().toJson(nowWeatherDto));
        if(nowWeatherDto!=null){
            Gson gson = new Gson();
            String nowWeatherDtoStr = gson.toJson(nowWeatherDto);
            HefengWeatherResultDto hefengWeatherResultDto=gson.fromJson(nowWeatherDtoStr,HefengWeatherResultDto.class);
            //System.out.println("-----------hefengWeatherResultDto------------");
            //System.out.println(new Gson().toJson(hefengWeatherResultDto));

            List<ForecastWeatherDto> forecastWeatherDtoList=this.findForecastWeatherByLocationIdAndDateDto(locationId,date);
            //System.out.println(new Gson().toJson(forecastWeatherDtoList));

            if(forecastWeatherDtoList!=null&&forecastWeatherDtoList.size()>0){
                String futureWeatherData = gson.toJson(forecastWeatherDtoList.get(0));
                HefengFutureWeatherDto hefengFutureWeatherDto = gson.fromJson(futureWeatherData, HefengFutureWeatherDto.class);
                if(hefengFutureWeatherDto!=null){
                    hefengWeatherResultDto.setDaily(hefengFutureWeatherDto.getDaily());
                    return hefengWeatherResultDto;
                }
            }
        }
        return null;
    }
}