package tool import ( "context" "encoding/json" "fmt" "net/http" "net/url" "slices" "strconv" "strings" "time" "example.com/ueino/pkg/model" ) func forecastDates(args model.WeatherArguments, now time.Time) (time.Time, time.Time, error) { zone := time.FixedZone("Asia/Shanghai", 8*60*60) now = now.In(zone) today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, zone) start := today var err error if args.StartDate != "" { start, err = time.ParseInLocation(time.DateOnly, args.StartDate, zone) if err != nil { return time.Time{}, time.Time{}, fmt.Errorf("start_date 必须是 YYYY-MM-DD 格式的有效日期") } } else if args.EndDate != "" { return time.Time{}, time.Time{}, fmt.Errorf("end_date 不能单独提供,请同时提供 start_date") } end := start if args.EndDate != "" { end, err = time.ParseInLocation(time.DateOnly, args.EndDate, zone) if err != nil { return time.Time{}, time.Time{}, fmt.Errorf("end_date 必须是 YYYY-MM-DD 格式的有效日期") } } last := today.AddDate(0, 0, 15) if end.Before(start) { return time.Time{}, time.Time{}, fmt.Errorf("结束日期不能早于开始日期") } if start.Before(today) || end.After(last) { return time.Time{}, time.Time{}, fmt.Errorf("预报仅支持 %s 至 %s,不支持历史或更远日期", today.Format(time.DateOnly), last.Format(time.DateOnly)) } return start, end, nil } func (w *Weather) forecast(ctx context.Context, args model.WeatherArguments) (string, error) { start, end, err := forecastDates(args, time.Now()) if err != nil { return "", err } search := url.Values{"name": {args.Location}, "count": {"1"}, "language": {"zh"}, "format": {"json"}} var locations model.WeatherLocations if err := w.getWeatherJSON(ctx, w.geocodingURL+"?"+search.Encode(), &locations); err != nil { return "", err } if len(locations.Results) == 0 { return "", fmt.Errorf("未找到地点 %q,请提供明确的城市名称", args.Location) } location := locations.Results[0] query := url.Values{ "latitude": {strconv.FormatFloat(location.Latitude, 'f', -1, 64)}, "longitude": {strconv.FormatFloat(location.Longitude, 'f', -1, 64)}, "start_date": {start.Format(time.DateOnly)}, "end_date": {end.Format(time.DateOnly)}, "timezone": {"Asia/Shanghai"}, "daily": {"weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max"}, } var response model.WeatherDailyResponse if err := w.getWeatherJSON(ctx, w.forecastURL+"?"+query.Encode(), &response); err != nil { return "", err } result := model.WeatherForecast{ Location: strings.TrimSpace(location.Name + " " + location.Admin1 + " " + location.Country), Timezone: "Asia/Shanghai", } daily := response.Daily for date := start; !date.After(end); date = date.AddDate(0, 0, 1) { day := date.Format(time.DateOnly) index := slices.Index(daily.Dates, day) if index < 0 || index >= len(daily.Codes) || index >= len(daily.MaxTemps) || index >= len(daily.MinTemps) || index >= len(daily.RainChances) { return "", fmt.Errorf("天气接口未提供 %s 的完整预报,无法查询该日期范围", day) } if daily.Codes[index] == nil || daily.MaxTemps[index] == nil || daily.MinTemps[index] == nil || daily.RainChances[index] == nil { return "", fmt.Errorf("天气接口未提供 %s 的完整预报,无法查询该日期范围", day) } result.Days = append(result.Days, model.WeatherDay{ Date: day, Condition: weatherCondition(*daily.Codes[index]), MinTemperatureC: *daily.MinTemps[index], MaxTemperatureC: *daily.MaxTemps[index], PrecipitationChancePct: *daily.RainChances[index], }) } data, err := json.Marshal(result) return string(data), err } func (w *Weather) getWeatherJSON(ctx context.Context, endpoint string, result any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return err } resp, err := w.client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("天气接口返回 %s", resp.Status) } if err := json.NewDecoder(resp.Body).Decode(result); err != nil { return fmt.Errorf("解析天气接口响应失败: %w", err) } return nil } func weatherCondition(code int) string { switch code { case 0: return "晴" case 1: return "大部晴朗" case 2: return "多云" case 3: return "阴" case 45, 48: return "雾" case 51, 53, 55: return "毛毛雨" case 56, 57, 66, 67: return "冻雨" case 61: return "小雨" case 63: return "中雨" case 65: return "大雨" case 71, 73, 75, 77: return "雪" case 80, 81, 82: return "阵雨" case 85, 86: return "阵雪" case 95: return "雷暴" case 96, 99: return "雷暴伴冰雹" default: return fmt.Sprintf("未知天气(WMO %d)", code) } }