EntryGateController.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. //
  2. // LoginQuestionViewController.swift
  3. // RoderickRalph
  4. //
  5. // Created by AI Assistant on 2025/09/16.
  6. //
  7. import Foundation
  8. import UIKit
  9. //import sys/utsname.h
  10. class EntryGateController: UIViewController, RoutePickerDelegate {
  11. // MARK: - API Endpoints
  12. private let pathGetRoutes = "/ditch/list"
  13. private let pathSetRoute = "/wx/iosLogin"
  14. // MARK: - UI Components
  15. private let backdropImage: UIImageView = {
  16. let imageView = UIImageView()
  17. imageView.image = UIImage(named: "res001")
  18. imageView.contentMode = .scaleAspectFill
  19. imageView.translatesAutoresizingMaskIntoConstraints = false
  20. return imageView
  21. }()
  22. private let enterBtn: UIButton = {
  23. let button = UIButton(type: .system)
  24. button.setTitle("登录", for: .normal)
  25. button.setTitleColor(.black, for: .normal)
  26. button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24)
  27. button.backgroundColor = .white
  28. button.layer.cornerRadius = 25
  29. button.translatesAutoresizingMaskIntoConstraints = false
  30. return button
  31. }()
  32. private let routeBtn: UIButton = {
  33. let button = UIButton(type: .system)
  34. button.setTitle("渠道 ▼", for: .normal)
  35. button.setTitleColor(.black, for: .normal)
  36. button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
  37. button.backgroundColor = .white
  38. button.layer.cornerRadius = 20
  39. button.contentHorizontalAlignment = .center
  40. button.translatesAutoresizingMaskIntoConstraints = false
  41. return button
  42. }()
  43. // MARK: - Properties
  44. private var routePopup: RoutePickerView?
  45. // MARK: - Device Model Helper
  46. private func deviceModel() -> String {
  47. var systemInfo = utsname()
  48. uname(&systemInfo)
  49. let machineMirror = Mirror(reflecting: systemInfo.machine)
  50. let identifier = machineMirror.children.reduce("") { identifier, element in
  51. guard let value = element.value as? Int8, value != 0 else { return identifier }
  52. return identifier + String(UnicodeScalar(UInt8(value)))
  53. }
  54. return deviceNameFor(identifier)
  55. }
  56. private func deviceNameFor(_ identifier: String) -> String {
  57. switch identifier {
  58. // iPhone
  59. case "iPhone1,1": return "iPhone"
  60. case "iPhone1,2": return "iPhone 3G"
  61. case "iPhone2,1": return "iPhone 3GS"
  62. case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
  63. case "iPhone4,1": return "iPhone 4S"
  64. case "iPhone5,1", "iPhone5,2": return "iPhone 5"
  65. case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
  66. case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
  67. case "iPhone7,2": return "iPhone 6"
  68. case "iPhone7,1": return "iPhone 6 Plus"
  69. case "iPhone8,1": return "iPhone 6s"
  70. case "iPhone8,2": return "iPhone 6s Plus"
  71. case "iPhone8,4": return "iPhone SE"
  72. case "iPhone9,1", "iPhone9,3": return "iPhone 7"
  73. case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
  74. case "iPhone10,1", "iPhone10,4": return "iPhone 8"
  75. case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
  76. case "iPhone10,3", "iPhone10,6": return "iPhone X"
  77. case "iPhone11,2": return "iPhone XS"
  78. case "iPhone11,4", "iPhone11,6": return "iPhone XS Max"
  79. case "iPhone11,8": return "iPhone XR"
  80. case "iPhone12,1": return "iPhone 11"
  81. case "iPhone12,3": return "iPhone 11 Pro"
  82. case "iPhone12,5": return "iPhone 11 Pro Max"
  83. case "iPhone12,8": return "iPhone SE (2nd generation)"
  84. case "iPhone13,1": return "iPhone 12 mini"
  85. case "iPhone13,2": return "iPhone 12"
  86. case "iPhone13,3": return "iPhone 12 Pro"
  87. case "iPhone13,4": return "iPhone 12 Pro Max"
  88. case "iPhone14,2": return "iPhone 13"
  89. case "iPhone14,3": return "iPhone 13 mini"
  90. case "iPhone14,4": return "iPhone 13 Pro"
  91. case "iPhone14,5": return "iPhone 13 Pro Max"
  92. case "iPhone14,6": return "iPhone SE (3rd generation)"
  93. case "iPhone14,7": return "iPhone 14"
  94. case "iPhone14,8": return "iPhone 14 Plus"
  95. case "iPhone15,2": return "iPhone 14 Pro"
  96. case "iPhone15,3": return "iPhone 14 Pro Max"
  97. case "iPhone15,4": return "iPhone 15"
  98. case "iPhone15,5": return "iPhone 15 Plus"
  99. case "iPhone16,1": return "iPhone 15 Pro"
  100. case "iPhone16,2": return "iPhone 15 Pro Max"
  101. case "iPhone17,1": return "iPhone 16 Pro"
  102. case "iPhone17,2": return "iPhone 16 Pro Max"
  103. case "iPhone17,3": return "iPhone 16"
  104. case "iPhone17,4": return "iPhone 16 Plus"
  105. case "iPhone17,5": return "iPhone 16e"
  106. case "iPhone18,1": return "iPhone 17 Pro"
  107. case "iPhone18,2": return "iPhone 17 Pro Max"
  108. case "iPhone18,3": return "iPhone 17"
  109. case "iPhone18,4": return "iPhone Air"
  110. // iPad
  111. case "iPad1,1": return "iPad"
  112. case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad 2"
  113. case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)"
  114. case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)"
  115. case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
  116. case "iPad5,3", "iPad5,4": return "iPad Air 2"
  117. case "iPad6,11", "iPad6,12": return "iPad (5th generation)"
  118. case "iPad7,5", "iPad7,6": return "iPad (6th generation)"
  119. case "iPad7,11", "iPad7,12": return "iPad (7th generation)"
  120. case "iPad11,6", "iPad11,7": return "iPad (8th generation)"
  121. case "iPad12,1", "iPad12,2": return "iPad (9th generation)"
  122. case "iPad13,18", "iPad13,19": return "iPad (10th generation)"
  123. case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch)"
  124. case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)"
  125. case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)"
  126. case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)"
  127. case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": return "iPad Pro (11-inch)"
  128. case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": return "iPad Pro (12.9-inch) (3rd generation)"
  129. case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)"
  130. case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)"
  131. case "iPad13,4", "iPad13,5", "iPad13,6", "iPad13,7": return "iPad Pro (11-inch) (3rd generation)"
  132. case "iPad13,8", "iPad13,9", "iPad13,10", "iPad13,11": return "iPad Pro (12.9-inch) (5th generation)"
  133. case "iPad14,1", "iPad14,2": return "iPad mini (6th generation)"
  134. case "iPad14,3", "iPad14,4": return "iPad Pro (11-inch) (4th generation)"
  135. case "iPad14,5", "iPad14,6": return "iPad Pro (12.9-inch) (6th generation)"
  136. case "iPad14,8", "iPad14,9": return "iPad Air (11-inch) (6th generation)"
  137. case "iPad14,10", "iPad14,11": return "iPad Air (13-inch) (6th generation)"
  138. case "iPad15,3", "iPad15,4": return "iPad Air (11-inch) (7th generation)"
  139. case "iPad15,5", "iPad15,6": return "iPad Air (13-inch) (7th generation)"
  140. case "iPad15,7", "iPad15,8": return "iPad (11th generation)"
  141. case "iPad16,1", "iPad16,2": return "Pad mini (7th generation)"
  142. case "iPad16,3", "iPad16,4": return "iPad Pro (11-inch) (5th generation)"
  143. case "iPad16,5", "iPad16,6": return "iPad Pro (12.9-inch) (7th generation)"
  144. // iPod
  145. case "iPod1,1": return "iPod touch"
  146. case "iPod2,1": return "iPod touch (2nd generation)"
  147. case "iPod3,1": return "iPod touch (3rd generation)"
  148. case "iPod4,1": return "iPod touch (4th generation)"
  149. case "iPod5,1": return "iPod touch (5th generation)"
  150. case "iPod7,1": return "iPod touch (6th generation)"
  151. case "iPod9,1": return "iPod touch (7th generation)"
  152. // Simulator
  153. case "i386", "x86_64", "arm64": return "Simulator"
  154. default: return identifier
  155. }
  156. }
  157. private var channels: [Channel] = []
  158. private var selectedChannel: Channel?
  159. private var loginUserInfo: LoginUserInfo?
  160. // System loading overlay
  161. private var loadingOverlay: UIView?
  162. private var loadingSpinner: UIActivityIndicatorView?
  163. // MARK: - Lifecycle
  164. override func viewDidLoad() {
  165. super.viewDidLoad()
  166. buildUI()
  167. applyLayout()
  168. wireActions()
  169. // Hide navigation bar
  170. navigationController?.setNavigationBarHidden(true, animated: false)
  171. // Fetch channel list on load
  172. fetchRoutes()
  173. }
  174. override func viewWillAppear(_ animated: Bool) {
  175. super.viewWillAppear(animated)
  176. navigationController?.setNavigationBarHidden(true, animated: animated)
  177. }
  178. // MARK: - UI Setup
  179. private func buildUI() {
  180. view.addSubview(backdropImage)
  181. view.addSubview(enterBtn)
  182. view.addSubview(routeBtn)
  183. }
  184. private func applyLayout() {
  185. NSLayoutConstraint.activate([
  186. // Background image - fill entire screen
  187. backdropImage.topAnchor.constraint(equalTo: view.topAnchor),
  188. backdropImage.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  189. backdropImage.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  190. backdropImage.bottomAnchor.constraint(equalTo: view.bottomAnchor),
  191. // Login button - center of screen
  192. enterBtn.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  193. enterBtn.centerYAnchor.constraint(equalTo: view.centerYAnchor,constant: 50),
  194. enterBtn.widthAnchor.constraint(equalToConstant: 200),
  195. enterBtn.heightAnchor.constraint(equalToConstant: 50),
  196. // Channel select button - below login button
  197. routeBtn.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  198. routeBtn.topAnchor.constraint(equalTo: enterBtn.bottomAnchor, constant: 30),
  199. routeBtn.widthAnchor.constraint(equalToConstant: 200),
  200. routeBtn.heightAnchor.constraint(equalToConstant: 40)
  201. ])
  202. }
  203. private func wireActions() {
  204. enterBtn.addTarget(self, action: #selector(didTapLogin), for: .touchUpInside)
  205. routeBtn.addTarget(self, action: #selector(didTapChannelPicker), for: .touchUpInside)
  206. }
  207. // MARK: - Actions
  208. @objc private func didTapLogin() {
  209. guard let channel = selectedChannel else {
  210. flashToast(message: "请先选择渠道")
  211. return
  212. }
  213. submitRoute(channel: channel)
  214. }
  215. @objc private func didTapChannelPicker() {
  216. guard !channels.isEmpty else {
  217. flashToast(message: "渠道列表为空,请稍后重试")
  218. fetchRoutes() // Retry fetching
  219. return
  220. }
  221. presentRoutePicker(channels: channels)
  222. }
  223. // MARK: - Channel Selection Flow
  224. private func fetchRoutes() {
  225. guard let url = URL(string: apiBaseURL + pathGetRoutes) else {
  226. print("[Channel] Invalid getQudaoList URL")
  227. return
  228. }
  229. var request = URLRequest(url: url)
  230. request.httpMethod = "POST"
  231. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  232. let bodyParams: [String: Any] = ["appId": kTakuAppID]
  233. request.httpBody = try? JSONSerialization.data(withJSONObject: bodyParams, options: [])
  234. if let body = request.httpBody,
  235. let bodyString = String(data: body, encoding: .utf8) {
  236. print("[Channel] Request URL: \(url)")
  237. print("[Channel] Request Headers: \(request.allHTTPHeaderFields ?? [:])")
  238. print("[Channel] Request Body: \(bodyString)")
  239. }
  240. let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
  241. if let httpResponse = response as? HTTPURLResponse {
  242. print("[Channel] Response Code: \(httpResponse.statusCode)")
  243. print("[Channel] Response Headers: \(httpResponse.allHeaderFields)")
  244. }
  245. if let data = data, let responseString = String(data: data, encoding: .utf8) {
  246. print("[Channel] Response Body: \(responseString)")
  247. }
  248. if let error = error {
  249. print("[Channel] fetch error: \(error)")
  250. DispatchQueue.main.async { [weak self] in
  251. self?.flashToast(message: "网络错误,请重新登录")
  252. }
  253. return
  254. }
  255. guard let data = data else { return }
  256. let channels = self?.decodeRoutes(from: data) ?? []
  257. DispatchQueue.main.async {
  258. if channels.isEmpty {
  259. print("[Channel] No channels returned")
  260. self?.flashToast(message: "没有渠道信息,请重新登录")
  261. } else {
  262. self?.channels = channels
  263. // Set first channel as default if none selected
  264. if self?.selectedChannel == nil && !channels.isEmpty {
  265. self?.selectedChannel = channels[0]
  266. self?.refreshChannelTitle()
  267. }
  268. }
  269. }
  270. }
  271. task.resume()
  272. }
  273. private func decodeRoutes(from data: Data) -> [Channel] {
  274. func normalizeArray(_ arr: [Any]) -> [Channel] {
  275. var result: [Channel] = []
  276. for (idx, item) in arr.enumerated() {
  277. if let dict = item as? [String: Any] {
  278. let idAny = dict["id"] ?? dict["ditchId"] ?? dict["value"] ?? idx
  279. let nameAny = dict["name"] ?? dict["ditchName"] ?? dict["label"] ?? "\(idAny)"
  280. let idStr = String(describing: idAny)
  281. let nameStr = String(describing: nameAny)
  282. result.append(Channel(id: idStr, name: nameStr))
  283. } else if let str = item as? String {
  284. result.append(Channel(id: str, name: str))
  285. } else if let num = item as? NSNumber {
  286. let s = num.stringValue
  287. result.append(Channel(id: s, name: s))
  288. }
  289. }
  290. return result
  291. }
  292. if let obj = try? JSONSerialization.jsonObject(with: data, options: []) {
  293. if let dict = obj as? [String: Any] {
  294. if let arr = dict["data"] as? [Any] {
  295. return normalizeArray(arr)
  296. }
  297. if let arr = dict["list"] as? [Any] {
  298. return normalizeArray(arr)
  299. }
  300. if let arr = dict["channels"] as? [Any] {
  301. return normalizeArray(arr)
  302. }
  303. } else if let arr = obj as? [Any] {
  304. return normalizeArray(arr)
  305. }
  306. }
  307. return []
  308. }
  309. private func presentRoutePicker(channels: [Channel]) {
  310. routePopup?.removeFromSuperview()
  311. let popup = RoutePickerView(channels: channels)
  312. popup.delegate = self
  313. popup.translatesAutoresizingMaskIntoConstraints = false
  314. view.addSubview(popup)
  315. NSLayoutConstraint.activate([
  316. popup.topAnchor.constraint(equalTo: view.topAnchor),
  317. popup.bottomAnchor.constraint(equalTo: view.bottomAnchor),
  318. popup.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  319. popup.trailingAnchor.constraint(equalTo: view.trailingAnchor)
  320. ])
  321. self.routePopup = popup
  322. }
  323. private func submitRoute(channel: Channel) {
  324. guard let url = URL(string: apiBaseURL + pathSetRoute) else {
  325. print("[Channel] Invalid setQudao URL")
  326. return
  327. }
  328. var request = URLRequest(url: url)
  329. request.httpMethod = "POST"
  330. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  331. // let userId = String(UserDefaults.standard.object(forKey: "userId") as? Int ?? 0)
  332. let memberPhone = UserDefaults.standard.string(forKey: "memberPhone") ?? ""
  333. let memberIcon = UserDefaults.standard.string(forKey: "memberIconURL") ?? ""
  334. let memberName = UserDefaults.standard.string(forKey: "memberName") ?? memberPhone
  335. let phoneInfo: [String: Any] = [
  336. "systemName": UIDevice.current.systemName,
  337. "systemVersion": UIDevice.current.systemVersion,
  338. "model": deviceModel(),
  339. "localizedModel": UIDevice.current.localizedModel
  340. ]
  341. let phoneJsonString: String
  342. if let jsonData = try? JSONSerialization.data(withJSONObject: phoneInfo, options: []),
  343. let jsonString = String(data: jsonData, encoding: .utf8) {
  344. phoneJsonString = jsonString
  345. } else {
  346. phoneJsonString = "{}"
  347. }
  348. let body: [String: Any] = [
  349. "iosId": UIDevice.current.identifierForVendor?.uuidString ?? "",
  350. "alias": memberName,
  351. "phone": memberPhone,
  352. "brand": UIDevice.current.systemName,
  353. "model": deviceModel(),
  354. "appId": kTakuAppID,
  355. "deviceId": UIDevice.current.identifierForVendor?.uuidString ?? "",
  356. "iconUrl": memberIcon,
  357. "ditchId": Int64(channel.id) ?? 0,
  358. "phoneJson": phoneJsonString
  359. ]
  360. request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
  361. if let body = request.httpBody,
  362. let bodyString = String(data: body, encoding: .utf8) {
  363. print("[Channel] setQudao Request URL: \(url)")
  364. print("[Channel] setQudao Request Headers: \(request.allHTTPHeaderFields ?? [:])")
  365. print("[Channel] setQudao Request Body: \(bodyString)")
  366. }
  367. showSystemOverlay()
  368. let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
  369. if let httpResponse = response as? HTTPURLResponse {
  370. print("[Channel] setQudao Response Code: \(httpResponse.statusCode)")
  371. print("[Channel] setQudao Response Headers: \(httpResponse.allHeaderFields)")
  372. }
  373. if let data = data, let responseString = String(data: data, encoding: .utf8) {
  374. print("[Channel] setQudao Response Body: \(responseString)")
  375. }
  376. if let data = data {
  377. do {
  378. if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
  379. if let code = json["code"] as? Int, code != 200 {
  380. let message = (json["message"] as? String) ?? (json["msg"] as? String) ?? "未知错误"
  381. DispatchQueue.main.async { [weak self] in
  382. self?.hideSystemOverlay()
  383. self?.flashToast(message: message)
  384. }
  385. return
  386. }
  387. }
  388. } catch {
  389. // Ignore JSON parse error here
  390. }
  391. }
  392. if let data = data,
  393. let obj = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
  394. let code = obj["code"] as? Int, code == 200,
  395. let dataDict = obj["data"] as? [String: Any] {
  396. let nick = (dataDict["nickName"] as? String) ?? ""
  397. let roleId = (dataDict["userId"] as? String) ?? ""
  398. let todayCount: Int = {
  399. if let v = dataDict["todayAnswerCount"] as? Int { return v }
  400. if let s = dataDict["todayAnswerCount"] as? String, let i = Int(s) { return i }
  401. return 0
  402. }()
  403. let historyCount: Int = {
  404. if let v = dataDict["historyAnswerCount"] as? Int { return v }
  405. if let s = dataDict["historyAnswerCount"] as? String, let i = Int(s) { return i }
  406. return 0
  407. }()
  408. let registryTimeStr = (dataDict["registryTimeStr"] as? String) ?? ""
  409. let headImgURL = dataDict["headImg"] as? String
  410. let lastLoginTimeStr = (dataDict["lastLoginTimeStr"] as? String) ?? ""
  411. let powerValue: Int = {
  412. if let v = dataDict["power"] as? Int { return v }
  413. if let s = dataDict["power"] as? String, let i = Int(s) { return i }
  414. return 0
  415. }()
  416. let lastQuestionId: String? = {
  417. if let s = dataDict["lastQuestionId"] as? String, !s.isEmpty { return s }
  418. if let n = dataDict["lastQuestionId"] as? NSNumber { return n.stringValue }
  419. return nil
  420. }()
  421. let answerLogsFromLogin: [String] = {
  422. if let arr = dataDict["answerRecordTimeList"] as? [String] { return arr }
  423. if let anyArr = dataDict["answerRecordTimeList"] as? [Any] { return anyArr.compactMap { String(describing: $0) } }
  424. return []
  425. }()
  426. DispatchQueue.main.async { [weak self] in
  427. guard let self = self else { return }
  428. self.hideSystemOverlay()
  429. self.loginUserInfo = LoginUserInfo(
  430. nickName: nick,
  431. userId: roleId,
  432. registryTimeStr: registryTimeStr,
  433. todayAnswerCount: todayCount,
  434. historyAnswerCount: historyCount,
  435. headImgURL: headImgURL,
  436. lastLoginTimeStr: lastLoginTimeStr,
  437. answerLogs: answerLogsFromLogin
  438. )
  439. // Save to UserDefaults for backup
  440. UserDefaults.standard.set(nick, forKey: "nickname")
  441. UserDefaults.standard.set(roleId, forKey: "roleID")
  442. UserDefaults.standard.set(registryTimeStr, forKey: "registryTimeStr")
  443. UserDefaults.standard.set(todayCount, forKey: "todayAnswerCount")
  444. UserDefaults.standard.set(historyCount, forKey: "historyAnswerCount")
  445. UserDefaults.standard.set(headImgURL, forKey: "headImgURL")
  446. UserDefaults.standard.set(lastLoginTimeStr, forKey: "lastLoginTimeStr")
  447. UserDefaults.standard.set(powerValue, forKey: "power")
  448. UserDefaults.standard.set(answerLogsFromLogin, forKey: "answerLogs")
  449. if let lq = lastQuestionId { UserDefaults.standard.set(lq, forKey: "lastQuestionId") }
  450. UserDefaults.standard.set(channel.name, forKey: "selectedChannelName")
  451. UserDefaults.standard.synchronize()
  452. DispatchQueue.main.async { [weak self] in
  453. self?.flashToast(message: "登录成功")
  454. }
  455. // Navigate to Quiz
  456. self.goToQuiz()
  457. }
  458. }
  459. if let error = error {
  460. print("[Channel] set error: \(error)")
  461. DispatchQueue.main.async { [weak self] in
  462. self?.hideSystemOverlay()
  463. self?.flashToast(message: "网络错误,请重试")
  464. }
  465. return
  466. }
  467. DispatchQueue.main.async {
  468. self?.hideSystemOverlay()
  469. self?.routePopup?.removeFromSuperview()
  470. self?.routePopup = nil
  471. print("[Channel] setQudao success for: \(channel.name) (id=\(channel.id))")
  472. }
  473. }
  474. task.resume()
  475. }
  476. private func goToQuiz() {
  477. let questionVC = QuizStageController()
  478. // 传递登录用户信息
  479. if let userInfo = loginUserInfo {
  480. questionVC.setLoginUserInfo(userInfo)
  481. }
  482. // 传递选择的渠道信息
  483. if let channel = selectedChannel {
  484. questionVC.setSelectedChannel(channel)
  485. }
  486. let navController = UINavigationController(rootViewController: questionVC)
  487. if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
  488. if let window = windowScene.windows.first {
  489. // 将 questionVC 作为 rootViewController
  490. window.rootViewController = navController
  491. window.makeKeyAndVisible()
  492. }
  493. }
  494. // Get current window and transition
  495. // guard let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else {
  496. // return
  497. // }
  498. //
  499. // window.rootViewController = questionVC
  500. //
  501. // UIView.transition(with: window,
  502. // duration: 0.5,
  503. // options: .transitionCrossDissolve,
  504. // animations: nil,
  505. // completion: nil)
  506. }
  507. private func refreshChannelTitle() {
  508. if let channel = selectedChannel {
  509. routeBtn.setTitle("\(channel.name) ▼", for: .normal)
  510. } else {
  511. routeBtn.setTitle("渠道 ▼", for: .normal)
  512. }
  513. }
  514. // MARK: - RoutePickerDelegate
  515. func routePicker(_ panel: RoutePickerView, didPick channel: Channel) {
  516. selectedChannel = channel
  517. refreshChannelTitle()
  518. panel.removeFromSuperview()
  519. routePopup = nil
  520. print("[Channel] Selected channel: \(channel.name) (id=\(channel.id))")
  521. }
  522. // MARK: - System Loading Helpers
  523. private func showSystemOverlay() {
  524. guard loadingOverlay == nil else { return }
  525. let overlay = UIView()
  526. overlay.translatesAutoresizingMaskIntoConstraints = false
  527. overlay.backgroundColor = UIColor.black.withAlphaComponent(0.35)
  528. overlay.isUserInteractionEnabled = true
  529. let spinner = UIActivityIndicatorView(style: .large)
  530. spinner.translatesAutoresizingMaskIntoConstraints = false
  531. spinner.startAnimating()
  532. spinner.hidesWhenStopped = true
  533. overlay.addSubview(spinner)
  534. view.addSubview(overlay)
  535. NSLayoutConstraint.activate([
  536. overlay.topAnchor.constraint(equalTo: view.topAnchor),
  537. overlay.bottomAnchor.constraint(equalTo: view.bottomAnchor),
  538. overlay.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  539. overlay.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  540. spinner.centerXAnchor.constraint(equalTo: overlay.centerXAnchor),
  541. spinner.centerYAnchor.constraint(equalTo: overlay.centerYAnchor)
  542. ])
  543. loadingOverlay = overlay
  544. loadingSpinner = spinner
  545. }
  546. private func hideSystemOverlay() {
  547. loadingSpinner?.stopAnimating()
  548. loadingOverlay?.removeFromSuperview()
  549. loadingSpinner = nil
  550. loadingOverlay = nil
  551. }
  552. // MARK: - Toast Helper
  553. private func flashToast(message: String) {
  554. let tag = 9527
  555. if let existing = view.viewWithTag(tag) {
  556. existing.removeFromSuperview()
  557. }
  558. let toastLabel = UILabel()
  559. toastLabel.text = message
  560. toastLabel.font = UIFont.systemFont(ofSize: 15, weight: .medium)
  561. toastLabel.textColor = .white
  562. toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.8)
  563. toastLabel.textAlignment = .center
  564. toastLabel.alpha = 0.0
  565. toastLabel.layer.cornerRadius = 16
  566. toastLabel.clipsToBounds = true
  567. toastLabel.numberOfLines = 0
  568. toastLabel.tag = tag
  569. toastLabel.translatesAutoresizingMaskIntoConstraints = false
  570. view.addSubview(toastLabel)
  571. let horizontalPadding: CGFloat = 24
  572. let verticalPadding: CGFloat = 12
  573. let maxWidth = view.frame.width - 40
  574. let size = toastLabel.sizeThatFits(CGSize(width: maxWidth - horizontalPadding * 2, height: CGFloat.greatestFiniteMagnitude))
  575. let width = min(size.width + horizontalPadding * 2, maxWidth)
  576. let height = size.height + verticalPadding * 2
  577. NSLayoutConstraint.activate([
  578. toastLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  579. toastLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
  580. toastLabel.widthAnchor.constraint(equalToConstant: width),
  581. toastLabel.heightAnchor.constraint(equalToConstant: height)
  582. ])
  583. UIView.animate(withDuration: 0.25, animations: {
  584. toastLabel.alpha = 1.0
  585. }) { _ in
  586. DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
  587. UIView.animate(withDuration: 0.25, animations: {
  588. toastLabel.alpha = 0.0
  589. }) { _ in
  590. toastLabel.removeFromSuperview()
  591. }
  592. }
  593. }
  594. }
  595. }