// // DailSyncViewController.swift // Twear // // Created by yangbin on 2021/12/21. // import UIKit import Kingfisher import Alamofire import MBProgressHUD import SnapKit class DailSyncViewController: UIViewController, XMLParserDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout! @IBOutlet weak var collectionViewBottom: NSLayoutConstraint! var styleArray: [String] = ["最新", "数据", "简约", "卡通", "色彩", "商务"] @IBOutlet weak var locLabel1: UILabel! @IBOutlet weak var locLabel2: UILabel! @IBOutlet weak var locLabel3: UILabel! @IBOutlet weak var locLabel4: UILabel! @IBOutlet weak var locLabel5: UILabel! @IBOutlet weak var locLabel6: UILabel! @IBOutlet weak var titleView: UIView! var dialNum: Int = 9 var dialWidth: Int = 240 var dialHeight: Int = 280 var identifierDic: [String: String] = [:] // var isSyncing: Bool = false // var tempIndex: Int = -1 // var syncIndex = UserInfo.dailIndex // var isSynced: Bool = UserInfo.isDailSync var user = UserInfo var dialIndexPath = IndexPath(row: -1, section: -1) let platform = CurDevice.platform override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let navController = navigationController as? ZCNavigationController navController?.enableScreenEdgePanGestureRecognizer(true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if user.isDailSync { // if user.dailIndex >= 0 && user.dailIndex <= dialNum-1 { // collectionView.scrollToItem(at: IndexPath(row: user.dailIndex, section: 0), at: .bottom, animated: false) // collectionView.scrollToItem(at: IndexPath(row: user.dailIndex, section: 0), at: .top, animated: false) // let cell = collectionView.cellForItem(at: IndexPath(row: user.dailIndex, section: 0)) as! DailCell // cell.syncComplete() // } } } override func viewDidLoad() { super.viewDidLoad() title = LocString("表盘推送") // clearCache() // getCacheSize() collectionViewFlowLayout.minimumLineSpacing = 10 collectionViewFlowLayout.minimumInteritemSpacing = 20 collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 5, left: 10, bottom: 0, right: 10)//10+NAVBAR_HEIGHT+10 collectionViewFlowLayout.itemSize = CGSize(width: (SCREEN_WIDTH-60)/3.0, height: 130) collectionViewFlowLayout.headerReferenceSize = CGSize(width: SCREEN_WIDTH, height: 50) collectionView.register(UINib(nibName: "DailHeaderView", bundle: .main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "DailHeaderView") // collectionView.register(UINib(nibName: "DailCell", bundle: .main), forCellWithReuseIdentifier: "DailCell") collectionViewBottom.constant = 10 + NAVBAR_HEIGHT + 10 locLabel1.text = LocString("最新") locLabel2.text = LocString("数据") locLabel3.text = LocString("简约") locLabel4.text = LocString("卡通") locLabel5.text = LocString("色彩") locLabel6.text = LocString("商务") if user.dialIndexPath != "" { let indexPathArray = user.dialIndexPath.split(separator: "-") if indexPathArray.count == 2 { dialIndexPath = IndexPath(row: Int(indexPathArray[1])!, section: Int(indexPathArray[0])!) } } if platform == ._828 { queryDialInfo() } // URLCache.shared.removeAllCachedResponses() } func queryDialInfo() { Alamofire.SessionManager.default.session.configuration.requestCachePolicy = .reloadIgnoringLocalCacheData Alamofire.SessionManager.default.session.configuration.urlCache = nil URLCache.shared.removeAllCachedResponses() Alamofire.SessionManager.default.request("http://www.hodafone.com.cn/hodafone/dial/rtl/\(dialWidth)x\(dialHeight)/version.xml").responseData { responseData in // if responseData.response?.statusCode == 400 { if let data = responseData.data { URLCache.shared.removeAllCachedResponses() let parser = XMLParser(data: data) parser.delegate = self parser.parse() } // } else { // // } } } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { if elementName == "dial" { if let latestVersion = attributeDict["least"] { print(latestVersion) // if user.dailVersion.checkVersion(latestVersion) { if user.dailVersion != latestVersion { var dic: [String: Int] = [:] for i in 0..<6 { if let num = attributeDict["item\(i)"] { dic["\(i)"] = Int(num) ?? 0 } } print(dic) clearCache() user.dialNumDic = dic user.dailVersion = latestVersion AdminHelper.shared.updateUser(user) collectionView.reloadData() } } } } @IBAction func chooseStyle(_ sender: UIButton) { gotoSubVC(index: sender.tag) } func gotoSubVC(index: Int) { if platform != ._828 { return } if IsDailSyncing { MBProgressHUD.showh(LocString("正在推送表盘中,请稍后...")) return } let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "DailSyncSubVC") as! DailSyncSubVC vc.dialWidth = dialWidth vc.dialHeight = dialHeight vc.dialNum = user.dialNumDic["\(index)"] ?? 0 if index == dialIndexPath.section { vc.dialIndex = dialIndexPath.row } vc.styleIndex = index vc.title = LocString(styleArray[index]) vc.syncDialClosure = {[weak self] indexPath in self?.syncCompleteOnline(indexPath: indexPath) } navigationController?.pushViewController(vc, animated: true) } func showAlert() -> Bool { if !DeviceIsConnected { IsDailSyncing = false self.showAlert(title: LocString("设备已断开"), message: "", cancelText: nil) {[weak self] action in self?.navigationController?.popToRootViewController(animated: true) } cancel: { _ in } return true } else { return false } } func downloadDailFile(_ indexPath: IndexPath) { if showAlert() { return } if IsDailSyncing { return } let cell = self.collectionView.cellForItem(at: indexPath) as! DailCell if cell.progressView.label.text == LocString("已安装") { return } updateUserInteraction(true) cell.updateProgressView(0, isDownload: true) let dest: DownloadRequest.DownloadFileDestination = { _, _ in let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendingPathComponent("dial.bin") return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) } Alamofire.download("http://www.hodafone.com.cn/hodafone/dial/rtl/\(dialWidth)x\(dialHeight)/\(indexPath.section)/\(indexPath.row)/dial.bin", to: dest).downloadProgress { progress in cell.updateProgressView(Int(progress.fractionCompleted*5), isDownload: true) }.responseData {[weak self] response in if let _ = response.value { // self?.syncDail(indexPath, cell: cell, path: response.destinationURL!.path) } else { cell.initProgressView() self?.updateUserInteraction(false) self?.showAlert(title: LocString("提示"), message: LocString("安装失败,请重试"), cancelText: nil) } } } // private func syncDail(_ indexPath: IndexPath, cell: DailCell, path: String = "") { // if showAlert() { return } // if platform == ._828 { // if !FileManager.default.fileExists(atPath: path) { // updateUserInteraction(false) // showAlert(title: LocString("提示"), message: LocString("安装失败,请重试"), cancelText: nil) // return // } //// let cell = self.collectionView.cellForItem(at: indexPath) as! DailCell // BluetoothManager.shared.syncFileWith(path: path) { progress in // cell.updateProgressView(Int(Double(progress)*0.95)+5) // } completion: {[weak self] error in // self?.updateUserInteraction(false) // if error == nil { // self?.syncCompleteOnline(indexPath: indexPath) // cell.syncComplete() // } else { // cell.initProgressView() // self?.showAlert(title: LocString("提示"), message: LocString("安装失败,请重试"), cancelText: nil) // } // } // } else { // if IsDailSyncing { return } // let cell = self.collectionView.cellForItem(at: indexPath) as! DailCell // if cell.progressView.label.text == LocString("已安装") { return } // updateUserInteraction(true) // cell.updateProgressView(0) //// switch platform { //// case ._816: //// BluetoothManager.shared.syncDialWith(path: "\(Bundle.main.resourcePath!)/dial/Dialdata280/\(indexPath.row)") { progress in //// cell.updateProgressView(progress) //// } completion: {[weak self] error in //// self?.updateUserInteraction(false) //// if error == nil { //// cell.syncComplete() //// } else { //// cell.initProgressView() //// self?.showAlert(title: LocString("提示"), message: LocString("安装失败,请重试"), cancelText: nil) //// } //// } //// //// case ._818: //// BluetoothManager.shared.syncFileWith(path: "\(Bundle.main.resourcePath!)/dial/DialDataRtk/\(indexPath.row)/dial.bin") { progress in //// cell.updateProgressView(progress) //// } completion: {[weak self] error in //// self?.updateUserInteraction(false) //// if error == nil { //// self?.syncComplete(index: indexPath.row) //// cell.syncComplete() //// } else { //// cell.initProgressView() //// self?.showAlert(title: LocString("提示"), message: LocString("安装失败,请重试"), cancelText: nil) //// } //// } //// //// default: //// break //// } // } // } func syncComplete(index: Int) { user.dailIndex = index collectionView.reloadData() user.isDailSync = true AdminHelper.shared.updateUser(user) } func syncCompleteOnline(indexPath: IndexPath) { dialIndexPath = indexPath collectionView.reloadData() user.isDailSync = true user.dialIndexPath = "\(indexPath.section)-\(indexPath.row)" AdminHelper.shared.updateUser(user) } func updateUserInteraction(_ isSyncing: Bool) { UIApplication.shared.isIdleTimerDisabled = isSyncing IsDailSyncing = isSyncing let navController = navigationController as? ZCNavigationController navController?.enableScreenEdgePanGestureRecognizer(!isSyncing) } func clearCache() { let cache = ImageCache.default cache.clearMemoryCache() cache.clearDiskCache { DispatchQueue.main.async { print("s.清除缓存成功") } } } func getCacheSize() { ImageCache.default.calculateDiskCacheSize { (size) in let sizeStr = ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .binary) print(sizeStr) } } deinit { print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!") } } extension DailSyncViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if platform == ._828 { return min(user.dialNumDic["\(section)"] ?? 0, 6) } else { return dialNum } } func numberOfSections(in collectionView: UICollectionView) -> Int { if platform == ._828 { return 6 } else { return 1 } } // collectionViewFlowLayout.headerReferenceSize = CGSize(width: SCREEN_WIDTH, height: 30) func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { var reusableView: UICollectionReusableView? if kind == UICollectionView.elementKindSectionHeader { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "DailHeaderView", for: indexPath) as! DailHeaderView headerView.moreBtnBlock = {[weak self] in self?.gotoSubVC(index: indexPath.section) } headerView.titleLabel.text = LocString(styleArray[indexPath.section]) // let label = UILabel() // label.font = BoldFont(16) // headerView.addSubview(label) // label.snp.makeConstraints { make in // make.left.equalToSuperview().offset(7) // make.centerY.equalToSuperview() // } // label.text = LocString(styleArray[indexPath.section]) reusableView = headerView } return reusableView! } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let identifier: String = "DailCell\(indexPath.row)\(indexPath.section)" if identifierDic[identifier] == nil { collectionView.register(UINib(nibName: "DailCell", bundle: .main), forCellWithReuseIdentifier: identifier) identifierDic[identifier] = identifier } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! DailCell switch platform { case ._828: cell.dailImageView.kf.setImage(with: URL(string: "http://www.hodafone.com.cn/hodafone/dial/rtl/\(dialWidth)x\(dialHeight)/\(indexPath.section)/\(indexPath.row)/preview.png"), placeholder: UIImage(named: "dail_default_3"), options: [.transition(.fade(0.3))]) // cell.dailImageView.image = UIImage(contentsOfFile: "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/\(indexPath.row)/preview") default: break } cell.cellClickClosure = {[weak self] in if self?.platform == ._828 { self?.downloadDailFile(indexPath) } else { // self?.syncDail(indexPath, cell: cell) } } if platform == ._828 { cell.cellClickClosure = {[weak self] in self?.downloadDailFile(indexPath) } if indexPath == dialIndexPath { cell.syncComplete() } else { cell.initProgressView() } } else { if indexPath.row == user.dailIndex { cell.syncComplete() } else { cell.initProgressView() } } return cell } } //class DailHeaderView: UICollectionReusableView { // //}