package com.gyee.frame.service.weather;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gyee.frame.common.cache.RedisUtils;
import com.gyee.frame.common.conf.V2Config;
import com.gyee.frame.common.spring.InitialRunner;
import com.gyee.frame.mapper.auto.WeatherfdMapper;
import com.gyee.frame.model.auto.*;
import com.gyee.frame.model.custom.Tablepar;
import com.gyee.frame.model.custom.weather.*;
import com.gyee.frame.service.WeatherfdService;
import com.gyee.frame.util.MathUtil;
import com.gyee.frame.util.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


@Service
public class WeatherService {

    private RestTemplate restTemplate = new RestTemplate();
    private final Integer DATABASE = 2;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private WeatherfdService weatherfdService;

    public Map<String, Object> getWeatherRealInfo(String id) {
        try {

            Map<String, Object> map = new HashMap<>();

            if (StringUtils.notEmp(id)) {

                if (InitialRunner.wpmap.containsKey(id)) {
                    Windpowerstation wp = InitialRunner.wpmap.get(id);

                    id = wp.getId();


                } else if (InitialRunner.pjmap.containsKey(id)) {
                    Project pj = InitialRunner.pjmap.get(id);
                    Windpowerstation wp = InitialRunner.wpmap.get(pj.getWindpowerstationid());
                    id = wp.getId();
                } else if (InitialRunner.lnmap.containsKey(id)) {
                    Line ln = InitialRunner.lnmap.get(id);
                    Project pj = InitialRunner.pjmap.get(ln.getProjectid());
                    Windpowerstation wp = InitialRunner.wpmap.get(pj.getWindpowerstationid());
                    id = wp.getId();
                }

                String weatherStr = null;
                WeatherReal weatherReal = null;
                // weather,forecast,onecall

                try {


                    StringBuilder sb = new StringBuilder();
                    sb.append(V2Config.getWeatherurl()).append("/meteorological/datas?");
                    if (id.equals("0") || id.equals("-1") || id.equals("-2")) {
                        sb.append("&wpid=").append(V2Config.getWeatherqygs());
                    } else {
                        sb.append("&wpid=").append(id);
                    }
                    sb.append("&model=weather");

                    String url = String.valueOf(sb);

                    ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                    weatherStr = resp.getBody().toJSONString();

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


                } catch (HttpClientErrorException exception) {

                }


                if (InitialRunner.wpmap.containsKey(id)) {
                    Windpowerstation wp = InitialRunner.wpmap.get(id);
                    if (wp.getName().indexOf("风电场") != -1) {
                        String name = wp.getName().substring(0, wp.getName().indexOf("风电场"));
                        map.put("name", name);
                    } else if (wp.getName().indexOf("光电场") != -1) {
                        String name = wp.getName().substring(0, wp.getName().indexOf("光电场"));
                        map.put("name", name);
                    }

                } else {
                    map.put("name", "银川");
                }

	/*		switch(id) {
				case "0" :
					map.put("name","银川");
					weatherStr = redisUtils.get("NX_QYGS_WEATHER_WEATHER",DATABASE);
					break;
				case "-1" :
					map.put("name","银川");
					weatherStr = redisUtils.get("NX_QYGS_WEATHER_WEATHER",DATABASE);
					break;
				case "-2" :
					map.put("name","银川");
					weatherStr = redisUtils.get("NX_QYGS_WEATHER_WEATHER",DATABASE);
					break;
				case "MHS_FDC" :
					map.put("name","麻黄山");
					weatherStr = redisUtils.get("MHS_FDC_WEATHER_WEATHER",DATABASE);
					break;
				case "NSS_FDC" :
					map.put("name","牛首山");
					weatherStr = redisUtils.get("NSS_FDC_WEATHER_WEATHER",DATABASE);
					break;
				case "QS_FDC" :
					map.put("name","青山");
					weatherStr = redisUtils.get("QS_FDC_WEATHER_WEATHER",DATABASE);
					break;
				case "SBQ_FDC" :
					map.put("name","石板泉");
					weatherStr = redisUtils.get("SBQ_FDC_WEATHER_WEATHER",DATABASE);
					break;
				case "XS_FDC" :
					map.put("name","香山");
					weatherStr = redisUtils.get("XS_FDC_WEATHER_WEATHER",DATABASE);
					break;
				case "DWK_GDC" :
					map.put("name","大武口");
					weatherStr = redisUtils.get("DWK_GDC_WEATHER_WEATHER",DATABASE);
					break;
				case "PL_GDC" :
					map.put("name","平罗");
					weatherStr = redisUtils.get("PL_GDC_WEATHER_WEATHER",DATABASE);
					break;
				case "XH_GDC" :
					map.put("name","宣和");
					weatherStr = redisUtils.get("XH_GDC_WEATHER_WEATHER",DATABASE);
					break;
				case "MCH_GDC" :
					map.put("name","马场湖");
					weatherStr = redisUtils.get("MCH_GDC_WEATHER_WEATHER",DATABASE);
					break;
				case "HZJ_GDC" :
					map.put("name","海子井");
					weatherStr = redisUtils.get("HZJ_GDC_WEATHER_WEATHER",DATABASE);
					break;
				default:
					break;
			}*/


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


                    double qxd = weatherReal.getVisibility();
                    //清晰度
                    map.put("qxd", MathUtil.twoBit(qxd / 1000));

                    if (null != weatherReal.getMain()) {
                        Main main = weatherReal.getMain();
                        //温度
                        map.put("wd", main.getTemp());
                        //大气压强
                        map.put("dqyl", main.getPressure());
                        //湿度
                        map.put("sd", main.getHumidity());

                    }

                    if (null != weatherReal.getCoord()) {
                        Coord coord = weatherReal.getCoord();
                        //经度
                        map.put("jingdu", coord.getLon());
                        //维度
                        map.put("weidu", coord.getLat());
                    }

                    if (null != weatherReal.getClouds()) {
                        Clouds clouds = weatherReal.getClouds();
                        //云量
                        map.put("yunliang", clouds.getAll());
                    }

                    if (null != weatherReal.getSys()) {
                        Sys sys = weatherReal.getSys();
                        if (StringUtils.notEmp(sys.getSunrise())) {
                            Date date = new Date(sys.getSunrise() * 1000);
                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            //日出时间
                            map.put("richushijian", sdf.format(date));

                        }
                        if (StringUtils.notEmp(sys.getSunset())) {
                            Date date = new Date(sys.getSunset() * 1000);
                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            //日落时间
                            map.put("riluoshijian", sdf.format(date));
                        }
                    }

                    if (null != weatherReal.getWind()) {
                        Wind wind = weatherReal.getWind();
                        //风速
                        map.put("fs", wind.getSpeed());

                        if (StringUtils.notEmp(wind.getDeg())) {
                            double fx = wind.getDeg();
                            if (fx <= 11.25 || fx >= 348.76) {
                                //风向
                                map.put("fx", "北");
                            } else if (fx >= 33.76 && fx <= 56.25) {
                                map.put("fx", "东北");
                            } else if (fx >= 78.76 && fx <= 101.25) {
                                map.put("fx", "东");
                            } else if (fx >= 123.76 && fx <= 146.25) {
                                map.put("fx", "东南");
                            } else if (fx >= 168.76 && fx <= 191.25) {
                                map.put("fx", "南");
                            } else if (fx >= 213.76 && fx <= 236.25) {
                                map.put("fx", "西南");
                            } else if (fx >= 258.76 && fx <= 281.25) {
                                map.put("fx", "西");
                            } else if (fx >= 303.76 && fx <= 326.25) {
                                map.put("fx", "西北");
                            }

                        }

                    }

                    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("description", "晴");
                                map.put("tqtp", "01");
                            }

                        }
                    }
                }
            }

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 分页查询气象历史数据
     *
     * @param wpId
     * @param startTs
     * @param endTs
     * @return
     */
    public PageInfo<Weatherfd> getWeatherHistory(Tablepar tablepar, String wpId, Date startTs, Date endTs) {

        WeatherfdExample example = new WeatherfdExample();
        example.createCriteria().andWindpowerstationidEqualTo(wpId)
                .andRecodedataBetween(startTs, endTs);
        example.setOrderByClause("recodedata DESC");

        PageHelper.startPage(tablepar.getPageNum(), tablepar.getPageSize());
        List<Weatherfd> list = weatherfdService.selectByExample(example);
        PageInfo<Weatherfd> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }
}
