package com.gyee.frame.service.weather;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.gyee.frame.common.conf.V2Config;
import com.gyee.frame.model.auto.Weatherfd;
import com.gyee.frame.model.auto.WeatherfdExample;
import com.gyee.frame.model.auto.Windpowerstation;
import com.gyee.frame.model.auto.WindpowerstationExample;
import com.gyee.frame.model.custom.weather.*;
import com.gyee.frame.service.WeatherfdService;
import com.gyee.frame.service.WindpowerstationService;
import com.gyee.frame.util.DateUtils;
import com.gyee.frame.util.StringUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Service
public class WeatherParsing {

    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private WindpowerstationService windpowerstationService;

    @Autowired
    private WeatherfdService weatherfdService;

    /**
     * 定时获取预测天气
     */
    //@Scheduled(cron = "0 20 1 * * ?")
    //@Scheduled(fixedRate = 15000)
    public void getWeatherDay5() {

        WindpowerstationExample example = new WindpowerstationExample();
        example.createCriteria().andIdLike("%FDC%");
        example.setOrderByClause("ordernum ASC");
        List<Windpowerstation> list = windpowerstationService.selectByExample(example);

        for (Windpowerstation w : list) {
            StringBuilder sb = new StringBuilder();
            sb.append(V2Config.getWeatherurl()).append("/meteorological/datas");
            sb.append("?wpid=").append(w.getCode());
            sb.append("&model=").append("forecast");
            String url = String.valueOf(sb);
            ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
            String weatherStr = resp.getBody().toJSONString();
            try {
                JsonRootBean jsonRootBean = JSONObject.parseObject(weatherStr, new TypeReference<JsonRootBean>() {
                });

                if (StringUtils.notEmp(jsonRootBean)) {
                    long e = 0L;
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    com.gyee.frame.model.custom.weather.List neww = null;
                    if (null != jsonRootBean && null != jsonRootBean.getList() && !jsonRootBean.getList().isEmpty()) {
                        List<Weatherfd> fds = new ArrayList<>();
                        for (com.gyee.frame.model.custom.weather.List weatherReal : jsonRootBean.getList()) {
                            Map<String, Object> map = new HashMap<>();
                            Calendar cal = Calendar.getInstance();
                            cal.setTimeInMillis(weatherReal.getDt() * 1000);
                            long beginDate = cal.getTimeInMillis();
                            cal.set(Calendar.HOUR_OF_DAY, 0);
                            cal.set(Calendar.MINUTE, 0);
                            cal.set(Calendar.SECOND, 0);
                            cal.set(Calendar.MILLISECOND, 0);
                            cal.add(Calendar.DAY_OF_MONTH, 1);
                            long endDate = cal.getTimeInMillis();
                            long c = (endDate - beginDate) / (1000 * 3600);
//                            System.out.println(df.format(beginDate));
//                            System.out.println(df.format(endDate));
                            if (c / 3 != 6 && c / 3 != 3) {
                                continue;
                            }
                            System.out.println(c / 3);//

                            if (c / 3 == 6) {
                                neww = weatherReal;
                            }
                            if (c / 3 == 3 && null != neww) {
                                Weatherfd fd = new Weatherfd();
                                fd.setRecodedata(DateUtils.parseStrtoDate(DateUtils.format(beginDate, DateUtils.DATE_TIME_PATTERN)));
                                fd.setRegion(w.getName());
                                fd.setWindpowerstationid(w.getId());
                                fd.setWeather(getIcon(weatherReal).get("tqmc").toString());
                                if (null != weatherReal.getMain()) {
                                    Main main = weatherReal.getMain();
                                    //最高气温
                                    fd.setMaximumtem(main.getTemp());
                                    fd.setTemperature1(main.getTemp());//白天气温
                                    fd.setRealfeel1(main.getTemp() + 5);//白天体感温度
                                }
                                if (null != neww.getMain()) {
                                    Main main = neww.getMain();
                                    //最低气温
                                    fd.setMinimumtem(main.getTemp());
                                    fd.setTemperature2(main.getTemp());//夜间气温
                                    fd.setRealfeel2(main.getTemp() + 5);//夜间体感温度
                                }
                                fd.setSunrise("05:56");//日出时间
                                fd.setSunset("20:05");//日落时间
                                fd.setSunduration(9.00);//持续时长
                                fd.setWeather1(getIcon(weatherReal).get("tqmc").toString());//白气象
                                fd.setWeather2(getIcon(neww).get("tqmc").toString());//夜气象
                                fd.setPrecipitation1(0.00);//白天降水
                                fd.setPrecipitation2(0.00);//夜间降雨

                                if (null != weatherReal.getWind()) {
                                    Wind wind = weatherReal.getWind();
                                    map.put("fs", wind.getSpeed());
                                    fd.setSpeed1(wind.getSpeed());//白天风速
                                    fd.setGust1(wind.getSpeed() + 3);//白天阵风风速
                                    //白天风向
                                    if (StringUtils.notEmp(wind.getDeg())) {
                                        double fx = wind.getDeg();
                                        if (fx >= 11.25 && fx <= 348.76) {
                                            fd.setWinddirection1("北");
                                        } else if (fx >= 33.76 && fx <= 56.25) {
                                            fd.setWinddirection1("东北");
                                        } else if (fx >= 78.76 && fx <= 101.25) {
                                            fd.setWinddirection1("东");
                                        } else if (fx >= 123.76 && fx <= 146.25) {
                                            fd.setWinddirection1("东南");
                                        } else if (fx >= 168.76 && fx <= 191.25) {
                                            fd.setWinddirection1("南");
                                        } else if (fx >= 213.76 && fx <= 236.25) {
                                            fd.setWinddirection1("西南");
                                        } else if (fx >= 258.76 && fx <= 281.25) {
                                            fd.setWinddirection1("西");
                                        } else if (fx >= 303.76 && fx <= 326.25) {
                                            fd.setWinddirection1("西北");
                                        }
                                    }
                                }

                                if (null != neww.getWind()) {
                                    Wind wind = neww.getWind();
                                    fd.setSpeed2(wind.getSpeed());//白天风速
                                    fd.setGust2(wind.getSpeed() + 3);//白天阵风风速

                                    //白天风向
                                    if (StringUtils.notEmp(wind.getDeg())) {
                                        double fx = wind.getDeg();
                                        if (fx >= 11.25 && fx <= 348.76) {
                                            fd.setWinddirection2("北");
                                        } else if (fx >= 33.76 && fx <= 56.25) {
                                            fd.setWinddirection2("东北");
                                        } else if (fx >= 78.76 && fx <= 101.25) {
                                            fd.setWinddirection2("东");
                                        } else if (fx >= 123.76 && fx <= 146.25) {
                                            fd.setWinddirection2("东南");
                                        } else if (fx >= 168.76 && fx <= 191.25) {
                                            fd.setWinddirection2("南");
                                        } else if (fx >= 213.76 && fx <= 236.25) {
                                            fd.setWinddirection2("西南");
                                        } else if (fx >= 258.76 && fx <= 281.25) {
                                            fd.setWinddirection2("西");
                                        } else if (fx >= 303.76 && fx <= 326.25) {
                                            fd.setWinddirection2("西北");
                                        }
                                    }
                                }
                                e = weatherReal.getDt() * 1000;//记录实际预测的日期

                                //判断实际预测日期的是否存在
                                WeatherfdExample wexample = new WeatherfdExample();
                                wexample.createCriteria().andRecodedataEqualTo(DateUtils.parseStrtoDate(DateUtils.format(fd.getRecodedata(), DateUtils.DATE_PATTERN)))
                                        .andWindpowerstationidEqualTo(w.getId());
                                List<Weatherfd> weatherfds = weatherfdService.selectByExample(wexample);


                                //如果存在更新，负责新增一条记录
                                if (weatherfds != null && weatherfds.size() > 0){
                                    System.out.println("存在"+weatherfds.get(0).getId());//
                                    fd.setId(weatherfds.get(0).getId());
                                    weatherfdService.updateByPrimaryKeySelective(fd);
                                }else{
                                    weatherfdService.insertSelective(fd);
                                    System.out.println("不存在");//
                                }


                                //fds.add(fd);
                            }
                        }

                        //System.out.println(fds.size()+"eeeeeeeeeeeeeeeee" + df.format(e));

                        //填补后一个月的预测数据
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(new Date());
                        cal.add(Calendar.MONTH, +1);//设置获取1个月后的时间
                        long prDate = cal.getTimeInMillis();
                        System.out.println(df.format(prDate));//
                        long prday =  (prDate - e) /(1000 * 3600 * 24);//计算需要填补预测天气的天数
                        long nextday = e;
                        for (int i = 0;i<prday;i++){//循环添加需要预测的天气记录
                             cal.setTimeInMillis(nextday);
                             cal.add(Calendar.DATE, +1);// 日期加1
                            nextday = cal.getTimeInMillis();//获取到下一个预测日期
                            System.out.println(df.format(nextday));//


                            //判断该预测日期是否存在记录
                            WeatherfdExample wexample = new WeatherfdExample();
                            wexample.createCriteria().andRecodedataEqualTo(DateUtils.parseStrtoDate(DateUtils.format(cal.getTime(), DateUtils.DATE_PATTERN)))
                                    .andWindpowerstationidEqualTo(w.getId());
                            List<Weatherfd> weatherfds = weatherfdService.selectByExample(wexample);

                            //如果需要补充的预测记录存在，则跳过
                            if (null == weatherfds  || weatherfds.size() <= 0){
                                cal.add(Calendar.YEAR, -1); // 年份减1
                                long ori = cal.getTimeInMillis();//获取到上一年的预测天气日期
                                System.out.println(df.format(ori));//
                                //获取到上一年同期的天气记录
                                wexample = new WeatherfdExample();
                                wexample.createCriteria().andRecodedataEqualTo(DateUtils.parseStrtoDate(DateUtils.format(cal.getTime(), DateUtils.DATE_PATTERN)))
                                        .andWindpowerstationidEqualTo(w.getId());
                                List<Weatherfd> oriweatherfds = weatherfdService.selectByExample(wexample);

                                //将上一期的天气填充到需要
                                cal.add(Calendar.YEAR, +1); // 年份加1，
                                Weatherfd orifd = oriweatherfds.get(0);
                                orifd.setId(null);
                                orifd.setRecodedata(DateUtils.parseStrtoDate(DateUtils.format(cal.getTime(), DateUtils.DATE_PATTERN)));
                                weatherfdService.insertSelective(orifd);
                                System.out.println("不存在");//
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public void getWeatherDay1() {
        ResponseEntity<JSONObject> resp = restTemplate.getForEntity("http://10.155.32.59:7011/meteorological/datas?wpid=sbq_fdc&model=weather", JSONObject.class);
        String weatherStr = resp.getBody().toJSONString();

        WeatherReal weatherReal = JSONObject.parseObject(weatherStr, new TypeReference<WeatherReal>() {
        });
    }


    private Map getIcon(com.gyee.frame.model.custom.weather.List weatherReal) {
        Map map = new HashedMap();

        if (null != weatherReal.getWeather() && !weatherReal.getWeather().isEmpty()) {
            Weather weather = weatherReal.getWeather().get(0);

            String icon = weather.getIcon();

            if (StringUtils.notEmp(icon)) {
                if (icon.equals("01d") || icon.equals("01n")) {
                    map.put("tqmc", "晴");
                    map.put("tqtp", "01");
                } else if (icon.equals("02d") || icon.equals("02n")) {
                    map.put("tqmc", "少云");
                    map.put("tqtp", "02");
                } else if (icon.equals("03d") || icon.equals("03n")) {
                    map.put("tqmc", "多云");
                    map.put("tqtp", "06");
                } else if (icon.equals("04d") || icon.equals("04n")) {
                    map.put("tqmc", "阴");
                    map.put("tqtp", "07");
                } else if (icon.equals("09d") || icon.equals("09n")) {
                    map.put("tqmc", "阵雨");
                    map.put("tqtp", "13");
                } else if (icon.equals("10d") || icon.equals("10n")) {
                    map.put("tqmc", "雨");
                    map.put("tqtp", "18");
                } else if (icon.equals("11d") || icon.equals("11n")) {
                    map.put("tqmc", "雷雨");
                    map.put("tqtp", "15");
                } else if (icon.equals("13d") || icon.equals("13n")) {
                    map.put("tqmc", "雪");
                    map.put("tqtp", "19");
                } else if (icon.equals("50d") || icon.equals("50n")) {
                    map.put("tqmc", "雾");
                    map.put("tqtp", "32");
                } else {
                    map.put("tqmc", "晴");
                    map.put("tqtp", "01");
                }

            }
        }
        return map;

    }

}
