CustomDialViewController.swift 19.9 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
//
//  CustomDialViewController.swift
//  Twear
//
//  Created by yangbin on 2022/1/20.
//

import UIKit
import MBProgressHUD
import Photos
import TZImagePickerController
import SwiftDate


class CustomDialViewController: UIViewController, TZImagePickerControllerDelegate {
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout!
    @IBOutlet weak var styleCollectionView: UICollectionView!
    @IBOutlet weak var styleCollectionViewFlowLayout: UICollectionViewFlowLayout!
    @IBOutlet weak var progressView: CustomProgress!
    var picker: TZImagePickerController?
    var imagePath = "custom"
    
    @IBOutlet weak var timeImageView: UIImageView!
    @IBOutlet weak var backgroundBtn: UIButton!
    @IBOutlet weak var styleBtn: UIButton!
    @IBOutlet weak var positionBtn: UIButton!
    @IBOutlet weak var backUnderLine: UIView!
    @IBOutlet weak var positionUnderLine: UIView!
    @IBOutlet weak var styleUnderLine: UIView!
   
    @IBOutlet weak var imageHeightLayout: NSLayoutConstraint!
    @IBOutlet weak var timeCenterY: NSLayoutConstraint!
    @IBOutlet weak var imageView: UIImageView!
    private var maxImageCount = 1000
    var imageArray: [UIImage] = []
    var imageKeys: [String] = []
    var curIndex: Int = 0
    
    var styleCellCount: Int = 4
    var colorStyle: Int = 1
    var positionStyle: Int = 0
    var curStyle: Int = 0 // 1样式 2位置
    
    var dialWidth: Int = 240
    var dialHeight: Int = 280
    
    var colorDic = ["橙": 0, "白": 1, "红": 6, "蓝": 3, "黄": 7, "绿": 5]
    var colorArray = ["橙", "白", "红", "蓝", "黄", "绿"]
    
    var user = UserInfo
    
