SettingViewController.swift 31.2 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 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
//
//  SettingViewController.swift
//  Twear
//
//  Created by yangbin on 2021/11/16.
//

import UIKit
import MBProgressHUD
import swiftScan
import Charts
import Kingfisher

class SettingViewController: UIViewController, LBXScanViewControllerDelegate {

    

    @IBOutlet weak var connectView: UIView!
    @IBOutlet weak var addDeviceView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout!
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var collectionView1: UICollectionView!
    @IBOutlet weak var collectionViewFlowLayout1: UICollectionViewFlowLayout!
    @IBOutlet weak var collectionViewHeight1: NSLayoutConstraint!
    @IBOutlet weak var collectionView1Width: NSLayoutConstraint!
    
    @IBOutlet weak var deviceNameLabel: UILabel!
    @IBOutlet weak var batteryBtn: UIButton!
    @IBOutlet weak var connectLabel: UILabel!
    @IBOutlet weak var connectImageView: UIImageView!
    @IBOutlet weak var deleteBtn: UIButton!
    @IBOutlet weak var idLabel: UILabel!
    
    @IBOutlet weak var watchImageView: UIImageView!
//    @IBOutlet weak var dailImageView2: UIImageView!
//    @IBOutlet weak var dailImageView1: UIImageView!
//    @IBOutlet weak var dailImageView3: UIImageView!
    
    
//    @IBOutlet weak var totalDistanceLabel: UILabel!
//    @IBOutlet weak var totalCalorieLabel: UILabel!
    
    var scanView: ScanView? = nil
    var scanDeviceMac: String? = nil
    var dialNum: Int = 9
    
    private let settingDic: [String: String] = ["遥控拍照": "remote_camera", "查找手环": "set_find", "提醒功能": "set_reminder", "语言设置": "set_language", "其他设置": "set_other", "抬腕亮屏": "lift_wrist", "勿扰模式": "no_disturb", "目标设置": "set_goals", "微信运动": "wechat_sport", "手环说明": "device_desc", "固件升级": "firmware_update", "联系人": "set_contacts", "名片": "set_card", "NFC": "set_nfc", "钱包": "set_wallet", "删除设备": "set_delete", "出厂设置": "set_restore", "后台保护": "set_background"]
    
    // 未连接手表时
    private let setting_all: [[String]] = [["遥控拍照", "查找手环", "提醒功能", "语言设置", "其他设置", "抬腕亮屏", "目标设置"], ["固件升级", "删除设备"]]
    
    // 连接手表时
    private let setting_828: [[String]] = [["遥控拍照", "查找手环", "提醒功能", "语言设置", "其他设置", "抬腕亮屏", "目标设置"], ["固件升级", "删除设备"]]

    var dialWidth: Int = 240
    var dialHeight: Int = 280

