package com.ho.filecenter.controller;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.ho.business.entity.Station;
import com.ho.business.vo.req.StationReq;
import com.ho.common.tools.annotation.TokenIgnore;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.constant.EnvConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.MyAddress;
import com.ho.common.tools.entity.WeatherRespVo;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.AbroadWeatherUtils;
import com.ho.common.tools.util.AddressUntils;
import com.ho.common.tools.util.IPUtils;
import com.ho.common.tools.util.WeatherUntils;
import com.ho.common.tools.vo.req.WeatherReq;
import com.ho.filecenter.feignclient.BusinessFeignClient;
import com.ho.filecenter.service.WeatherService;
import com.ho.filecenter.service.WeatherStationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author fancl
 * @desc: 天气Controller
 * @date 2022/11/11
 */
@RestController
@RequestMapping(ContextConstant.MEDIA_CONTEXT + "weather")
@Api(tags = "多媒体-天气模块")
@Slf4j
public class WeatherController {

    @Value("${spring.profiles.active}")
    String env;

    @Value("${openRedis.host}")
    String host;

    @Value("${openRedis.port}")
    String port;

    @Value("${openRedis.pass}")
    String pass;

    @Value("${openTestRedis.host}")
    String testHost;

    @Value("${openTestRedis.port}")
    String testPort;

    @Value("${openTestRedis.pass}")
    String testPass;


    @Autowired
    WeatherService weatherService;

    @Autowired
    RedisService redisService;

    @Autowired
    BusinessFeignClient businessFeignClient;

    @Autowired
    WeatherStationService weatherStationService;


    @GetMapping("info")
    @ApiOperation(value = "查询天气")
    public DataResult<WeatherRespVo> getWeather(HttpServletRequest request) {
        //先获取到IP,这个ip一定要是公网IP ,否则没有实际意义
        //URL resource = HttpUtil.class.getClassLoader().getResource("ip2region.db");;
        String ipAddr = IPUtils.getIpAddr(request);
        log.info("获取到IP: {}", ipAddr);
        log.info("获取到env", env);
        if (env.equals("dev") || env.equals("exp") || env.equals("danji") || env.equals("opentest")) {
            //这个是南京的IP
            //ipAddr = "114.222.185.168";
            //这个是南通的IP
            ipAddr = "221.227.154.59";
        }
        //通合的先显示南通的地址IP,后续再优化
        else if (EnvConstant.TONG_HE.equals(env)) {
            ipAddr = "221.227.154.59";
        }
        log.info("IP: {}", ipAddr);
        //根据IP缓存天气信息,避免解析过程漫长
        String key = RedisKeyConstant.WEATHER_IP + ipAddr;
        if (redisService.hasKey(key)) {
            WeatherRespVo weatherRespVo = (WeatherRespVo) redisService.get(key);
            return DataResult.success(weatherRespVo);
        }
        WeatherRespVo vo = weatherService.getWeather(ipAddr);
        if (vo == null) {
            return DataResult.success(DataResult.success(new WeatherRespVo()));
        }
        //保存10分钟
        redisService.set(key, vo, 10, TimeUnit.MINUTES);
        return DataResult.success(vo);

    }


    @PostMapping("stationWeatherInfo")
    @ApiOperation(value = "查询站地区天气")
    @TokenIgnore
    public DataResult<WeatherRespVo> stationWeatherInfo(@RequestBody StationReq stationReq) {
        WeatherRespVo weatherRespVo = new WeatherRespVo();
        //根据电站地区信息
        DataResult<Station> stationDataResult = businessFeignClient.selectByStationId(stationReq.getStationId());
        if (!stationDataResult.isSuccess() || stationDataResult.getData() == null) {
            return DataResult.success(weatherRespVo);
        }
        try {
//            Station station = stationDataResult.getData();
//            //截取地址名 ,然后转为pinyin,再从缓存中取值
//            int idxShi = station.getAddress().indexOf("市");
//            String stationNameShort = station.getAddress().substring(0, idxShi+1);
//            String pinyin = PinyinUtil.getPinyin(stationNameShort);
//            String key = "weatherProvinceCity:" + pinyin;
//            WeatherRespVo info = (WeatherRespVo)redisService.get(key);
//            if(info !=null){
//                info.setCityzh(station.getDistrict());
//                return DataResult.success(info);
//            }
            Station station = stationDataResult.getData();
            String key = RedisKeyConstant.WEATHER_PROVINCE_CITY + station.getAdCode();
            WeatherRespVo info = (WeatherRespVo) redisService.get(key);
            if (info != null) {
                return DataResult.success(info);
            }
        } catch (Exception e) {
            log.error("查询省市天气缓存出错:" + e.getMessage());
        }
        return DataResult.success(weatherRespVo);

    }


