package com.huimv.environ.env.timer;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huimv.environ.eco.entity.envVo.EnvVo;
import com.huimv.environ.eco.service.IBaseTelecomRoomService;
import com.huimv.environ.env.environ.dao.entity.EnvDayEntity;
import com.huimv.environ.env.environ.dao.entity.EnvHourEntity;
import com.huimv.environ.env.environ.dao.repo.EnvDayRepo;
import com.huimv.environ.env.environ.dao.repo.EnvHourRepo;
import com.mysql.cj.xdevapi.JsonArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@EnableScheduling
public class EnvTimer {
    @Autowired
    private RedisTemplate<String ,String> redisTemplate;

    @Autowired
    private EnvDayRepo envDayRepo;

    @Autowired
    private EnvHourRepo EnvHourRepo;

    @Scheduled(cron = "0 0 6 * * ? ")
    private void getDay() throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();
        String envUrl = "https://dnqyt.envchina.com/api/public/station-data";
        LocalDate previousDay = LocalDate.now().minusDays(1);
        LocalDateTime previousDayStart = LocalDateTime.of(previousDay, LocalTime.MIN);
        String formattedDateTime = previousDayStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Date date = Date.from(previousDayStart.atZone(ZoneId.systemDefault()).toInstant());
        String sgToken = redisTemplate.opsForValue().get("sg:token");
        System.out.println(sgToken);
        //token不存在重新获取
        if (StringUtils.isEmpty(sgToken)){
            String url = "https://dnqyt.envchina.com/api/public/token";
            HashMap<String, String> params = new HashMap<>();
            params.put("userName", "ZXQLYZKJ2307A2");
            params.put("password", "e91294970cb74aaf9d9a6fe0973d8f5e");
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 创建请求实体对象
            HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            // 发送POST请求
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
            if (jsonObject.getInteger("code") != 200){
                System.out.println("获取token失败!");
            }else {
                sgToken = jsonObject.getJSONObject("data").getString("token");
                redisTemplate.opsForValue().set("sg:token", sgToken,2L,TimeUnit.HOURS);
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("token",sgToken);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(headers);

        String urlWithParams = envUrl + "?type=D&mn=33330424001391" + "&startTime=" + formattedDateTime + "&endTime=" + formattedDateTime;
        System.out.println(formattedDateTime);
        ResponseEntity<String> result = restTemplate.exchange(urlWithParams, HttpMethod.GET,formEntity,String.class);
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result.getBody());
        if (jsonObject.getInteger("code") == 200){
            EnvDayEntity envDayEntity = new EnvDayEntity();
            String data = jsonObject.getString("data");
            ObjectMapper objectMapper = new ObjectMapper();
            List<EnvVo> dataList = objectMapper.readValue(data, new TypeReference<List<EnvVo>>() {});
            for (EnvVo envVo : dataList) {
                if (envVo.getFactorCode().equals("w00000")){
                    envDayEntity.setWs(envVo.getAvg());
                }
                if (envVo.getFactorCode().equals("w01001")){
                    envDayEntity.setPh(envVo.getAvg());
                }
                if (envVo.getFactorCode().equals("w01018")){
                    envDayEntity.setCod(envVo.getAvg());
                }
                if (envVo.getFactorCode().equals("w21003")){
                    envDayEntity.setAd(envVo.getAvg());
                }
            }
            envDayEntity.setAddDate(date);
            envDayEntity.setFarmId(1);
            envDayRepo.save(envDayEntity);
        }

    }

    @Scheduled(cron = "0 10 0/1 * * ? ")
    private void getHour() throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();
        String envUrl = "https://dnqyt.envchina.com/api/public/station-data";
        LocalDateTime now = LocalDateTime.now();
        // 获取上一个整点时间（不包括当前整点）
        LocalDateTime lastHour = now.minusHours(1).truncatedTo(ChronoUnit.HOURS);
        // 格式化为指定格式的字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedLastHour = lastHour.format(formatter);

        String sgToken = redisTemplate.opsForValue().get("sg:token");
        System.out.println(sgToken);
        //token不存在重新获取
        if (StringUtils.isEmpty(sgToken)){
            String url = "https://dnqyt.envchina.com/api/public/token";
            HashMap<String, String> params = new HashMap<>();
            params.put("userName", "ZXQLYZKJ2307A2");
            params.put("password", "e91294970cb74aaf9d9a6fe0973d8f5e");
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 创建请求实体对象
            HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            // 发送POST请求
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
            if (jsonObject.getInteger("code") != 200){
                System.out.println("获取token失败!");
            }else {
                sgToken = jsonObject.getJSONObject("data").getString("token");
                redisTemplate.opsForValue().set("sg:token", sgToken,2L,TimeUnit.HOURS);
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("token",sgToken);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(headers);

        String urlWithParams = envUrl + "?type=H&mn=33330424001391" + "&startTime=" + formattedLastHour + "&endTime=" + formattedLastHour;
        System.out.println(formattedLastHour);
        ResponseEntity<String> result = restTemplate.exchange(urlWithParams, HttpMethod.GET,formEntity,String.class);
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result.getBody());
        if (jsonObject.getInteger("code") == 200){
            EnvHourEntity envHourEntity = new EnvHourEntity();
            envHourEntity.setMn("33330424001391");
            envHourEntity.setDatetime(Timestamp.valueOf(formattedLastHour));
            String data = jsonObject.getString("data");
            ObjectMapper objectMapper = new ObjectMapper();
            List<EnvVo> dataList = objectMapper.readValue(data, new TypeReference<List<EnvVo>>() {});
            for (EnvVo envVo : dataList) {
                if (envVo.getFactorCode().equals("w00000")){
                    envHourEntity.setWsPj(envVo.getAvg());
                    envHourEntity.setWsZd(envVo.getAvg());
                    envHourEntity.setWsZx(envVo.getAvg());
                    envHourEntity.setWszt("N");
                }
                if (envVo.getFactorCode().equals("w01001")){
                    envHourEntity.setPhPj(envVo.getAvg());
                    envHourEntity.setPhZd(envVo.getAvg());
                    envHourEntity.setPhZx(envVo.getAvg());
                    envHourEntity.setPhzt("N");
                }
                if (envVo.getFactorCode().equals("w01018")){
                    envHourEntity.setHxxylPj(envVo.getAvg());
                    envHourEntity.setHxxylZd(envVo.getAvg());
                    envHourEntity.setHxxylZx(envVo.getAvg());
                    envHourEntity.setHxxylzt("N");
                }
                if (envVo.getFactorCode().equals("w21003")){
                    envHourEntity.setAdPj(envVo.getAvg());
                    envHourEntity.setAdZd(envVo.getAvg());
                    envHourEntity.setAdZx(envVo.getAvg());
                    envHourEntity.setAdzt("N");
                }
            }
            Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
            envHourEntity.setAddTime(currentTimestamp);
            envHourEntity.setFarmId(1);
            EnvHourRepo.save(envHourEntity);
        }

    }

    public static void main(String[] args) throws JsonProcessingException {

    }

}