    private var settingArray: [[String]] = [] {
        didSet {
            collectionViewHeight.constant = CGFloat(77*(settingArray[0].count/4 + (settingArray[0].count%4 == 0 ? 0 : 1)) + 60)
            collectionViewHeight1.constant = CGFloat(77*(settingArray[1].count/4 + (settingArray[1].count%4 == 0 ? 0 : 1)) + 60)
            let spaceWidth = 5.0 * Double(settingArray[1].count - 1)
            let itemWidth = ((SCREEN_WIDTH-50)/4.0) * Double(settingArray[1].count)
            collectionView1Width.constant = CGFloat(itemWidth + spaceWidth + 10)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        let admin = AdminHelper.shared.loadLocalAdminData()
        if DeviceIsConnected {
            updateBattery(Battery)
        }
//        updateTotalDataView(DistanceUnit(rawValue: UInt8(admin.userInfo.distanceUnit))!)
        let navController = navigationController as? ZCNavigationController
        navController?.enableScreenEdgePanGestureRecognizer(true)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        settingArray = setting_828
        setupUI()
        
        BluetoothManager.shared.registerDelegate(self)
        BluetoothManager.shared.registerSyncDelegate(self)
        // Do any additional setup after loading the view.
    }
    
    
    func setupUI() {
        let bindButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 28))
        bindButton.setImage(UIImage(named: "device_add"), for: .normal)
        bindButton.addTarget(self, action: #selector(didClickRightBar), for: .touchUpInside)
//        navigationItem.rightBarButtonItem =  UIBarButtonItem(customView: bindButton)
        let scanButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 28))
        scanButton.setImage(UIImage(named: "scan_button"), for: .normal)
        scanButton.addTarget(self, action: #selector(didClickScanButton), for: .touchUpInside)
        navigationItem.rightBarButtonItems =  [UIBarButtonItem(customView: bindButton), UIBarButtonItem(customView: scanButton)]
        
        let setButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 28))
        setButton.setTitle(LocString("设备"), for: .normal)
        setButton.titleLabel?.font = BoldFont(18)
        setButton.setTitleColor(.black, for: .normal)
        setButton.addTarget(self, action: #selector(clickSetButton), for: .touchUpInside)
        navigationItem.leftBarButtonItem =  UIBarButtonItem(customView: setButton)
        
        
        let addTap = UITapGestureRecognizer(target: self, action:#selector(bindDevice))
        addDeviceView.addGestureRecognizer(addTap)
        

        collectionViewFlowLayout.minimumLineSpacing = 20
        collectionViewFlowLayout.minimumInteritemSpacing = 5
        collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 60, left: 5, bottom: 7, right: 5)
        collectionViewFlowLayout.itemSize = CGSize(width: (SCREEN_WIDTH-50)/4.0, height: 58)
        collectionView.bounces = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(UINib.init(nibName: "SettingCell", bundle: .main), forCellWithReuseIdentifier: "SettingCell")
        
        collectionViewFlowLayout1.minimumLineSpacing = 5
        collectionViewFlowLayout1.minimumInteritemSpacing = 5
        collectionViewFlowLayout1.sectionInset = UIEdgeInsets(top: 60, left: 5, bottom: 7, right: 5)
        collectionViewFlowLayout1.itemSize = CGSize(width: (SCREEN_WIDTH-50)/4.0, height: 58)
        collectionView1.bounces = false
        collectionView1.showsHorizontalScrollIndicator = false
        collectionView1.register(UINib.init(nibName: "SettingCell", bundle: .main), forCellWithReuseIdentifier: "SettingCell")
        
        
        idLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(reconnect)))
        updateConnectView(DeviceIsConnected)
//        updateTotalDataView(DistanceUnit(rawValue: UInt8(UserInfo.distanceUnit))!)
    }
    
    @objc func reconnect() {
        if idLabel.text == LocString("重新连接") {
//            BluetoothManager.shared.disconnect()
//            BluetoothManager.shared.reconnectPer()
            BluetoothManager.shared.reConnect()
        }
    }
    
//    func reconnectTimer() {
//        if GCDTimer.shared.isExistTimer(WithTimerName: "Reconnect") {
//            GCDTimer.shared.cancleTimer(WithTimerName: "Reconnect")
//        }
//        GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "Reconnect", timeInterval: 10, queue: .main, repeats: false) {[weak self] in
//            self?.reconnect()
//        }
//    }
//    
    
    private func updateConnectView(_ isConnected: Bool) {
        let curDevice = CurDevice
        if curDevice.uuid.count == 0 {
            addDeviceView.isHidden = false
            connectView.isHidden = true
//            dailImageView1.image = UIImage(named: "dail_default_1")
//            dailImageView2.image = UIImage(named: "dail_default_2")
//            dailImageView3.image = UIImage(named: "dail_default_3")
//            dailImageView3.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/test2.bmp")
            settingArray = setting_all
            if AppSettings.shared.language != .Chinese {
                if let i = settingArray[0].firstIndex(of: "微信运动") {
                    settingArray[0].remove(at: i)
                }
            }
            return
        }
        
        if curDevice.platform == ._828 {
            settingArray = setting_828
            dialWidth = 240
            dialHeight = 280
            if curDevice.name.contains("P8GT") {
                settingArray = setting_all
                watchImageView.image = UIImage(named: "P8GT_icon")
            } else if curDevice.name.contains("Watch 8") {
                watchImageView.image = UIImage(named: "Watch7_icon")
                dialWidth = 240
                dialHeight = 286
            } else if curDevice.name.contains("S7 NO.1") {
                watchImageView.image = UIImage(named: "S7_NO.1_icon")
                dialWidth = 240
                dialHeight = 286
            } else if curDevice.name.contains("G7 Pro Max Gameboy") {
//                watchImageView.image = UIImage(named: "S7_NO.1_icon")
                dialWidth = 240
                dialHeight = 286
            } else if curDevice.name.contains("hq7") {
                watchImageView.image = UIImage(named: "hq7_icon")
            } else {
                watchImageView.image = UIImage(named: "bracelet_icon")
            }
//            if curDevice.name.contains("Watch 8") {
//                
//            }
            
//            dailImageView1.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/0/preview")
//            dailImageView1.kf.setImage(with: URL(string: "http://www.hodafone.com.cn/hodafone/dial/rtl/\(dialWidth)x\(dialHeight)/0/0/preview.png"), placeholder: UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/0/preview"), options: [.transition(.fade(0.3))])
//            dailImageView2.kf.setImage(with: URL(string: "http://www.hodafone.com.cn/hodafone/dial/rtl/\(dialWidth)x\(dialHeight)/0/1/preview.png"), placeholder: UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/1/preview"), options: [.transition(.fade(0.3))])
//            dailImageView3.kf.setImage(with: URL(string: "http://www.hodafone.com.cn/hodafone/dial/rtl/\(dialWidth)x\(dialHeight)/0/2/preview.png"), placeholder: UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/2/preview"), options: [.transition(.fade(0.3))])
//            dailImageView2.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/1/preview")
//            dailImageView3.image = UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreviewHQ7/2/preview")
        
        }
        
        if AppSettings.shared.language != .Chinese {
            if let i = settingArray[0].firstIndex(of: "微信运动") {
                settingArray[0].remove(at: i)
            }
        }
        
        if #available(iOS 13.0, *) {
          
        } else {
            if let i = settingArray[0].firstIndex(of: "NFC") {
                settingArray[0].remove(at: i)
            }
        }
        

       