    @ApiIgnore
    @TokenIgnore
    @ApiOperation(value = "提供给外部查询天气的接口")
    @PostMapping("getWeatherForOther")
    public DataResult<WeatherRespVo> getWeatherForOther(@RequestBody WeatherReq weatherReq) {
        //先获取到IP,这个ip一定要是公网IP ,否则没有实际意义
        //URL resource = HttpUtil.class.getClassLoader().getResource("ip2region.db");
        String ipAddr = weatherReq.getIp();
        log.info("IP: {}", ipAddr);
        if (env.equals("dev") || env.equals("exp") || env.equals("danji") || env.equals("opentest")) {
            //这个是南通的IP
            ipAddr = "221.227.154.59";
        }
        log.info("IP: {}", ipAddr);
        //根据IP缓存天气信息,避免解析过程漫长
        String key = RedisKeyConstant.WEATHER_IP + ipAddr;
        if (redisService.hasKey(key)) {
            WeatherRespVo weatherRespVo = (WeatherRespVo) redisService.get(key);
            return DataResult.success(weatherRespVo);
        }
        WeatherRespVo vo = weatherService.getWeather(ipAddr);
        if (vo == null) {
            return DataResult.success(DataResult.success(new WeatherRespVo()));
        }
        //保存10分钟
        redisService.set(key, vo, 10, TimeUnit.MINUTES);
        return DataResult.success(vo);

    }

    @ApiIgnore
    @TokenIgnore
    @ApiOperation(value = "根据电站查询天气的接口")
    @PostMapping("getStationWeather")
    public DataResult<WeatherRespVo> getStationWeather(@RequestBody WeatherReq weatherReq) {
        log.info("weatherReq:{}", weatherReq);
        WeatherRespVo weather = null;
        try {
            weather = weatherService.getWeatherFromAddr(weatherReq.getStationId(), weatherReq.getAddr());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        if (weather == null) {
            return DataResult.success(DataResult.success(new WeatherRespVo()));
        }
        return DataResult.success(weather);

    }

    //每天的站级天气信息
    @PostMapping("jobStationWeathers")
    @TokenIgnore
    public DataResult jobStationWeathers() {
        log.info("jobStationWeathers ,start");
        //先查所有电站
        DataResult<List<Station>> listDataResult = businessFeignClient.selectAllStation();
        //不成功直接返回
        if (!listDataResult.isSuccess() || listDataResult.getData() == null) {
            return DataResult.success();
        }
        List<Station> stations = listDataResult.getData();
        if (!stations.isEmpty()) {
            //得到不重复的电站
//            List<Station> stationList = weatherStationService.dealStation(stations);
            //生成按省市为key的缓存
            long updateTime = System.currentTimeMillis();
            Map<String, String> map = new HashMap<>();
            for (Station station : stations) {
                //循环调用
//                String pinyin = PinyinUtil.getPinyin(station.getAddress());
//                log.info("pinyin:" + pinyin);
//                String longitude = String.valueOf(station.getLongitude());
//                String latitude = String.valueOf(station.getLatitude());
//                WeatherRespVo weather = weatherService.getWeatherFromApi(longitude, latitude);
//                weather.setUpdateTime(updateTime);
//                weather.setCityzh(station.getName());
//                //
//                String key = "weatherProvinceCity:" + pinyin;
//                redisService.set(key,weather );
                String adCode = station.getAdCode();
                if (null == adCode) {
                    MyAddress address = AddressUntils.getAddress(String.valueOf(station.getLatitude()),String.valueOf(station.getLongitude()));
                    if (null != address) {
                        adCode = address.getAdcode();
                    }
                }
                if (map.get(adCode) != null) {
                    continue;
                }
                String key = RedisKeyConstant.WEATHER_PROVINCE_CITY + adCode;
                WeatherRespVo weatherRespVo = AbroadWeatherUtils.getWeatherRespVo(String.valueOf(station.getLatitude()),String.valueOf(station.getLongitude()));
                weatherRespVo.setUpdateTime(updateTime);
                redisService.set(key, weatherRespVo);
                map.put(adCode, adCode);
            }
        }
        return DataResult.success();
    }

    //每天的站级天气信息
    @PostMapping("test")
    @TokenIgnore
    public DataResult test() {
        log.info("jobStationWeathers ,start");
        //先查所有电站
        DataResult<List<Station>> listDataResult = businessFeignClient.selectAllStation();
        //不成功直接返回
        if (!listDataResult.isSuccess() || listDataResult.getData() == null) {
            return DataResult.success();
        }
        List<Station> stations = listDataResult.getData();
        if (!stations.isEmpty()) {
            //得到不重复的电站
            List<Station> stationList = weatherStationService.dealStation(stations);
            //生成按省市为key的缓存
            long updateTime = System.currentTimeMillis();
            for (Station station : stationList) {
                //循环调用
                String pinyin = PinyinUtil.getPinyin(station.getAddress());
                log.info("pinyin:" + pinyin);
                String longitude = String.valueOf(station.getLongitude());
                String latitude = String.valueOf(station.getLatitude());
                WeatherRespVo weather = new WeatherRespVo();
                //weather = weatherService.getWeatherFromApi(longitude, latitude);
                weather.setUpdateTime(updateTime);
                weather.setCityzh(station.getName());
                //
                String key = RedisKeyConstant.WEATHER_PROVINCE_CITY + pinyin;
                redisService.set(key, weather);
            }
        }
        return DataResult.success();
    }

}
