import tkinter as tk
from tkinter import ttk, messagebox
import requests

# 替换成你自己的和风天气key
WEATHER_KEY = "your_key"


def get_city_location(city_name):
    """获取城市的location_id"""
    url = f"https://geoapi.qweather.com/v2/city/lookup?location={city_name}&key={WEATHER_KEY}"
    try:
        resp = requests.get(url, timeout=10)
        # 判断http状态码是否正常
        if resp.status_code != 200:
            messagebox.showerror("网络错误", f"HTTP状态码：{resp.status_code}")
            return None
        data = resp.json()
    except requests.exceptions.RequestException as e:
        messagebox.showerror("网络异常", f"请求失败：{str(e)}")
        return None
    except ValueError:
        messagebox.showerror("解析错误", "服务器返回数据不是JSON，检查网络或key")
        return None

    if data.get("code") != "200":
        msg = data.get("message", "未知错误")
        messagebox.showerror("接口返回错误", f"{msg}")
        return None
    return data["location"][0]["id"]


def query_weather():
    """查询天气按钮触发函数"""
    city = entry_city.get().strip()
    if not city:
        messagebox.showwarning("提示", "请输入城市名称！")
        return

    loc_id = get_city_location(city)
    if loc_id is None:
        return

    weather_url = f"https://devapi.qweather.com/v7/weather/now?location={loc_id}&key={WEATHER_KEY}"
    try:
        res = requests.get(weather_url, timeout=10)
        if res.status_code != 200:
            messagebox.showerror("网络错误", f"HTTP状态码：{res.status_code}")
            return
        res_data = res.json()
    except requests.exceptions.RequestException as e:
        messagebox.showerror("网络异常", f"请求失败：{str(e)}")
        return
    except ValueError:
        messagebox.showerror("解析错误", "服务器返回数据不是JSON")
        return

    if res_data.get("code") != "200":
        msg = res_data.get("message", "未知错误")
        messagebox.showerror("接口返回错误", f"{msg}")
        return

    now = res_data["now"]
    info_text = f"""
城市：{city}
实时天气：{now['text']}
温度：{now['temp']} ℃
体感温度：{now['feelsLike']} ℃
湿度：{now['humidity']} %
风向风力：{now['windDir']} {now['windScale']}级
气压：{now['pressure']} hPa
"""
    text_result.config(state=tk.NORMAL)
    text_result.delete(1.0, tk.END)
    text_result.insert(tk.END, info_text)
    text_result.config(state=tk.DISABLED)


def main():
    root = tk.Tk()
    root.title("天气查询小工具")
    root.geometry("420x340")
    root.resizable(False, False)

    # 标题
    title_label = ttk.Label(root, text="🔍天气查询工具", font=("微软雅黑", 16))
    title_label.pack(pady=12)

    # 输入行
    frame_input = ttk.Frame(root)
    frame_input.pack(pady=5)
    ttk.Label(frame_input, text="输入城市：", font=("微软雅黑", 11)).grid(row=0, column=0, padx=5)
    global entry_city
    entry_city = ttk.Entry(frame_input, width=20, font=("微软雅黑", 11))
    entry_city.grid(row=0, column=1, padx=5)

    btn_query = ttk.Button(root, text="查询天气", command=query_weather)
    btn_query.pack(pady=10)

    # 结果显示框
    global text_result
    text_result = tk.Text(root, width=48, height=12, font=("微软雅黑", 10))
    text_result.pack(padx=10, pady=5)
    text_result.config(state=tk.DISABLED)

    root.mainloop()


if __name__ == "__main__":
    main()