//        if curDevice.platform == .other {
//            dailImageView1.image = UIImage(named: "dail_default_1")
//            dailImageView2.image = UIImage(named: "dail_default_2")
//            dailImageView3.image = UIImage(named: "dail_default_3")
//
//        } else
//        UIImage(contentsOfFile:  "\(Bundle.main.resourcePath!)/dial/dialrtkpreview/\(indexPath.row)/preview@2x")
        
 
        addDeviceView.isHidden = true
        connectView.isHidden = false
        deviceNameLabel.text = CurDevice.name
        deleteBtn.isHidden = isConnected
        batteryBtn.isHidden = !isConnected
        connectLabel.text = isConnected ? LocString("已连接") : LocString("正在连接...")
        connectImageView.image = UIImage(named: isConnected ? "bluetooth_connected" : "bluetooth_disconnected")
        idLabel.textColor = isConnected ? .black : UIColor.rgbColorFromHex(0xFF0000)
        idLabel.text = isConnected ? CurDevice.mac : LocString("重新连接")
    }
    
//    private func updateTotalDataView(_ unit: DistanceUnit) {
//        let step = StepModel.getRecentSteps()
//        totalCalorieLabel.text = "\(String(format:"%02d",Int(step.calorie)))\(LocString("千卡"))"
//        if unit == .foot {
//            totalDistanceLabel.text = "\(step.distance.mileString())\(LocString("英里"))"
//        } else {
//            totalDistanceLabel.text = "\(String(format:"%.2f", step.distance))\(LocString("公里"))"
//        }
//
//    }

    private func removeAlpha(image: UIImage) -> UIImage? {
        guard let imageRef = image.cgImage else { return nil }
        if imageRef.alphaInfo == CGImageAlphaInfo.none {
            return image
        }
        let width = imageRef.width
        let height = imageRef.height
        let colorSpace = imageRef.colorSpace
//        CGColorSpaceCreateDeviceRGB
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo().rawValue | CGImageAlphaInfo.noneSkipLast.rawValue)
        let offscreenContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace!, bitmapInfo: bitmapInfo.rawValue)
        offscreenContext?.draw(imageRef, in: rect)
        let imageNoAlpha = UIImage(cgImage: (offscreenContext?.makeImage()!)!)
        return imageNoAlpha
    }
    


 

    @IBAction func deleteDevice(_ sender: Any) {
        unbindDevice()
    }
    
    @objc func didClickScanButton() {
        
        if CurDevice.uuid.count > 0 {
            unbindDevice()
            return
        } else {
            let vc = ScanViewController()
            var style = LBXScanViewStyle()
            style.animationImage = UIImage(named: "scan_line")
            style.colorRetangleLine = UIColor.rgbColorFromHex(0x1DB5D7)
            style.centerUpOffset = NAVBAR_HEIGHT
            vc.scanStyle = style
            vc.scanResultDelegate = self
            navigationController?.pushViewController(vc, animated: true)
            scanDeviceMac = nil
        }
    }
    
    func scanFinished(scanResult: LBXScanResult, error: String?) {
        if CurDevice.uuid.count > 0 {
            unbindDevice()
        } else {
//            print(scanResult.strScanned)
//            let strValue = "mac=abc12324,name=231"

            guard let result = scanResult.strScanned else { return }
            var str = result.replacingOccurrences(of: "\"", with: "").uppercased()
            str = str.replacingOccurrences(of: "=", with: "")
            str = str.replacingOccurrences(of: " ", with: "")
            var qr = ""
            if str.range(of: "MAC:") != nil {
                guard let startIndex = str.range(of: "MAC:")?.upperBound else { return }
                let endIndex = str.index(startIndex, offsetBy: 17)
                qr = String(str[startIndex..<endIndex])
            } else if str.range(of: "MAC") != nil {
                guard let startIndex = str.range(of: "MAC")?.upperBound else { return }
                let endIndex = str.index(startIndex, offsetBy: 17)
                qr = String(str[startIndex..<endIndex])
            } else {
                return
            }
//            guard let startIndex = str.range(of: "MAC")?.upperBound else { return }
//            let endIndex = str.index(startIndex, offsetBy: 17)
//            let s = str[startIndex..<endIndex]
            scanDeviceMac = qr
//            print("\(scanDeviceMac)")
            
//            scanDeviceMac = "00:E0:12:34:57:55"

            scanView = ScanView()
            scanView?.show()
            startScan(true)
//            scanView?.updateUI(.Pairing)
            
            scanView?.clickClosure = {[weak self] index, device in
                if index == 2 {
                    self?.scanView = nil
                    BluetoothManager.shared.stopScanning()
                } else if index == 3 { //配对失败 重试
                    self?.startScan(true)
//                    scanView?.updateUI(.Pairing)
                } else if index == 4 { //重新搜索
                    self?.startScan()
                }
            }
        }
  
    }
    
    @objc func didClickRightBar() {
        if CurDevice.uuid.count > 0 {
            unbindDevice()
        } else {
            bindDevice()
        }
        
    }
    func unbindDevice() {
        let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "UnbindViewController") as! UnbindViewController
        vc.unbindClosure = {[weak self] in
            self?.updateConnectView(false)
        }
        navigationController?.pushViewController(vc, animated: true)
    }

    
    @objc func bindDevice() {
        scanDeviceMac = nil
        scanView = ScanView()
        scanView?.show()
        startScan()
        
        scanView?.clickClosure = {[weak self] index, device in
            if index == 2 {
                self?.scanView = nil
                BluetoothManager.shared.stopScanning()
            } else if index == 3 { //配对失败 重试
                self?.startScan()
            } else if index == 4 { //重新搜索
                self?.startScan()
            }
            
            if let per = device as? CBPeripheral {
                BluetoothManager.shared.stopScanning()
                BluetoothManager.shared.connect(peripheral: per)
                self?.scanView?.updateUI(.Pairing)
                if GCDTimer.shared.isExistTimer(WithTimerName: "StartScan") {
                    GCDTimer.shared.cancleTimer(WithTimerName: "StartScan")
                }
                if GCDTimer.shared.isExistTimer(WithTimerName: "DevicePairing") {
                    GCDTimer.shared.cancleTimer(WithTimerName: "DevicePairing")
                }
                GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "DevicePairing", timeInterval: 12, queue: .main, repeats: false) {
                    self?.pairingFail()
                }
            }
            
        }
    }
    
    private func pairingFail() {
        if !DeviceIsConnected {
            BluetoothManager.shared.forgetPeripheral()
            scanView?.updateUI(.PairFail)
        }
    }
    
    private func startScan(_ isQR: Bool = false) {
        BluetoothManager.shared.startScanning()
        var timeInterval: Double = 10
        if isQR {
            scanView?.updateUI(.Pairing)
            timeInterval = 18
        }
        GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "StartScan", timeInterval: timeInterval, queue: .main, repeats: false) {
            BluetoothManager.shared.stopScanning()
            if isQR {
                self.pairingFail()
            } else {
                self.scanView?.updateUI(.ScanComplete)
            }
        }
    }
    
    
    @objc func clickSetButton() {
        
        
    }
    
    private func showALert() -> Bool {
        if !IsBindDevice {
            MBProgressHUD.showh(LocString("请先绑定设备"))
            return true
        }
        if !DeviceIsConnected {
            MBProgressHUD.showh(LocString("设备未连接"))
            return true
        } else {
            if isFirstSync {
                MBProgressHUD.showh(LocString("正在同步中..."))
                return true
            }
        }
        return false
    }
    
    @IBAction func gotoDailVC(_ sender: Any) {
        if showALert() {
            return
        }
        MBProgressHUD.hide()
//        if CurDevice.name.contains("P8GT") {
//            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "DialLocalVC") as! DialLocalVC
//            vc.dialNum = 51
//            navigationController?.pushViewController(vc, animated: true)
//        } else {
       
        IsDailSyncing = false
        
        let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "DailViewController") as! DailViewController
        vc.dialWidth = dialWidth
        vc.dialHeight = dialHeight
        vc.dialNum = dialNum
        navigationController?.pushViewController(vc, animated: true)
