import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import random
from datetime import datetime

class WeatherApp:
    def __init__(self, root):
        self.root = root
        self.root.title("🌤️ 天气查询小工具")
        self.root.geometry("900x660")
        self.root.configure(bg='#f0f8ff')
        
        # 城市数据
        self.cities = [
            "北京", "上海", "广州", "深圳", "杭州", "成都", "武汉", "南京",
            "重庆", "天津", "苏州", "西安", "长沙", "青岛", "大连", "厦门",
            "宁波", "福州", "合肥", "郑州", "昆明", "贵阳", "南宁", "海口",
            "哈尔滨", "长春", "沈阳", "呼和浩特", "乌鲁木齐", "拉萨",
            "兰州", "银川", "西宁", "太原", "石家庄", "济南", "南昌"
        ]
        
        # 天气图标映射
        self.weather_icons = {
            "晴": "☀️", "多云": "⛅", "阴": "☁️", "小雨": "🌦️",
            "中雨": "🌧️", "大雨": "🌧️", "雷阵雨": "⛈️", "暴雨": "🌊",
            "雪": "❄️", "雾": "🌫️", "霾": "😷", "大风": "💨"
        }
        
        # 初始化变量
        self.city_var = tk.StringVar(value="北京")
        self.favorites = ["北京", "上海", "广州"]
        self.history = []
        
        # 创建界面
        self.create_widgets()
        
        # 默认查询北京天气
        self.query_weather()
        
    def create_widgets(self):
        """创建界面组件"""
        # 标题栏
        self.create_header()
        
        # 主内容区
        main_frame = tk.Frame(self.root, bg='#f0f8ff')
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 左侧：查询区
        left_frame = tk.Frame(main_frame, bg='#f0f8ff', width=260)
        left_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 20))
        left_frame.pack_propagate(False)
        
        self.create_search_panel(left_frame)
        self.create_favorites_panel(left_frame)
        self.create_history_panel(left_frame)
        
        # 右侧：显示区
        right_frame = tk.Frame(main_frame, bg='#f0f8ff')
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 创建标签页
        self.notebook = ttk.Notebook(right_frame)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        
        self.create_weather_tab()
        self.create_hourly_tab()
        self.create_forecast_tab()
        self.create_details_tab()
        
        # 状态栏
        self.create_statusbar()
        
    def create_header(self):
        """创建标题栏"""
        header_frame = tk.Frame(self.root, bg='#4A90D9', height=65)
        header_frame.pack(fill=tk.X)
        header_frame.pack_propagate(False)
        
        title_label = tk.Label(header_frame, 
                              text="🌤️ 天气查询小工具", 
                              font=("Microsoft YaHei", 24, "bold"),
                              fg="white", 
                              bg='#4A90D9')
        title_label.pack(pady=12)
        
    def create_search_panel(self, parent):
        """创建搜索面板"""
        search_frame = tk.LabelFrame(parent, text="🔍 城市查询", 
                                    font=("Microsoft YaHei", 11, "bold"),
                                    bg='white', fg="#2c3e50",
                                    padx=12, pady=12)
        search_frame.pack(fill=tk.X, pady=(0, 12))
        
        # 城市选择
        tk.Label(search_frame, text="选择城市:", 
                font=("Microsoft YaHei", 10),
                bg='white').pack(anchor=tk.W, pady=(0, 5))
        
        city_combo = ttk.Combobox(search_frame, 
                                 textvariable=self.city_var,
                                 values=self.cities,
                                 font=("Microsoft YaHei", 10),
                                 state="normal")
        city_combo.pack(fill=tk.X, pady=(0, 10))
        city_combo.bind('<Return>', self.on_search)
        
        # 查询按钮
        btn_frame = tk.Frame(search_frame, bg='white')
        btn_frame.pack(fill=tk.X)
        
        tk.Button(btn_frame, text="🔍 查询天气", 
                 command=self.query_weather,
                 font=("Microsoft YaHei", 10, "bold"),
                 bg="#4A90D9", fg="white",
                 relief=tk.RAISED, width=12).pack(side=tk.LEFT, padx=(0, 5))
        
        tk.Button(btn_frame, text="📍 定位", 
                 command=self.get_location_weather,
                 font=("Microsoft YaHei", 10),
                 bg="#27AE60", fg="white",
                 relief=tk.RAISED, width=8).pack(side=tk.LEFT)
        
        # 快捷城市
        quick_frame = tk.Frame(search_frame, bg='white')
        quick_frame.pack(fill=tk.X, pady=(10, 0))
        
        tk.Label(quick_frame, text="热门城市:", 
                font=("Microsoft YaHei", 9),
                bg='white', fg="#7f8c8d").pack(anchor=tk.W, pady=(0, 5))
        
        hot_cities = ["北京", "上海", "广州", "深圳", "杭州", "成都"]
        cities_frame = tk.Frame(quick_frame, bg='white')
        cities_frame.pack(fill=tk.X)
        
        for i, city in enumerate(hot_cities):
            btn = tk.Button(cities_frame, text=city,
                          command=lambda c=city: self.quick_select(c),
                          font=("Microsoft YaHei", 9),
                          bg="#ECF0F1", fg="#2c3e50",
                          relief=tk.FLAT, width=6)
            btn.grid(row=i//3, column=i%3, padx=2, pady=2)
            
    def create_favorites_panel(self, parent):
        """创建收藏夹面板"""
        fav_frame = tk.LabelFrame(parent, text="⭐ 收藏城市", 
                                 font=("Microsoft YaHei", 11, "bold"),
                                 bg='white', fg="#2c3e50",
                                 padx=12, pady=12)
        fav_frame.pack(fill=tk.X, pady=(0, 12))
        
        # 收藏城市列表
        self.fav_listbox = tk.Listbox(fav_frame, height=4,
                                      font=("Microsoft YaHei", 10),
                                      bg='#F8F9FA')
        self.fav_listbox.pack(fill=tk.X, pady=(0, 10))
        self.fav_listbox.bind('<Double-Button-1>', self.on_fav_select)
        
        # 收藏按钮
        fav_btn_frame = tk.Frame(fav_frame, bg='white')
        fav_btn_frame.pack(fill=tk.X)
        
        tk.Button(fav_btn_frame, text="➕ 添加收藏", 
                 command=self.add_favorite,
                 font=("Microsoft YaHei", 9),
                 bg="#F39C12", fg="white",
                 relief=tk.RAISED, width=10).pack(side=tk.LEFT, padx=(0, 5))
        
        tk.Button(fav_btn_frame, text="➖ 删除", 
                 command=self.remove_favorite,
                 font=("Microsoft YaHei", 9),
                 bg="#E74C3C", fg="white",
                 relief=tk.RAISED, width=8).pack(side=tk.LEFT)
        
        self.update_favorites()
        
    def create_history_panel(self, parent):
        """创建历史记录面板"""
        history_frame = tk.LabelFrame(parent, text="📜 查询历史", 
                                     font=("Microsoft YaHei", 11, "bold"),
                                     bg='white', fg="#2c3e50",
                                     padx=12, pady=12)
        history_frame.pack(fill=tk.BOTH, expand=True)
        
        # 历史记录列表
        self.history_listbox = tk.Listbox(history_frame, height=5,
                                          font=("Microsoft YaHei", 9),
                                          bg='#F8F9FA')
        self.history_listbox.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        self.history_listbox.bind('<Double-Button-1>', self.on_history_select)
        
        # 清空按钮
        tk.Button(history_frame, text="🗑️ 清空历史", 
                 command=self.clear_history,
                 font=("Microsoft YaHei", 9),
                 bg="#95A5A6", fg="white",
                 relief=tk.RAISED).pack(fill=tk.X)
        
    def create_weather_tab(self):
        """创建天气概览标签页"""
        weather_frame = tk.Frame(self.notebook, bg='white')
        self.notebook.add(weather_frame, text="🌤️ 当前天气")
        
        # 当前天气显示
        self.current_weather_frame = tk.Frame(weather_frame, bg='#EBF5FB', 
                                             height=220, relief=tk.RAISED, bd=2)
        self.current_weather_frame.pack(fill=tk.X, pady=15, padx=15)
        self.current_weather_frame.pack_propagate(False)
        
        # 城市名和时间
        top_frame = tk.Frame(self.current_weather_frame, bg='#EBF5FB')
        top_frame.pack(fill=tk.X, padx=20, pady=(12, 0))
        
        self.city_name_label = tk.Label(top_frame, text="北京", 
                                       font=("Microsoft YaHei", 28, "bold"),
                                       bg='#EBF5FB', fg="#2c3e50")
        self.city_name_label.pack(side=tk.LEFT)
        
        self.update_time_label = tk.Label(top_frame, text="", 
                                         font=("Microsoft YaHei", 11),
                                         bg='#EBF5FB', fg="#7f8c8d")
        self.update_time_label.pack(side=tk.RIGHT)
        
        # 温度和天气
        middle_frame = tk.Frame(self.current_weather_frame, bg='#EBF5FB')
        middle_frame.pack(fill=tk.X, padx=20, pady=15)
        
        # 温度
        temp_frame = tk.Frame(middle_frame, bg='#EBF5FB')
        temp_frame.pack(side=tk.LEFT)
        
        self.temp_label = tk.Label(temp_frame, text="--°C", 
                                  font=("Microsoft YaHei", 54, "bold"),
                                  bg='#EBF5FB', fg="#E74C3C")
        self.temp_label.pack()
        
        # 天气图标和描述
        weather_info_frame = tk.Frame(middle_frame, bg='#EBF5FB')
        weather_info_frame.pack(side=tk.RIGHT, padx=(0, 40))
        
        self.weather_icon_label = tk.Label(weather_info_frame, text="☀️", 
                                          font=("Microsoft YaHei", 34),
                                          bg='#EBF5FB')
        self.weather_icon_label.pack()
        
        self.weather_desc_label = tk.Label(weather_info_frame, text="晴", 
                                          font=("Microsoft YaHei", 16),
                                          bg='#EBF5FB', fg="#2c3e50")
        self.weather_desc_label.pack()
        
        # 附加信息
        bottom_frame = tk.Frame(self.current_weather_frame, bg='#EBF5FB')
        bottom_frame.pack(fill=tk.X, padx=20, pady=(0, 12))
        
        info_items = [
            ("🌡️ 体感温度", "feels_like"),
            ("💧 湿度", "humidity"),
            ("💨 风速", "wind_speed"),
            ("🌈 气压", "pressure")
        ]
        
        self.extra_labels = {}
        for text, key in info_items:
            frame = tk.Frame(bottom_frame, bg='#EBF5FB')
            frame.pack(side=tk.LEFT, padx=(0, 25))
            
            tk.Label(frame, text=text, 
                    font=("Microsoft YaHei", 9),
                    bg='#EBF5FB', fg="#7f8c8d").pack()
            
            value_label = tk.Label(frame, text="--", 
                                 font=("Microsoft YaHei", 13, "bold"),
                                 bg='#EBF5FB', fg="#2c3e50")
            value_label.pack()
            
            self.extra_labels[key] = value_label
        
        # 生活建议
        advice_frame = tk.Frame(weather_frame, bg='white')
        advice_frame.pack(fill=tk.X, padx=15, pady=(0, 15))
        
        tk.Label(advice_frame, text="💡 生活建议", 
                font=("Microsoft YaHei", 13, "bold"),
                bg='white', fg="#2c3e50").pack(anchor=tk.W, pady=(0, 8))
        
        self.advice_text = tk.Text(advice_frame, height=5, 
                                  font=("Microsoft YaHei", 10),
                                  bg='#FEF9E7', wrap=tk.WORD)
        self.advice_text.pack(fill=tk.X)
        
    def create_hourly_tab(self):
        """创建逐小时预报标签页"""
        hourly_frame = tk.Frame(self.notebook, bg='white')
        self.notebook.add(hourly_frame, text="⏰ 逐小时预报")
        
        self.hourly_text = scrolledtext.ScrolledText(hourly_frame, 
                                                    font=("Microsoft YaHei", 11),
                                                    bg='white', wrap=tk.WORD)
        self.hourly_text.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)
        
    def create_forecast_tab(self):
        """创建未来预报标签页"""
        forecast_frame = tk.Frame(self.notebook, bg='white')
        self.notebook.add(forecast_frame, text="📅 未来预报")
        
        self.forecast_text = scrolledtext.ScrolledText(forecast_frame, 
                                                      font=("Microsoft YaHei", 11),
                                                      bg='white', wrap=tk.WORD)
        self.forecast_text.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)
        
    def create_details_tab(self):
        """创建详细信息标签页"""
        details_frame = tk.Frame(self.notebook, bg='white')
        self.notebook.add(details_frame, text="📊 详细信息")
        
        self.details_text = scrolledtext.ScrolledText(details_frame, 
                                                     font=("Microsoft YaHei", 11),
                                                     bg='white', wrap=tk.WORD)
        self.details_text.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)
        
    def create_statusbar(self):
        """创建状态栏"""
        status_frame = tk.Frame(self.root, bg='#34495E', height=28)
        status_frame.pack(side=tk.BOTTOM, fill=tk.X)
        status_frame.pack_propagate(False)
        
        self.status_label = tk.Label(status_frame, 
                                    text="就绪 | 等待查询...", 
                                    font=("Microsoft YaHei", 9),
                                    fg="white", 
                                    bg='#34495E',
                                    anchor=tk.W)
        self.status_label.pack(side=tk.LEFT, padx=10)
        
        self.time_label = tk.Label(status_frame, 
                                  text=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                  font=("Microsoft YaHei", 9),
                                  fg="white", 
                                  bg='#34495E')
        self.time_label.pack(side=tk.RIGHT, padx=10)
        
        self.update_time()
        
    def update_time(self):
        """更新时间显示"""
        self.time_label.config(text=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        self.root.after(1000, self.update_time)
        
    def on_search(self, event=None):
        """搜索事件"""
        self.query_weather()
        
    def quick_select(self, city):
        """快速选择城市"""
        self.city_var.set(city)
        self.query_weather()
        
    def query_weather(self):
        """查询天气"""
        city = self.city_var.get().strip()
        if not city:
            messagebox.showwarning("警告", "请输入城市名称！")
            return
            
        self.status_label.config(text=f"正在查询 {city} 的天气...")
        self.simulate_weather_data(city)
        
        if city not in self.history:
            self.history.insert(0, city)
            if len(self.history) > 10:
                self.history.pop()
            self.update_history()
            
    def simulate_weather_data(self, city):
        """模拟天气数据"""
        temp = random.randint(-5, 38)
        feels_like = temp + random.randint(-3, 3)
        humidity = random.randint(30, 85)
        wind_speed = random.randint(1, 35)
        pressure = random.randint(990, 1030)
        
        weather_types = ["晴", "多云", "阴", "小雨", "晴", "多云", "晴"]
        weather = random.choice(weather_types)
        
        # 更新当前天气显示
        self.city_name_label.config(text=city)
        self.update_time_label.config(text=f"更新于 {datetime.now().strftime('%H:%M')}")
        self.temp_label.config(text=f"{temp}°C")
        self.weather_icon_label.config(text=self.weather_icons.get(weather, "🌤️"))
        self.weather_desc_label.config(text=weather)
        
        # 更新附加信息
        self.extra_labels["feels_like"].config(text=f"{feels_like}°C")
        self.extra_labels["humidity"].config(text=f"{humidity}%")
        self.extra_labels["wind_speed"].config(text=f"{wind_speed}km/h")
        self.extra_labels["pressure"].config(text=f"{pressure}hPa")
        
        # 更新生活建议
        self.update_advice(temp, weather, humidity, wind_speed)
        
        # 更新逐小时预报
        self.update_hourly_forecast(temp, weather)
        
        # 更新未来预报
        self.update_forecast()
        
        # 更新详细信息
        self.update_details(city, temp, feels_like, humidity, wind_speed, pressure, weather)
        
        # 更新状态
        self.status_label.config(text=f"✅ {city} 天气已更新 | {datetime.now().strftime('%H:%M:%S')}")
        
    def update_advice(self, temp, weather, humidity, wind_speed):
        """更新生活建议"""
        self.advice_text.delete(1.0, tk.END)
        
        advices = []
        
        if temp > 33:
            advices.append("🔥 高温预警：注意防暑降温，多喝水，避免长时间户外活动。")
        elif temp > 28:
            advices.append("☀️ 天气炎热：建议穿短袖，注意防晒。")
        elif temp > 20:
            advices.append("🌤️ 气温适宜：适合户外活动。")
        elif temp > 10:
            advices.append("🍂 气温适中：建议穿外套。")
        elif temp > 0:
            advices.append("❄️ 天气较冷：注意保暖，穿上厚衣服。")
        else:
            advices.append("🥶 严寒天气：注意防寒保暖，减少外出。")
        
        if "雨" in weather:
            advices.append("☔ 有降雨可能：记得带伞出门。")
        if wind_speed > 30:
            advices.append("💨 风力较大：注意防风，远离广告牌。")
        if humidity > 78:
            advices.append("💧 湿度较高：注意防潮，衣物不易干。")
        elif humidity < 42:
            advices.append("💧 空气干燥：注意补水，使用保湿产品。")
        
        advices.append("😊 保持好心情，祝你度过愉快的一天！")
        
        for advice in advices:
            self.advice_text.insert(tk.END, f"• {advice}\n")
            
    def update_hourly_forecast(self, base_temp, base_weather):
        """更新逐小时预报"""
        self.hourly_text.delete(1.0, tk.END)
        
        self.hourly_text.insert(tk.END, "⏰ 逐小时天气预报\n\n", "title")
        
        now = datetime.now()
        for i in range(12):
            hour = (now.hour + i) % 24
            temp = base_temp + random.randint(-3, 3)
            weather = random.choice(["晴", "多云", "晴", "多云", "阴"])
            icon = self.weather_icons.get(weather, "🌤️")
            
            time_str = f"{hour:02d}:00"
            self.hourly_text.insert(tk.END, f"{time_str}  {icon}  {temp}°C  {weather}\n")
        
        self.hourly_text.tag_config("title", font=("Microsoft YaHei", 14, "bold"), foreground="#2c3e50")
        
    def update_forecast(self):
        """更新未来预报"""
        self.forecast_text.delete(1.0, tk.END)
        
        self.forecast_text.insert(tk.END, "📅 未来7天天气预报\n\n", "title")
        
        weekdays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
        now = datetime.now()
        
        for i in range(7):
            day = (now.day + i) % 28 + 1
            weekday = weekdays[(now.weekday() + i) % 7]
            high = random.randint(15, 35)
            low = high - random.randint(5, 12)
            weather = random.choice(["晴", "多云", "阴", "小雨", "晴", "多云", "晴"])
            icon = self.weather_icons.get(weather, "🌤️")
            
            forecast = f"{weekday} {now.month}/{day}  {icon}  {weather}  {low}°C ~ {high}°C\n"
            self.forecast_text.insert(tk.END, forecast)
        
        self.forecast_text.tag_config("title", font=("Microsoft YaHei", 14, "bold"), foreground="#2c3e50")
        
    def update_details(self, city, temp, feels_like, humidity, wind_speed, pressure, weather):
        """更新详细信息"""
        self.details_text.delete(1.0, tk.END)
        
        moon_phases = ["新月", "蛾眉月", "上弦月", "盈凸月", "满月", "亏凸月", "下弦月", "残月"]
        air_qualities = ["优", "良", "轻度污染", "中度污染"]
        uv_levels = ["低", "中等", "高", "很高"]
        
        details = f"""
📊 {city} 天气详细信息

═══════════════════════

📍 基本信息
   城市：{city}
   日期：{datetime.now().strftime("%Y年%m月%d日")}
   时间：{datetime.now().strftime("%H:%M:%S")}

🌤️ 天气状况
   天气现象：{weather}
   当前温度：{temp}°C
   体感温度：{feels_like}°C
   天气图标：{self.weather_icons.get(weather, "🌤️")}

💨 大气参数
   相对湿度：{humidity}%
   风速：{wind_speed} km/h
   气压：{pressure} hPa

🌅 日出日落信息
   日出时间：06:30
   日落时间：18:45

🌙 月相信息
   月相：{random.choice(moon_phases)}

🏙️ 空气质量
   AQI指数：{random.randint(30, 160)}
   空气质量：{random.choice(air_qualities)}
   PM2.5：{random.randint(10, 110)} μg/m³
   PM10：{random.randint(20, 190)} μg/m³

💡 温馨提示
   紫外线指数：{random.randint(1, 11)}/{random.choice(uv_levels)}
   穿衣建议：{self.get_dress_advice(temp)}
   运动指数：{random.choice(["适宜", "较适宜", "不太适宜"])}
   洗车指数：{random.choice(["适宜", "较适宜", "不适宜"])}

═══════════════════════
数据更新时间：{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
        """
        
        self.details_text.insert(1.0, details)
        
    def get_dress_advice(self, temp):
        """获取穿衣建议"""
        if temp > 33:
            return "短袖短裤，注意防晒"
        elif temp > 28:
            return "短袖短裤，轻薄透气"
        elif temp > 24:
            return "短袖或薄长袖"
        elif temp > 18:
            return "长袖衬衫或薄外套"
        elif temp > 14:
            return "外套加内搭"
        elif temp > 10:
            return "毛衣或卫衣，外套"
        elif temp > 5:
            return "厚外套，毛衣"
        elif temp > 0:
            return "羽绒服，围巾手套"
        else:
            return "厚羽绒服，帽子围巾手套全副武装"
        
    def get_location_weather(self):
        """获取当前位置天气"""
        cities_nearby = ["北京", "上海", "广州", "深圳"]
        location = random.choice(cities_nearby)
        self.city_var.set(location)
        self.query_weather()
        messagebox.showinfo("定位成功", f"已定位到：{location}")
        
    def add_favorite(self):
        """添加收藏城市"""
        city = self.city_var.get().strip()
        if not city:
            messagebox.showwarning("警告", "请先选择城市！")
            return
            
        if city not in self.favorites:
            self.favorites.append(city)
            self.update_favorites()
            messagebox.showinfo("成功", f"已将{city}添加到收藏！")
        else:
            messagebox.showinfo("提示", f"{city}已在收藏列表中！")
            
    def remove_favorite(self):
        """删除收藏城市"""
        selection = self.fav_listbox.curselection()
        if selection:
            city = self.fav_listbox.get(selection[0])
            self.favorites.remove(city)
            self.update_favorites()
            
    def update_favorites(self):
        """更新收藏列表"""
        self.fav_listbox.delete(0, tk.END)
        for city in self.favorites:
            self.fav_listbox.insert(tk.END, city)
            
    def update_history(self):
        """更新历史记录"""
        self.history_listbox.delete(0, tk.END)
        for city in self.history:
            self.history_listbox.insert(tk.END, city)
            
    def on_fav_select(self, event):
        """收藏选择事件"""
        selection = self.fav_listbox.curselection()
        if selection:
            city = self.fav_listbox.get(selection[0])
            self.city_var.set(city)
            self.query_weather()
            
    def on_history_select(self, event):
        """历史选择事件"""
        selection = self.history_listbox.curselection()
        if selection:
            city = self.history_listbox.get(selection[0])
            self.city_var.set(city)
            self.query_weather()
            
    def clear_history(self):
        """清空历史记录"""
        if messagebox.askyesno("确认", "确定要清空查询历史吗？"):
            self.history.clear()
            self.update_history()

def main():
    """主函数"""
    root = tk.Tk()
    
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    width = 920
    height = 670
    x = (screen_width - width) // 2
    y = (screen_height - height) // 2
    root.geometry(f"{width}x{height}+{x}+{y}")
    
    app = WeatherApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()