DailSyncViewController.swift 16.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
//
//  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 {
//
//}