//        }
    }

    func updateBattery(_ value: Int, isCharging: Bool = false) {
        var imageName = "battery_"
        if isCharging {
            imageName = "charging_"
        }
        switch value {
        case 98...100:
            imageName += "100"
        case 90...97:
            imageName += "90"
        case 80...89:
            imageName += "80"
        case 70...79:
            imageName += "70"
        case 60...69:
            imageName += "60"
        case 50...59:
            imageName += "50"
        case 40...49:
            imageName += "40"
        case 30...39:
            imageName += "30"
        case 20...29:
            imageName += "20"
        case 10...19:
            imageName += "10"
        case 0...9:
            imageName += "5"
        default:
            imageName += "5"
        }
        batteryBtn.setImage(UIImage(named: imageName), for: .normal)
        batteryBtn.setTitle(" \(value)%", for: .normal)
    }
    
    deinit {
        BluetoothManager.shared.unRegisterSyncDelegate(self)
        BluetoothManager.shared.unRegisterDelegate(self)
        print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!")
    }

}

extension SettingViewController: BluetoothSyncDelegate {
    func didReceiveBattery(value: Int) {
//        DeviceIsCharging = isCharging
        updateBattery(value, isCharging: false)
    }
    
    func didReceiveFindPhoneCommand(value: Int) {
        MBProgressHUD.show("did receive find phone command");
    }
}
extension SettingViewController: BluetoothManagerDelegate {
    func centralManagerDidUpdateState(_ state: Int) {
        switch state {
 
        case 4:
            print("poweredOff22")
            updateConnectView(false)
            connectLabel.text = LocString("已断开")
//            connectImageView.image = UIImage(named: "bluetooth_disconnected")
//            idLabel.text = "重新连接"
//            idLabel.textColor = UIColor.rgbColorFromHex(0xFF0000)
//            deleteBtn.isHidden = false
//            batteryBtn.isHidden = true
            
        case 5:
            connectLabel.text = LocString("正在连接...")
        default:
            print(" ")
        }
        
    }
    