    @IBOutlet weak var progressBottomLayout: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        if CurDevice.name.contains("Watch 8") {
//            dialWidth = 240
//            dialHeight = 286
        imageHeightLayout.constant = 180.0*CGFloat(dialHeight)/CGFloat(dialWidth)
//        }
        if CurDevice.name.contains("P8GT") {
            colorArray = ["橙", "白"]
        }
        
        configureCollectionView()

        progressView.label.font = RegularFont(15)
        progressView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(sync)))
        progressBottomLayout.constant = 25 + NAVBAR_HEIGHT
        let imagesName = UIImage.getImagesName(path: imagePath).sorted()
        if imagesName.count > 0 {
//            curIndex = 1
            initProgress()
            imageKeys.append(contentsOf: imagesName)
            for imageName in imagesName {
                imageArray.append(UIImage.getImageFromPath(imageName, path: imagePath)!)
            }
//            imageView.image = imageArray[0]
        } else {
            initProgress(false)
        }
        
        
        if user.customDial == "" {
            imageView.image = UIImage(named: "custom_default")
        } else {
            let customStyleArray = user.customDial.split(separator: "-")
            if customStyleArray.count == 3 {
                curIndex = Int(customStyleArray[0])!
                if curIndex > imageArray.count || curIndex == 0 {
                    curIndex = 0
                    imageView.image = UIImage(named: "custom_default")
                } else {
                    imageView.image = imageArray[curIndex-1]
                }
                colorStyle = Int(customStyleArray[1])!
                positionStyle = Int(customStyleArray[2])!
                timeImageView.image = UIImage(named: "dial_color_\(colorStyle)")
                timeCenterY = timeCenterY.setMultiplier(multiplier: CGFloat(positionStyle)*0.5+0.5)
            }
        }
        
        
       
        
        backgroundBtn.setTitle(LocString("背景"), for: .normal)
        styleBtn.setTitle(LocString("样式"), for: .normal)
        positionBtn.setTitle(LocString("位置"), for: .normal)
        
        // Do any additional setup after loading the view.
    }
    
    func configureCollectionView(){
        collectionViewFlowLayout.scrollDirection = .horizontal
        collectionViewFlowLayout.minimumLineSpacing = 10
        collectionViewFlowLayout.minimumInteritemSpacing = 10
        collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
        collectionViewFlowLayout.itemSize = CGSize(width: 68.5, height: 80)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.bounces = true
        
        //        self.automaticallyAdjustsScrollViewInsets = false
        collectionView.register(UINib.init(nibName: "AddPictureCell", bundle: Bundle.main), forCellWithReuseIdentifier: "AddPictureCell")
        

        styleCollectionViewFlowLayout.minimumLineSpacing = 25
        styleCollectionViewFlowLayout.minimumInteritemSpacing = 10
        styleCollectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        styleCollectionViewFlowLayout.itemSize = CGSize(width: (SCREEN_WIDTH-100.0)/4.0, height: (SCREEN_WIDTH-100.0)/24.0*7.0)
        styleCollectionView.delegate = self
        styleCollectionView.dataSource = self
    
        styleCollectionView.bounces = false
        styleCollectionView.register(UINib.init(nibName: "DialStyleCell", bundle: Bundle.main), forCellWithReuseIdentifier: "DialStyleCell")
    }
    
    
    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
        }
    }
    @IBAction func selectMode(_ sender: UIButton) {
        if IsDailSyncing {
            MBProgressHUD.showh(LocString("正在推送表盘中,请稍后..."))
            return
        }
        backgroundBtn.titleLabel?.font = RegularFont(15)
        styleBtn.titleLabel?.font = RegularFont(15)
        positionBtn.titleLabel?.font = RegularFont(15)
        backgroundBtn.setTitleColor(.black, for: .normal)
        styleBtn.setTitleColor(.black, for: .normal)
        positionBtn.setTitleColor(.black, for: .normal)
        backUnderLine.isHidden = true
        styleUnderLine.isHidden = true
        positionUnderLine.isHidden = true
        sender.titleLabel?.font = BoldFont(15)
        sender.setTitleColor(UIColor.rgbColorFromHex(0x00993E), for: .normal)
        curStyle = sender.tag
        switch sender.tag {
        case 0:
            backUnderLine.isHidden = false
        case 1:
            styleUnderLine.isHidden = false
            styleCellCount = colorArray.count
            styleCollectionView.reloadData()
        case 2:
            positionUnderLine.isHidden = false
            styleCellCount = 3
            styleCollectionView.reloadData()
        default:
            break
        }
        collectionView.isHidden = sender.tag != 0
        styleCollectionView.isHidden = sender.tag == 0
    }
    
    

    
    @IBAction func sync() {
        if showAlert() { return }
        if IsDailSyncing { return }
        let image = resizeImage1(image: self.imageView.image!, targetSize: CGSize(width: dialWidth, height: dialHeight))
//        if self.imageView.image == UIImage(named: "custom_default") {
//            image = resizeImage1(image: self.imageView.image!, targetSize: CGSize(width: dialWidth, height: dialHeight))
//        }
       
        if let imageData = image.rbg565Data(), imageData.count > 0 {
            updateUserInteraction(true)
            updateProgress(0)
            BluetoothManager.shared.syncCustomDial(imageData, colorStyle: colorStyle, position: positionStyle) {[weak self] progress in
                self?.updateProgress(progress)
            } completion: {[weak self] error in
                self?.updateUserInteraction(false)
                if error == nil {
                    self?.updateProgress(100)
                } else {
                    self?.initProgress()
                    self?.showAlert(title: LocString("提示"), message: LocString("安装失败,请重试"), cancelText: nil)
                }
            }
        }
    }
    
    func updateProgress(_ value: Int) {
        if value == 100 {
            progressView.value = 100
            progressView.trackView.backgroundColor = LineColor
            progressView.layer.borderColor = LineColor.cgColor
            progressView.layer.borderWidth = 0
            progressView.label.text = LocString("安装完成")
            progressView.label.textColor = .white
            user.customDial = "\(curIndex)-\(colorStyle)-\(positionStyle)"
            AdminHelper.shared.updateUser(user)
        } else {
            progressView.value = value
            progressView.backView.backgroundColor = .white
            progressView.trackView.backgroundColor = UIColor.rgbColorFromHex(0x64C876)
            progressView.layer.borderWidth = 1
            progressView.layer.borderColor = UIColor.rgbColorFromHex(0x00993E).cgColor
            progressView.label.text = LocString("安装中...")
            progressView.label.textColor = .black            
        }
    }
    
    func initProgress(_ bool: Bool = true) {
        if bool {
            progressView.backView.backgroundColor = TintColor
        } else {
            progressView.backView.backgroundColor = LineColor
        }
        progressView.value = 0
        progressView.label.text = LocString("安装")
        progressView.label.textColor = .white
        progressView.layer.borderWidth = 0
    }

    private func addImages(_ images: [UIImage]) {
        if IsDailSyncing {
            MBProgressHUD.showh(LocString("正在推送表盘中,请稍后..."))
            return
        }
        _ = MBProgressHUD.showMessage("")
        DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
            self.initProgress()
            self.curIndex = self.imageArray.count+1
            for image in images {
                self.imageArray.append(image)
                self.imageView.image = image
                let key = Date().toString(.custom("MMddHHmmss"))
                self.imageKeys.append(key)
                _ = image.saveImageToPath(key, path: self.imagePath)
            }
            
            MBProgressHUD.hide()
            self.collectionView.reloadData()
        }
        
    }
    
    private func deleteImage(_ item: Int) {
        if IsDailSyncing {
            MBProgressHUD.showh(LocString("正在推送表盘中,请稍后..."))
            return
        }
        let alertVC = UIAlertController(title: LocString("提示"), message: LocString("确定删除此背景吗?"), preferredStyle: .alert)
        let confirm = UIAlertAction(title: LocString("确定"), style: .destructive) { [weak self] (action) in
            if UIImage.deleteImage(name: (self?.imageKeys[item])!, path: (self?.imagePath)!) {
                self?.imageArray.remove(at: item)
                self?.imageKeys.remove(at: item)
            }
            if self?.imageArray.count == 0 {
                self?.curIndex = 0
                self?.imageView.image = UIImage(named: "custom_default")
                self?.initProgress(false)
            } else {
                if self?.imageArray.count == item {
                    self?.curIndex = item
                    self?.imageView.image = self?.imageArray[item-1]
                } else if item+1 == self?.curIndex {
                    self?.imageView.image = self?.imageArray[item]
                } else {
                    self?.curIndex -= 1
                }
                self?.initProgress()
            }
            self?.collectionView.reloadData()
        }
        let cancel = UIAlertAction(title: LocString("取消"), style: .default, handler: nil)
        alertVC.addAction(cancel)
        alertVC.addAction(confirm)
        present(alertVC, animated: true, completion: nil)
    }
    
    func updateUserInteraction(_ isSyncing: Bool) {
        IsDailSyncing = isSyncing
        UIApplication.shared.isIdleTimerDisabled = isSyncing
        let navController = navigationController as? ZCNavigationController
        navController?.enableScreenEdgePanGestureRecognizer(!isSyncing)
    }
    
    deinit {
        print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!")
    }
    
    private func photoAlbum() {
        
        if PHPhotoLibrary.authorizationStatus().rawValue == 2 {
            MBProgressHUD.show("请在“设置-隐私-照片“选项中,允许'YTWatch'访问你的照片")
            return
        }
        //        maxImageCount-imageArray.count
        picker = TZImagePickerController(maxImagesCount: 1, columnNumber: 3, delegate: self)
        picker?.modalPresentationStyle = .fullScreen
        //        picker?.allowPickingVideo = true
        //        if imageArray.count > 0 {
        //            if newsType == .image {
        picker?.allowPickingVideo = false
        //            }
        //        }240 280
        //视频
        picker?.scaleAspectFillCrop = true
        picker?.allowCameraLocation = false //位置
        let cropWidth: CGFloat = SCREEN_WIDTH*0.65
        let cropHeight: CGFloat = cropWidth*CGFloat(dialHeight)/CGFloat(dialWidth)
        picker?.cropRect = CGRect(x: (SCREEN_WIDTH-cropWidth)/2, y: (SCREEN_HEIGHT-cropHeight)/2, width: cropWidth, height: cropHeight)
        picker?.allowPickingGif = false //GIF
        picker?.allowTakePicture = true //内部拍照
        picker?.allowCrop = true //裁剪
        
        picker?.didFinishPickingPhotosHandle = {[weak self] (photos, assets, isSelectOriginalPhoto) -> Void in
            if let images = photos {
                self?.addImages(images)
                
            }
        }
        

        self.present(picker!, animated: true, completion: nil)
        
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    func resizeImage1(image: UIImage, targetSize: CGSize) -> UIImage {

        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)

        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0)
        image.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }
    
    func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
        let size = image.size

        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height

        // Figure out what our orientation is, and use that to form the rectangle
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
        }

        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }
    
}
extension CustomDialViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if IsDailSyncing {
            MBProgressHUD.showh(LocString("正在推送表盘中,请稍后..."))
            return
        }
        if collectionView == self.collectionView {
            if indexPath.row == 0 {
                if imageArray.count <= maxImageCount {
                    photoAlbum()
                } else {
                    MBProgressHUD.showh(LocString("最多只能添加9张图片"))
                }
            } else {
                curIndex = indexPath.row
                imageView.image = imageArray[indexPath.row-1]
                collectionView.reloadData()
                initProgress()
            }
        } else {
            if curStyle == 1 { //样式
                colorStyle = colorDic[colorArray[indexPath.row]]!
                timeImageView.image = UIImage(named: "dial_color_\(colorStyle)")
            } else {//位置
                positionStyle = indexPath.row
                timeCenterY = timeCenterY.setMultiplier(multiplier: CGFloat(positionStyle)*0.5+0.5)
            }
            initProgress()
            collectionView.reloadData()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.collectionView {
            return imageArray.count + 1
        } else {
            return styleCellCount
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.collectionView {
            let cell: AddPictureCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddPictureCell", for: indexPath) as! AddPictureCell
            var array = imageArray
            array.insert(UIImage(named: "image_add")!, at: 0)
            var keyArray = imageKeys
            keyArray.insert("add", at: 0)
            if indexPath.row == 0 {
                cell.selectedImageView.isHidden = true
            } else if indexPath.row == curIndex {
                cell.selectedImageView.isHidden = false
            } else {
                cell.selectedImageView.isHidden = true
            }
            cell.deleteBtn.isHidden = indexPath.row == 0//imageArray.count
            cell.picture.image = array[indexPath.row]
            cell.imageKey = keyArray[indexPath.row]
            
            cell.deleteBtnBlock = {[weak self] in
                self?.deleteImage(indexPath.row-1)
            }
            return cell
        } else {
            let cell: DialStyleCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DialStyleCell", for: indexPath) as! DialStyleCell
            if curIndex == 0 {
                cell.picture.image = UIImage(named: "custom_default")
            } else {
                cell.picture.image = imageArray[curIndex-1]
            }
            if curStyle == 1 { //样式
                if colorDic[colorArray[indexPath.row]]! == colorStyle {
                    cell.selectedImageView.isHidden = false
                } else {
                    cell.selectedImageView.isHidden = true
                }
                
                cell.timeImageView.image = UIImage(named: "dial_color_\(colorDic[colorArray[indexPath.row]]!)")
                cell.timeCenterY = cell.timeCenterY.setMultiplier(multiplier: CGFloat(positionStyle)*0.5+0.5)
            } else {
                if indexPath.row == positionStyle {
                    cell.selectedImageView.isHidden = false
                } else {
                    cell.selectedImageView.isHidden = true
                }
                cell.timeImageView.image = UIImage(named: "dial_color_\(colorStyle)")
                cell.timeCenterY = cell.timeCenterY.setMultiplier(multiplier: CGFloat(indexPath.row)*0.5+0.5)
            }
            
            return cell
            
        }
        
        
        
    }
    
    
}