| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052 |
- import tkinter as tk
- from tkinter import ttk, messagebox
- import json
- import requests
- import threading
- from datetime import datetime
- import uuid
- import time
- import os
- import configparser
- import re
- class PhoneQueryApp:
- def __init__(self, root):
- self.root = root
- self.root.title("手机数据查询系统")
- self.root.geometry("1300x920") # 增加高度以容纳新控件
-
- # 配置文件
- self.config_file = "config.ini"
- self.token = self.load_token()
-
- # 商品数据
- self.current_products = []
- self.is_loading_cycles = False
- self.current_page = 0
- self.total_pages = 0
- self.page_size = 30
- self.current_keyword = ""
- self.current_sort = "sort_composite" # 默认综合排序
-
- # 自动检测相关变量
- self.auto_detect_running = False
- self.auto_detect_stop = False
- self.auto_detect_page = 0
- self.auto_detect_products = []
- self.auto_detect_thread = None
- self.auto_collect_count = 0
- self.auto_check_count = 0
-
- # 排序选项映射
- self.sort_map = {
- "综合排序": "sort_composite",
- "价格从低到高": "sort_price_asc",
- "价格从高到低": "sort_price_desc"
- }
-
- # 筛选选项映射
- self.memory_map = {
- "1T": 187,
- "512G": 192,
- "256G": 209,
- "128G": 210,
- "64G": 217,
- }
-
- self.battery_map = {
- "100%": 1680,
- "95%-99%": 5699,
- "90%-95%": 5700,
- "85%-90%": 5697,
- "80%-85%": 5698,
- "70%-80%": 6159,
- "70%以下": 6160,
- "不支持": 1627
- }
-
- # 状况标签映射
- self.condition_tags = {
- 10: "屏幕完美",
- 11: "机身无痕",
- 12: "功能完好",
- 17: "电池效率95%+",
- 20: "原厂在保",
- 19: "无维修",
- 15: "官方在保",
- 13: "原厂电池",
- 14: "原厂屏幕",
- 21: "原厂部件"
- }
-
- self.create_widgets()
- self.result_tree.bind("<Button-3>", self.show_context_menu)
-
- def load_token(self):
- """从配置文件加载Token"""
- if os.path.exists(self.config_file):
- try:
- config = configparser.ConfigParser()
- config.read(self.config_file)
- return config.get('Settings', 'token', fallback='dccf18b052ef46d78d4feb796182d5df')
- except:
- return 'dccf18b052ef46d78d4feb796182d5df'
- return 'dccf18b052ef46d78d4feb796182d5df'
-
- def save_token(self):
- """保存Token到配置文件"""
- try:
- config = configparser.ConfigParser()
- if os.path.exists(self.config_file):
- config.read(self.config_file)
- if not config.has_section('Settings'):
- config.add_section('Settings')
- config.set('Settings', 'token', self.token_var.get())
- with open(self.config_file, 'w') as f:
- config.write(f)
- self.token = self.token_var.get()
- messagebox.showinfo("成功", "Token已保存")
- return True
- except Exception as e:
- messagebox.showerror("错误", f"保存Token失败: {e}")
- return False
-
- def get_headers(self):
- """获取请求头"""
- return {
- "Connection": "keep-alive",
- "content-type": "application/json;charset=UTF-8",
- "ahs-app-version": "7.49.3",
- "Ahs-Timestamp": str(int(datetime.now().timestamp())),
- "Ahs-Token": self.token,
- "Ahs-Session-Id": str(uuid.uuid4()),
- "Ahs-App-Id": "10007",
- "Ahs-Device-Id": "3166e003-4ba7-4b57-8158-30859d81c7d5",
- "Ahs-Sign": "9ea25fcfcda37585065244ed271f1b0d",
- "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 26_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.74(0x18004a2c) NetType/WIFI Language/zh_CN",
- "Referer": "https://servicewechat.com/wx7e490492b4c23e98/1055/page-frame.html",
- "Accept": "*/*",
- "Accept-Encoding": "gzip, deflate, br"
- }
-
- def create_widgets(self):
- """创建界面组件"""
- main_frame = ttk.Frame(self.root, padding="10")
- main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
-
- self.root.columnconfigure(0, weight=1)
- self.root.rowconfigure(0, weight=1)
- main_frame.columnconfigure(0, weight=1)
- main_frame.rowconfigure(6, weight=1) # 调整行索引
-
- # Token设置区域
- token_frame = ttk.LabelFrame(main_frame, text="Token设置", padding="10")
- token_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
- token_frame.columnconfigure(1, weight=1)
-
- ttk.Label(token_frame, text="Ahs-Token:", font=("Arial", 10)).grid(row=0, column=0, sticky=tk.W, padx=(0, 10))
- self.token_var = tk.StringVar(value=self.token)
- self.token_entry = ttk.Entry(token_frame, textvariable=self.token_var, width=60, font=("Arial", 10))
- self.token_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(0, 10))
-
- self.save_token_btn = ttk.Button(token_frame, text="保存Token", command=self.save_token, width=12)
- self.save_token_btn.grid(row=0, column=2)
-
- # 查询区域
- query_frame = ttk.LabelFrame(main_frame, text="查询条件", padding="10")
- query_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
- query_frame.columnconfigure(1, weight=1)
- query_frame.columnconfigure(3, weight=1)
-
- # 机型输入
- ttk.Label(query_frame, text="机型:", font=("Arial", 11)).grid(row=0, column=0, sticky=tk.W, padx=(0, 10))
- self.model_entry = ttk.Entry(query_frame, width=35, font=("Arial", 11))
- self.model_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(0, 10))
- self.model_entry.insert(0, "iPhone 15 Pro")
-
- # 排序选择
- ttk.Label(query_frame, text="排序方式:", font=("Arial", 11)).grid(row=0, column=2, sticky=tk.W, padx=(10, 10))
- self.sort_var = tk.StringVar(value="综合排序")
- self.sort_combo = ttk.Combobox(query_frame, textvariable=self.sort_var,
- values=["综合排序", "价格从低到高", "价格从高到低", "最新上架", "人气最高"],
- width=15, state="readonly", font=("Arial", 10))
- self.sort_combo.grid(row=0, column=3, sticky=(tk.W, tk.E), padx=(0, 10))
- self.sort_combo.bind('<<ComboboxSelected>>', self.on_sort_changed)
-
- # 搜索按钮
- self.search_btn = ttk.Button(query_frame, text="搜索", command=self.search_products, width=15)
- self.search_btn.grid(row=0, column=4)
-
- # ==================== 筛选区域 ====================
- # 第一行:内存 + 电池效率(各占一半)
- filter_row1 = ttk.Frame(main_frame)
- filter_row1.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=(0, 5))
- filter_row1.columnconfigure(0, weight=1)
- filter_row1.columnconfigure(1, weight=1)
-
- # 内存筛选
- memory_frame = ttk.LabelFrame(filter_row1, text="内存(多选)", padding="5")
- memory_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 5))
-
- self.memory_vars = {}
- memory_options = ["1T", "512G", "256G", "128G"]
- for i, option in enumerate(memory_options):
- var = tk.BooleanVar()
- self.memory_vars[option] = var
- cb = ttk.Checkbutton(memory_frame, text=option, variable=var)
- cb.grid(row=0, column=i, sticky=tk.W, padx=15, pady=3)
-
- # 电池效率筛选
- battery_frame = ttk.LabelFrame(filter_row1, text="电池效率(多选)", padding="5")
- battery_frame.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(5, 0))
-
- self.battery_vars = {}
- battery_options = ["100%", "95%-99%", "90%-95%", "85%-90%", "80%-85%", "70%-80%", "70%以下", "不支持"]
- for i, option in enumerate(battery_options):
- var = tk.BooleanVar()
- self.battery_vars[option] = var
- row = i // 4
- col = i % 4
- cb = ttk.Checkbutton(battery_frame, text=option, variable=var)
- cb.grid(row=row, column=col, sticky=tk.W, padx=10, pady=3)
-
- # 第二行:成色 + 状况标签(各占一半)
- filter_row2 = ttk.Frame(main_frame)
- filter_row2.grid(row=3, column=0, sticky=(tk.W, tk.E), pady=(0, 5))
- filter_row2.columnconfigure(0, weight=1)
- filter_row2.columnconfigure(1, weight=1)
-
- # 成色筛选
- fineness_frame = ttk.LabelFrame(filter_row2, text="成色(多选)", padding="5")
- fineness_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 5))
-
- self.fineness_vars = {}
- fineness_options = ["全新仅拆封", "准新机", "99新", "95新", "9成新", "8成新", "7成新"]
- for i, option in enumerate(fineness_options):
- var = tk.BooleanVar()
- self.fineness_vars[option] = var
- cb = ttk.Checkbutton(fineness_frame, text=option, variable=var)
- cb.grid(row=0, column=i, sticky=tk.W, padx=10, pady=3)
-
- # 状况标签筛选
- condition_frame = ttk.LabelFrame(filter_row2, text="状况标签(多选)", padding="5")
- condition_frame.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(5, 0))
-
- self.condition_vars = {}
- condition_items = list(self.condition_tags.items())
- for i, (tag_id, tag_name) in enumerate(condition_items):
- var = tk.BooleanVar()
- self.condition_vars[tag_id] = var
- row = i // 5
- col = i % 5
- cb = ttk.Checkbutton(condition_frame, text=tag_name, variable=var)
- cb.grid(row=row, column=col, sticky=tk.W, padx=10, pady=3)
-
- # ==================== 自动检测区域 ====================
- auto_detect_frame = ttk.LabelFrame(main_frame, text="自动检测与收藏", padding="10")
- auto_detect_frame.grid(row=4, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
- auto_detect_frame.columnconfigure(2, weight=1)
-
- # 循环次数阈值设置
- ttk.Label(auto_detect_frame, text="循环次数少于:", font=("Arial", 10)).grid(row=0, column=0, sticky=tk.W, padx=(0, 5))
- self.cycle_threshold_var = tk.StringVar(value="100")
- self.cycle_threshold_entry = ttk.Entry(auto_detect_frame, textvariable=self.cycle_threshold_var, width=10)
- self.cycle_threshold_entry.grid(row=0, column=1, sticky=tk.W, padx=(0, 10))
- ttk.Label(auto_detect_frame, text="次", font=("Arial", 10)).grid(row=0, column=2, sticky=tk.W, padx=(0, 20))
-
- # 启动按钮
- self.start_auto_btn = ttk.Button(auto_detect_frame, text="🚀 启动自动检测", command=self.start_auto_detect, width=18)
- self.start_auto_btn.grid(row=0, column=3, padx=(0, 10))
-
- # 停止按钮
- self.stop_auto_btn = ttk.Button(auto_detect_frame, text="⏹ 停止", command=self.stop_auto_detect, width=12, state="disabled")
- self.stop_auto_btn.grid(row=0, column=4, padx=(0, 20))
-
- # 自动检测状态显示(使用Label而不是StringVar)
- self.auto_status_label = ttk.Label(auto_detect_frame, text="自动检测未启动", font=("Arial", 9))
- self.auto_status_label.grid(row=0, column=5, sticky=tk.W)
-
- # 统计信息
- self.auto_stats_var = tk.StringVar()
- self.auto_stats_var.set("检测: 0 | 收藏: 0")
- stats_label = ttk.Label(auto_detect_frame, textvariable=self.auto_stats_var, font=("Arial", 9))
- stats_label.grid(row=0, column=6, sticky=tk.W, padx=(20, 0))
-
- # ==================== 结果显示区域 ====================
- result_frame = ttk.LabelFrame(main_frame, text="查询结果(可多选商品,点击批量收藏)", padding="10")
- result_frame.grid(row=5, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
- result_frame.columnconfigure(0, weight=1)
- result_frame.rowconfigure(0, weight=1)
-
- # 添加电池效率列
- columns = ("名称", "价格", "电池效率", "循环次数", "成色", "内存", "颜色", "网络制式")
- self.result_tree = ttk.Treeview(result_frame, columns=columns, show="headings", height=15, selectmode="extended")
-
- self.result_tree.heading("名称", text="名称")
- self.result_tree.heading("价格", text="价格")
- self.result_tree.heading("电池效率", text="电池效率")
- self.result_tree.heading("循环次数", text="循环次数")
- self.result_tree.heading("成色", text="成色")
- self.result_tree.heading("内存", text="内存")
- self.result_tree.heading("颜色", text="颜色")
- self.result_tree.heading("网络制式", text="网络制式")
-
- self.result_tree.column("名称", width=350)
- self.result_tree.column("价格", width=90)
- self.result_tree.column("电池效率", width=100)
- self.result_tree.column("循环次数", width=90)
- self.result_tree.column("成色", width=90)
- self.result_tree.column("内存", width=70)
- self.result_tree.column("颜色", width=90)
- self.result_tree.column("网络制式", width=90)
-
- scrollbar = ttk.Scrollbar(result_frame, orient=tk.VERTICAL, command=self.result_tree.yview)
- self.result_tree.configure(yscrollcommand=scrollbar.set)
- self.result_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
- scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
-
- # ==================== 底部按钮栏 ====================
- bottom_frame = ttk.Frame(main_frame)
- bottom_frame.grid(row=6, column=0, sticky=(tk.W, tk.E), pady=(10, 5))
-
- self.check_price_btn = ttk.Button(bottom_frame, text="获取循环次数", command=self.check_prices, width=18)
- self.check_price_btn.pack(side=tk.LEFT, padx=(0, 10))
-
- self.batch_collect_btn = ttk.Button(bottom_frame, text="批量收藏所选商品", command=self.batch_collect, width=20)
- self.batch_collect_btn.pack(side=tk.LEFT, padx=(0, 20))
-
- self.progress_var = tk.StringVar()
- self.progress_var.set("")
- ttk.Label(bottom_frame, textvariable=self.progress_var, font=("Arial", 9)).pack(side=tk.LEFT, padx=(20, 0))
-
- # ==================== 分页栏 ====================
- pagination_frame = ttk.Frame(main_frame)
- pagination_frame.grid(row=7, column=0, sticky=(tk.W, tk.E), pady=(0, 5))
-
- self.prev_btn = ttk.Button(pagination_frame, text="上一页", command=self.prev_page, width=10)
- self.prev_btn.pack(side=tk.LEFT, padx=(0, 10))
-
- self.next_btn = ttk.Button(pagination_frame, text="下一页", command=self.next_page, width=10)
- self.next_btn.pack(side=tk.LEFT, padx=(0, 20))
-
- ttk.Label(pagination_frame, text="第").pack(side=tk.LEFT)
- self.page_entry = ttk.Entry(pagination_frame, width=8)
- self.page_entry.pack(side=tk.LEFT, padx=(5, 5))
- ttk.Label(pagination_frame, text="页").pack(side=tk.LEFT)
-
- self.jump_btn = ttk.Button(pagination_frame, text="跳转", command=self.jump_to_page, width=8)
- self.jump_btn.pack(side=tk.LEFT, padx=(10, 20))
-
- self.page_info_var = tk.StringVar()
- self.page_info_var.set("第 0 / 0 页")
- page_label = ttk.Label(pagination_frame, textvariable=self.page_info_var, font=("Arial", 9))
- page_label.pack(side=tk.LEFT)
-
- # ==================== 状态栏 ====================
- status_frame = ttk.Frame(main_frame)
- status_frame.grid(row=8, column=0, sticky=(tk.W, tk.E), pady=(5, 0))
-
- self.status_var = tk.StringVar()
- self.status_var.set("就绪")
- status_bar = ttk.Label(status_frame, textvariable=self.status_var, relief=tk.SUNKEN)
- status_bar.pack(side=tk.LEFT, fill=tk.X, expand=True)
-
- self.update_pagination_buttons()
-
- def on_sort_changed(self, event=None):
- """排序方式改变时自动搜索"""
- if self.model_entry.get().strip():
- self.search_products()
-
- def get_selected_memory(self):
- """获取选中的内存PPV ID列表"""
- selected = []
- for option, var in self.memory_vars.items():
- if var.get():
- selected.append(self.memory_map[option])
- return selected
-
- def get_selected_battery(self):
- """获取选中的电池效率PPV ID列表"""
- selected = []
- for option, var in self.battery_vars.items():
- if var.get():
- selected.append(self.battery_map[option])
- return selected
-
- def get_selected_fineness(self):
- fineness_map = {
- "全新仅拆封": 111,
- "准新机": 100,
- "99新": 99,
- "95新": 95,
- "9成新": 90,
- "8成新": 80,
- "7成新": 70
- }
- selected = []
- for option, var in self.fineness_vars.items():
- if var.get():
- selected.append(fineness_map[option])
- return selected
-
- def get_selected_condition_tags(self):
- selected = []
- for tag_id, var in self.condition_vars.items():
- if var.get():
- selected.append(tag_id)
- return selected
-
- def get_battery_efficiency(self, condition_labels):
- """从conditionLabels中提取电池效率"""
- if not condition_labels:
- return ""
-
- for label in condition_labels:
- if label.get('group') in ['原厂电池', '第三方电池']:
- return label.get('label', '')
- return ""
-
- def search_products(self, page=0):
- keyword = self.model_entry.get().strip()
- if not keyword:
- messagebox.showwarning("警告", "请输入机型")
- return
-
- self.current_keyword = keyword
- self.current_page = page
- # 获取当前选中的排序方式
- self.current_sort = self.sort_map.get(self.sort_var.get(), "sort_composite")
-
- for item in self.result_tree.get_children():
- self.result_tree.delete(item)
- self.current_products.clear()
- self.progress_var.set("")
- self.check_price_btn.config(state="normal")
- self.batch_collect_btn.config(state="normal")
-
- self.status_var.set("正在搜索...")
- self.search_btn.config(state="disabled")
- self.prev_btn.config(state="disabled")
- self.next_btn.config(state="disabled")
- self.jump_btn.config(state="disabled")
-
- thread = threading.Thread(target=self.do_search, args=(keyword, page))
- thread.daemon = True
- thread.start()
-
- def do_search(self, keyword, page):
- try:
- # 获取筛选条件
- memory_ids = self.get_selected_memory()
- battery_ids = self.get_selected_battery()
- fineness_ids = self.get_selected_fineness()
- condition_tags = self.get_selected_condition_tags()
-
- request_data = {
- "sortValue": self.current_sort, # 使用当前选中的排序方式
- "scene": "search",
- "keyword": keyword,
- "sirReq": False,
- "cityId": 324,
- "pageIndex": page,
- "pageSize": self.page_size
- }
-
- # 添加内存筛选(使用 gaeaSkuPpvIds)
- if memory_ids:
- request_data["gaeaSkuPpvIds"] = {
- "22": memory_ids # 22是内存的ppnId
- }
-
- # 添加电池效率筛选(使用 gaeaPricePpvIds)
- if battery_ids:
- request_data["gaeaPricePpvIds"] = {
- "473": battery_ids # 473是电池效率的ppnId
- }
-
- # 添加成色筛选
- if fineness_ids:
- request_data["gaeaFinenessIds"] = fineness_ids
-
- # 添加状况标签筛选
- if condition_tags:
- request_data["conditionTagList"] = condition_tags
-
- url = "https://dubai-mp.aihuishou.com/ahs-yanxuan-service/products/search-goods-v2"
- response = requests.post(url, json=request_data, headers=self.get_headers(), timeout=30)
- result = response.json()
- print("请求参数:", json.dumps(request_data, ensure_ascii=False))
- self.root.after(0, self.display_results, result, page)
-
- except Exception as e:
- self.root.after(0, self.show_error, str(e))
-
- def parse_product_info(self, product):
- name = product.get('name', '')
- sale_goods_no = product.get('saleGoodsNo', '')
- product_no = product.get('productNo', '')
-
- # 提取颜色
- color = ""
- color_keywords = ['黑色', '白色', '蓝色', '原色', '金色', '银色', '石墨色', '紫色', '绿色', '粉色', '红色', '黄色', '暗紫色', '深空黑色']
- for keyword in color_keywords:
- if keyword in name:
- color = keyword
- break
-
- # 获取电池效率
- condition_labels = product.get('conditionLabels', [])
- battery_efficiency = self.get_battery_efficiency(condition_labels)
-
- # 如果conditionLabels中没有,从productTag中获取
- if not battery_efficiency:
- product_tags = product.get('productTag', [])
- for tag in product_tags:
- if '电池' in tag:
- battery_efficiency = tag
- break
-
- return {
- 'name': name[:50],
- 'price': product.get('price', 0),
- 'battery_efficiency': battery_efficiency,
- 'cycle_count': '',
- 'fineness': product.get('gaeaFinenessName', ''),
- 'memory': product.get('memoryDesc', ''),
- 'color': color,
- 'network': "全网通",
- 'saleGoodsNo': sale_goods_no,
- 'productNo': product_no
- }
-
- def display_results(self, result, page):
- self.search_btn.config(state="normal")
- self.jump_btn.config(state="normal")
-
- if result.get('code') != 0:
- self.status_var.set(f"查询失败: {result.get('resultMessage', '未知错误')}")
- messagebox.showerror("错误", result.get('resultMessage', '查询失败'))
- return
-
- data = result.get('data', [])
- total_count = result.get('totalCount', 0)
-
- if total_count > 0:
- self.total_pages = (total_count + self.page_size - 1) // self.page_size
- else:
- if len(data) < self.page_size:
- self.total_pages = page + 1
- else:
- self.total_pages = page + 2
-
- if not data:
- self.status_var.set("未找到相关产品")
- messagebox.showinfo("提示", "未找到相关产品")
- self.update_pagination_buttons()
- return
-
- for product in data:
- info = self.parse_product_info(product)
- item_id = self.result_tree.insert("", tk.END, values=(
- info['name'],
- f"¥{info['price']}",
- info['battery_efficiency'],
- info['cycle_count'],
- info['fineness'],
- info['memory'],
- info['color'],
- info['network']
- ))
- self.current_products.append({
- 'item_id': item_id,
- 'saleGoodsNo': info['saleGoodsNo'],
- 'productNo': info['productNo'],
- 'info': info
- })
-
- sort_name = self.sort_var.get()
- self.status_var.set(f"第 {page + 1} 页,排序: {sort_name},共找到 {len(data)} 条结果")
- self.update_pagination_buttons()
-
- def update_pagination_buttons(self):
- self.page_info_var.set(f"第 {self.current_page + 1} / {self.total_pages if self.total_pages > 0 else 1} 页")
-
- if self.current_page <= 0:
- self.prev_btn.config(state="disabled")
- else:
- self.prev_btn.config(state="normal")
- self.next_btn.config(state="normal")
-
- if self.total_pages > 0 and self.current_page >= self.total_pages - 1:
- self.next_btn.config(state="disabled")
- else:
- if len(self.current_products) >= self.page_size:
- self.next_btn.config(state="normal")
- else:
- self.next_btn.config(state="disabled")
-
- def prev_page(self):
- if self.current_page > 0:
- self.search_products(self.current_page - 1)
-
- def next_page(self):
- if self.total_pages == 0 or self.current_page < self.total_pages - 1:
- self.search_products(self.current_page + 1)
-
- def jump_to_page(self):
- try:
- page_num = int(self.page_entry.get().strip())
- if page_num < 1:
- messagebox.showwarning("警告", "页码必须大于0")
- return
- if self.total_pages > 0 and page_num > self.total_pages:
- messagebox.showwarning("警告", f"页码不能超过 {self.total_pages}")
- return
- self.search_products(page_num - 1)
- self.page_entry.delete(0, tk.END)
- except ValueError:
- messagebox.showwarning("警告", "请输入有效的页码")
-
- def get_cycle_count(self, sale_goods_no):
- """获取商品的电池循环次数"""
- try:
- url = f"https://dubai-mp.aihuishou.com/ahs-yanxuan-service/products/goods-tag-param?saleGoodsNo={sale_goods_no}"
- response = requests.get(url, headers=self.get_headers(), timeout=10)
- result = response.json()
-
- if result.get('code') == 0 and 'data' in result:
- data = result['data']
- if 'machineConditionList' in data:
- for item in data['machineConditionList']:
- if item.get('name') == '充电次数':
- return item.get('value', '')
- if 'aggConditionTagParamList' in data:
- for group in data['aggConditionTagParamList']:
- if group.get('groupName') == '核心机况':
- for item in group.get('valueList', []):
- if item.get('name') == '充电次数':
- return item.get('value', '')
- return ''
- except Exception as e:
- print(f"获取循环次数失败: {e}")
- return ''
-
- def add_to_collection(self, item_no):
- try:
- url = "https://dubai-mp.aihuishou.com/ahs-yanxuan-service/collect/save"
- payload = json.dumps({"itemNo": item_no, "type": 1})
- headers = self.get_headers()
-
- response = requests.post(url, data=payload, headers=headers, timeout=10)
- result = response.json()
-
- if result.get('code') == 200 and result.get('data') == True:
- return True, "收藏成功"
- else:
- return False, result.get('resultMessage', '收藏失败')
- except Exception as e:
- return False, str(e)
-
- def batch_collect(self):
- selected_items = self.result_tree.selection()
- if not selected_items:
- messagebox.showwarning("警告", "请先选择要收藏的商品(可多选)")
- return
-
- result = messagebox.askyesno("确认收藏", f"确定要收藏选中的 {len(selected_items)} 个商品吗?")
- if not result:
- return
-
- thread = threading.Thread(target=self.process_batch_collect, args=(selected_items,))
- thread.daemon = True
- thread.start()
-
- def process_batch_collect(self, selected_items):
- self.batch_collect_btn.config(state="disabled")
- self.check_price_btn.config(state="disabled")
-
- success_count = 0
- fail_count = 0
- total = len(selected_items)
-
- for i, item_id in enumerate(selected_items):
- product = None
- for p in self.current_products:
- if p['item_id'] == item_id:
- product = p
- break
-
- if product:
- item_no = product['productNo'] or product['saleGoodsNo']
- self.root.after(0, lambda txt=f"收藏中: {i+1}/{total}": self.progress_var.set(txt))
-
- success, msg = self.add_to_collection(item_no)
-
- if success:
- success_count += 1
- else:
- fail_count += 1
- print(f"收藏失败: {product['info']['name']} - {msg}")
-
- time.sleep(0.2)
-
- self.root.after(0, lambda: self.finish_batch_collect(success_count, fail_count, total))
-
- def finish_batch_collect(self, success_count, fail_count, total):
- self.batch_collect_btn.config(state="normal")
- self.check_price_btn.config(state="normal")
- self.progress_var.set("")
-
- if fail_count == 0:
- self.status_var.set(f"批量收藏完成!成功收藏 {success_count} 个商品")
- messagebox.showinfo("批量收藏完成", f"成功收藏 {success_count} 个商品!")
- else:
- self.status_var.set(f"批量收藏完成:成功 {success_count},失败 {fail_count}")
- messagebox.showwarning("批量收藏完成", f"成功收藏 {success_count} 个商品\n失败 {fail_count} 个商品")
-
- def check_prices(self):
- if not self.current_products:
- messagebox.showwarning("警告", "请先搜索商品")
- return
- if self.is_loading_cycles:
- messagebox.showinfo("提示", "正在获取中,请稍候...")
- return
-
- thread = threading.Thread(target=self.process_check_prices)
- thread.daemon = True
- thread.start()
-
- def process_check_prices(self):
- self.is_loading_cycles = True
- self.check_price_btn.config(state="disabled")
- self.batch_collect_btn.config(state="disabled")
-
- total = len(self.current_products)
-
- for i, product in enumerate(self.current_products):
- self.root.after(0, lambda txt=f"获取中: {i+1}/{total}": self.progress_var.set(txt))
-
- cycle_count = self.get_cycle_count(product['saleGoodsNo'])
-
- if cycle_count:
- values = list(self.result_tree.item(product['item_id'], 'values'))
- values[3] = cycle_count
- self.root.after(0, lambda pid=product['item_id'], vals=values: self.result_tree.item(pid, values=vals))
-
- time.sleep(0.3)
-
- self.root.after(0, self.finish_check_prices)
-
- def finish_check_prices(self):
- self.is_loading_cycles = False
- self.check_price_btn.config(state="normal")
- self.batch_collect_btn.config(state="normal")
- self.progress_var.set("")
- self.status_var.set(f"完成!已获取 {len(self.current_products)} 条商品的循环次数")
- messagebox.showinfo("完成", f"已成功获取 {len(self.current_products)} 条商品的循环次数")
-
- def show_context_menu(self, event):
- item = self.result_tree.identify_row(event.y)
- if not item:
- return
-
- self.result_tree.selection_set(item)
- values = self.result_tree.item(item, 'values')
- product_name = values[0]
- battery = values[2]
- cycle_count = values[3]
-
- menu = tk.Menu(self.root, tearoff=0)
- menu.add_command(label=f"收藏: {product_name[:30]}", command=lambda: self.collect_single_item(item))
- if battery:
- menu.add_command(label=f"电池: {battery}", command=None, state="disabled")
- if cycle_count:
- menu.add_command(label=f"循环次数: {cycle_count}", command=None, state="disabled")
- menu.add_separator()
- menu.add_command(label="取消", command=None)
- menu.post(event.x_root, event.y_root)
-
- def collect_single_item(self, item):
- for product in self.current_products:
- if product['item_id'] == item:
- item_no = product['productNo'] or product['saleGoodsNo']
- success, msg = self.add_to_collection(item_no)
-
- if success:
- self.status_var.set(f"✓ 收藏成功: {product['info']['name'][:30]}")
- messagebox.showinfo("收藏成功", f"已成功收藏\n{product['info']['name']}")
- else:
- self.status_var.set(f"✗ 收藏失败: {msg}")
- messagebox.showerror("收藏失败", f"收藏失败\n{product['info']['name']}\n错误: {msg}")
- return
-
- # ==================== 自动检测功能 ====================
- def start_auto_detect(self):
- """启动自动检测"""
- # 检查是否已启动
- if self.auto_detect_running:
- messagebox.showinfo("提示", "自动检测已在运行中")
- return
-
- # 检查是否有搜索关键词
- keyword = self.model_entry.get().strip()
- if not keyword:
- messagebox.showwarning("警告", "请先输入要搜索的机型")
- return
-
- # 获取阈值
- try:
- threshold = int(self.cycle_threshold_var.get().strip())
- if threshold < 0:
- raise ValueError("阈值不能为负数")
- except ValueError:
- messagebox.showerror("错误", "请输入有效的循环次数阈值(正整数)")
- return
-
- # 确认启动
- result = messagebox.askyesno("确认启动",
- f"将自动检测所有符合条件的商品\n"
- f"机型: {keyword}\n"
- f"循环次数阈值: {threshold} 次\n\n"
- f"检测到的商品将自动收藏,是否继续?")
- if not result:
- return
-
- # 重置状态
- self.auto_detect_running = True
- self.auto_detect_stop = False
- self.auto_detect_page = 0
- self.auto_detect_products = []
- self.auto_collect_count = 0
- self.auto_check_count = 0
-
- # 更新UI状态
- self.start_auto_btn.config(state="disabled")
- self.stop_auto_btn.config(state="normal")
- self.auto_status_label.config(text="🔄 正在检测中...", foreground="blue")
- self.auto_stats_var.set("检测: 0 | 收藏: 0")
-
- # 清空当前显示
- for item in self.result_tree.get_children():
- self.result_tree.delete(item)
- self.current_products.clear()
-
- # 启动检测线程
- self.auto_detect_thread = threading.Thread(target=self.auto_detect_loop, args=(keyword, threshold))
- self.auto_detect_thread.daemon = True
- self.auto_detect_thread.start()
-
- def stop_auto_detect(self):
- """停止自动检测"""
- if self.auto_detect_running:
- self.auto_detect_stop = True
- self.auto_status_label.config(text="⏹ 正在停止...", foreground="orange")
- self.stop_auto_btn.config(state="disabled")
-
- def auto_detect_loop(self, keyword, threshold):
- """自动检测循环"""
- page = 0
- total_collected = 0
- total_checked = 0
-
- while not self.auto_detect_stop:
- try:
- # 搜索商品
- self.root.after(0, lambda: self.auto_status_label.config(
- text=f"🔄 正在检测第 {page + 1} 页...", foreground="blue"))
-
- # 执行搜索
- memory_ids = self.get_selected_memory()
- battery_ids = self.get_selected_battery()
- fineness_ids = self.get_selected_fineness()
- condition_tags = self.get_selected_condition_tags()
-
- request_data = {
- "sortValue": "sort_composite",
- "scene": "search",
- "keyword": keyword,
- "sirReq": False,
- "cityId": 324,
- "pageIndex": page,
- "pageSize": self.page_size
- }
-
- if memory_ids:
- request_data["gaeaSkuPpvIds"] = {"22": memory_ids}
- if battery_ids:
- request_data["gaeaPricePpvIds"] = {"473": battery_ids}
- if fineness_ids:
- request_data["gaeaFinenessIds"] = fineness_ids
- if condition_tags:
- request_data["conditionTagList"] = condition_tags
-
- url = "https://dubai-mp.aihuishou.com/ahs-yanxuan-service/products/search-goods-v2"
- response = requests.post(url, json=request_data, headers=self.get_headers(), timeout=30)
- result = response.json()
-
- if result.get('code') != 0:
- self.root.after(0, lambda: self.show_error(f"搜索失败: {result.get('resultMessage', '未知错误')}"))
- break
-
- data = result.get('data', [])
- total_count = result.get('totalCount', 0)
-
- # 计算总页数
- if total_count > 0:
- total_pages = (total_count + self.page_size - 1) // self.page_size
- else:
- total_pages = page + 1 if len(data) < self.page_size else page + 2
-
- # 如果没有数据,结束
- if not data:
- self.root.after(0, lambda: self.auto_status_label.config(
- text="✅ 检测完成,没有更多商品", foreground="green"))
- break
-
- # 处理当前页商品
- page_collected = 0
- for product in data:
- if self.auto_detect_stop:
- break
-
- total_checked += 1
-
- # 获取商品信息
- sale_goods_no = product.get('saleGoodsNo', '')
- product_no = product.get('productNo', '')
- name = product.get('name', '')
-
- # 获取循环次数
- cycle_count = self.get_cycle_count(sale_goods_no)
-
- # 解析循环次数为数字
- cycle_num = 0
- if cycle_count:
- try:
- # 尝试提取数字
- numbers = re.findall(r'\d+', cycle_count)
- if numbers:
- cycle_num = int(numbers[0])
- except:
- pass
-
- # 判断是否满足条件
- if cycle_num > 0 and cycle_num <= threshold:
- # 满足条件,收藏
- item_no = product_no or sale_goods_no
- success, msg = self.add_to_collection(item_no)
-
- if success:
- total_collected += 1
- page_collected += 1
- # 在列表中显示
- self.root.after(0, lambda p=product, c=cycle_count: self.display_auto_collected(p, c))
- else:
- # 收藏失败,记录日志
- print(f"自动收藏失败: {name} - {msg}")
-
- # 更新统计
- self.root.after(0, lambda tc=total_checked, tl=total_collected:
- self.auto_stats_var.set(f"检测: {tc} | 收藏: {tl}"))
-
- # 延时避免请求过快
- time.sleep(0.2)
-
- # 更新页面信息
- self.root.after(0, lambda p=page+1, pc=page_collected, tc=total_checked, tl=total_collected:
- self.auto_status_label.config(
- text=f"🔄 第 {p} 页完成,本页收藏 {pc} 个", foreground="blue"))
-
- # 检查是否到达最后一页
- if page >= total_pages - 1 or len(data) < self.page_size:
- self.root.after(0, lambda: self.auto_status_label.config(
- text="✅ 检测完成!已检测所有页面", foreground="green"))
- break
-
- page += 1
-
- # 检查是否被停止
- if self.auto_detect_stop:
- break
-
- # 页面间延时
- time.sleep(0.5)
-
- except Exception as e:
- self.root.after(0, lambda: self.show_error(f"自动检测出错: {e}"))
- break
-
- # 完成或停止
- self.root.after(0, self.finish_auto_detect, total_checked, total_collected)
-
- def display_auto_collected(self, product, cycle_count):
- """显示自动收藏的商品(高亮标记)"""
- info = self.parse_product_info(product)
- item_id = self.result_tree.insert("", tk.END, values=(
- info['name'],
- f"¥{info['price']}",
- info['battery_efficiency'],
- cycle_count,
- info['fineness'],
- info['memory'],
- info['color'],
- info['network']
- ))
-
- # 标记为已收藏(绿色背景)
- self.result_tree.tag_configure('collected', background='#90EE90')
- self.result_tree.item(item_id, tags=('collected',))
-
- # 保存到当前商品列表
- self.current_products.append({
- 'item_id': item_id,
- 'saleGoodsNo': info['saleGoodsNo'],
- 'productNo': info['productNo'],
- 'info': info
- })
-
- def finish_auto_detect(self, total_checked, total_collected):
- """完成自动检测"""
- self.auto_detect_running = False
- self.start_auto_btn.config(state="normal")
- self.stop_auto_btn.config(state="disabled")
-
- if self.auto_detect_stop:
- self.auto_status_label.config(
- text=f"⏹ 已停止 - 检测: {total_checked} | 收藏: {total_collected}",
- foreground="orange")
- else:
- self.auto_status_label.config(
- text=f"✅ 完成 - 检测: {total_checked} | 收藏: {total_collected}",
- foreground="green")
-
- self.auto_stats_var.set(f"检测: {total_checked} | 收藏: {total_collected}")
-
- # 显示完成消息
- if total_collected > 0:
- messagebox.showinfo("自动检测完成",
- f"检测完成!\n\n"
- f"共检测商品: {total_checked} 个\n"
- f"成功收藏: {total_collected} 个")
- else:
- if not self.auto_detect_stop:
- messagebox.showinfo("自动检测完成",
- f"检测完成!\n\n"
- f"共检测商品: {total_checked} 个\n"
- f"没有找到符合条件的商品")
-
- def show_error(self, error_msg):
- """显示错误信息"""
- self.search_btn.config(state="normal")
- self.jump_btn.config(state="normal")
- self.status_var.set(f"查询失败: {error_msg}")
- messagebox.showerror("错误", f"查询失败: {error_msg}")
- def main():
- root = tk.Tk()
- app = PhoneQueryApp(root)
- root.mainloop()
- if __name__ == "__main__":
- main()
|