    func didConnect(_ peripheral: CBPeripheral, _ mac: String) {
        print("已经连接")
        switch CurDevice.platform {
        default:
            settingArray = setting_all
        }
        if GCDTimer.shared.isExistTimer(WithTimerName: "StartScan") {
            GCDTimer.shared.cancleTimer(WithTimerName: "StartScan")
        }
        if GCDTimer.shared.isExistTimer(WithTimerName: "DevicePairing") {
            GCDTimer.shared.cancleTimer(WithTimerName: "DevicePairing")
        }
        
        if settingArray.count > 1 {
            collectionView.reloadData()
        }
        scanView?.updateUI(.PairSuccess)
//        addDeviceView.isHidden = true
//        connectView.isHidden = false
        
        updateConnectView(true)
 

    }
    
    func didDisconnected() {
        updateConnectView(false)
        DeviceIsConnected = false
        connectLabel.text = LocString("已断开")
    }
     
    
    func didDiscover(devices: [ScanDevice]) {
        if scanView != nil {
            if scanDeviceMac == nil {
                scanView?.deviceArray = devices
            } else {
                for device in devices {
                    print(device.mac)
                    if scanDeviceMac == device.mac {
//                        if let per = device.peripheral {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                            print("扫码连接")
                            if GCDTimer.shared.isExistTimer(WithTimerName: "StartScan") {
                                GCDTimer.shared.cancleTimer(WithTimerName: "StartScan")
                            }
                            if GCDTimer.shared.isExistTimer(WithTimerName: "DevicePairing") {
                                GCDTimer.shared.cancleTimer(WithTimerName: "DevicePairing")
                            }
                            BluetoothManager.shared.stopScanning()
                            BluetoothManager.shared.connect(peripheral: device.peripheral)
                  
                            GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "DevicePairing", timeInterval: 16, queue: .main, repeats: false) {
                                self.pairingFail()
                            }
                        }
                    }
                }
            }
        }
    }
    
    func didSetupServiceCharacteristics(_ peripheral: CBPeripheral) {
        
    }
}


