import { reactive, onMounted, onBeforeUnmount } from 'vue';
import dayjs from 'dayjs';

export type WeatherType = 'clear' | 'cloudy' | 'rainy';
interface WeatherData {
  weatherType: WeatherType;
  tempMin: number;
  tempMax: number;
  humidity: number;
  windSpeed: number;
  pop: number;
}
export const useWeather = () => {
  const appid = import.meta.env.VITE_APP_WEATHER_APPID;
  const city = import.meta.env.VITE_APP_WEATHER_CITY;
  const url = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${appid}&units=metric`;

  const weather = reactive<WeatherData>({
    weatherType: 'clear',
    tempMin: 30,
    tempMax: 30,
    humidity: 65,
    windSpeed: 3,
    pop: 0,
  });

  // 获取天气数据
  const getWeather = async () => {
    const response = await fetch(url);
    const res = await response.json();
    const data =
      (res?.list || []).find((item: any, index: number) => {
        // 获取接近当前时间的那一条数据
        return dayjs().isAfter(item.dt_txt) && dayjs().isBefore(res.list[index + 1]?.dt_txt);
      }) || {};

    weather.tempMin = Math.round(data.main.temp_min);
    weather.tempMax = Math.round(data.main.temp_max);
    weather.humidity = data.main.humidity;
    weather.windSpeed = Math.round(data.wind.speed);
    weather.pop = Math.round(data.pop * 100);

    const weatherMain = data.weather[0].main;
    // 天气类型只有晴空、阴、下雨三种设计
    if (weatherMain.includes('Clear')) {
      weather.weatherType = 'clear';
    } else if (weatherMain.includes('Clouds')) {
      weather.weatherType = 'cloudy';
    } else if (weatherMain.includes('Rain') || weatherMain.includes('Drizzle')) {
      weather.weatherType = 'rainy';
    } else {
      weather.weatherType = 'cloudy';
    }
  };

  let timer: NodeJS.Timeout | null = null;
  onMounted(() => {
    getWeather();
    // 轮询间隔10分钟
    timer = setInterval(getWeather, 1000 * 60 * 10);
  });

  onBeforeUnmount(() => {
    timer && clearInterval(timer);
  });

  return { weather };
};