extension SettingViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.collectionView {
            return settingArray[0].count
        } else {
            return settingArray[1].count
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SettingCell", for: indexPath) as! SettingCell
        let item = collectionView == self.collectionView ? 0 : 1
        cell.imageView.image = UIImage(named: settingDic[settingArray[item][indexPath.row]]!)
        cell.label.text = LocString(settingArray[item][indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        BluetoothManager.shared.clearDelegate()
//        if AppSettings.shared.language != .Chinese {
//            AppSettings.shared.setLanguage(language: .Chinese)
//        } else {
//            AppSettings.shared.setLanguage(language: .English)
//        }
//        return
        let item = collectionView == self.collectionView ? 0 : 1
        let settingText = settingArray[item][indexPath.row]
        if settingText == "删除设备" {
            if !IsBindDevice {
                MBProgressHUD.showh(LocString("请先绑定设备"))
            } else {
                unbindDevice()
            }
            return
        } else if settingText == "后台保护" {
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "BackgroundVC")
            navigationController?.pushViewController(vc, animated: true)
            return
        }
        
        if showALert() {
            return
        }
        MBProgressHUD.hide()
        
        switch settingText {
        case "目标设置":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "SetGoalsViewController")
            navigationController?.pushViewController(vc, animated: true)
        case "语言设置":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "LanguageSettingVC")
            navigationController?.pushViewController(vc, animated: true)
        case "查找手环":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "FindBraceletVC")
            navigationController?.pushViewController(vc, animated: true)
        case "遥控拍照":
            SystemAuth.authCamera  {[weak self] isAuth in
                if isAuth {
                    let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "CameraViewController") as! CameraViewController
                    vc.modalPresentationStyle = .fullScreen
                    vc.isFromDevice = false
                    self?.present(vc, animated: true, completion: nil)
                    IsCameraOpen = true
                } else {
                    self?.showAlert(title: LocString("提示"), message: LocString("请在“设置-隐私-相机”选项中,允许'YTWatch'访问你的相机"), cancelText: nil, confirm: nil)
                }
            }
        case "其他设置":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "OtherSettingVC") as! OtherSettingVC
//            vc.unitSettingClosure = {[weak self] unit in
//                self?.updateTotalDataView(unit)
//            }
            navigationController?.pushViewController(vc, animated: true)
        case "抬腕亮屏":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "WristViewController")
            navigationController?.pushViewController(vc, animated: true)
        case "勿扰模式":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NotDisturbViewController")
            navigationController?.pushViewController(vc, animated: true)
        case "提醒功能":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "RemindViewController")
            navigationController?.pushViewController(vc, animated: true)
        case "固件升级":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "FirmwareUpdateVC")
            navigationController?.pushViewController(vc, animated: true)
        case "微信运动":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "WeChatSportVC")
            navigationController?.pushViewController(vc, animated: true)
        case "联系人":
            SystemAuth.authContacts {[weak self] isAuth in
                if isAuth {
                    let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "ContactsViewController")
                    self?.navigationController?.pushViewController(vc, animated: true)
                } else {
                    self?.showAlert(title: LocString("提示"), message: LocString("请在“设置-隐私-通讯录”选项中,允许'YTWatch'访问你的通讯录"), cancelText: nil, confirm: nil)
                }
            }
        case "名片":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "CardViewController")
            navigationController?.pushViewController(vc, animated: true)
        case "NFC":
            if #available(iOS 13.0, *) {
                let user = UserInfo
                if user.nfc.count == 0 {
                    let vc1 = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NFCHomeVC")
                    navigationController?.pushViewController(vc1, animated: true)
                } else {
                    let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NFCViewController") as! NFCViewController
                    vc.nfcList = user.nfc
                    navigationController?.pushViewController(vc, animated: true)
                }
            }
        case "钱包":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "PayViewController")
            navigationController?.pushViewController(vc, animated: true)
        
        case "后台保护":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "BackgroundVC")
            navigationController?.pushViewController(vc, animated: true)
        default:
            break
        }
    }
    
    
}