MotionViewController.swift 13.4 KB
//
//  MotionViewController.swift
//  Twear
//
//  Created by yangbin on 2021/11/16.
//

import UIKit
import SnapKit
import MBProgressHUD

class MotionViewController: UIViewController {
    
    @IBOutlet weak var mapBackView: UIView!
    
    @IBOutlet weak var underLine: UIImageView!
    @IBOutlet weak var climbBtn: UIButton!
    @IBOutlet weak var rideBtn: UIButton!
    @IBOutlet weak var walkBtn: UIButton!
    @IBOutlet weak var runBtn: UIButton!
    @IBOutlet weak var typeImageView: UIImageView!
    @IBOutlet weak var distanceLabel: UILabel!
    @IBOutlet weak var detailLabel: UILabel!
    @IBOutlet weak var distanceUnitLabel: UILabel!
    @IBOutlet weak var totalDistanceLabel: UILabel!
    @IBOutlet weak var detailButton: UIButton!
    
    @IBOutlet weak var runModeView: UIView!
    @IBOutlet weak var outdoorBtn: UIButton!
    @IBOutlet weak var indoorBtn: UIButton!
    var selectedMode: TrainType = .running
    
    private lazy var mapView: MAMapView = MAMapView()
    
    var device = CurDevice
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        device = CurDevice
        getMotionHistory(selectedMode.rawValue)
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initNav()
        SystemAuth.authLocation {isAllow, isFirst in
//            if !isAllow {
//                self?.showAlert(title: "提示", message: "请打开定位服务以获取您的运动轨迹")
//            }
        }
        
        outdoorBtn.setTitle(LocString("户外"), for: .normal)
        indoorBtn.setTitle(LocString("室内"), for: .normal)
        
        initMapView()
//        getMotionHistory()
    }
    
    func initNav() {
        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)
        navigationItem.leftBarButtonItem =  UIBarButtonItem(customView: setButton)
    }
    
    func initMapView() {
        MAMapView.updatePrivacyShow(.didShow, privacyInfo: .didContain)
        MAMapView.updatePrivacyAgree(.didAgree)
        
        mapView.showsUserLocation = false
        mapView.userTrackingMode = .follow
        mapView.showsCompass = false
        mapView.zoomLevel = 16
        
        mapView.mapLanguage = (AppSettings.shared.language == .Chinese) ? 0 : 1
        
        let currentLocation = MAUserLocationRepresentation()
        currentLocation.showsAccuracyRing = true//精度圈是否显示
        currentLocation.fillColor = UIColor(white: 1, alpha: 0)//精度圈填充颜色
        currentLocation.strokeColor = UIColor(white: 1, alpha: 0)//调整精度圈边线颜色
        currentLocation.showsHeadingIndicator = false//是否显示蓝点方向指向
//        currentLocation.image = UIImage(named: "selected") //定位图标, 与蓝色原点互斥
        currentLocation.locationDotBgColor = .clear
        currentLocation.locationDotFillColor = .clear
        currentLocation.enablePulseAnnimation = false
//        currentLocation.a
        mapView.update(currentLocation)
        mapView.frame = mapBackView.bounds
        mapBackView.addSubview(mapView)
        
        
  
    }
    
    private func getMotionHistory(_ type: Int = 0) {
        guard let array = RealmTools.objectsWithPredicateAndSorted(object: MotionModel.self, predicate: NSPredicate(format: "typeRaw = %@", argumentArray:[type]), sortedKey: "date") as? Array<MotionModel>, array.count > 0 else {
            distanceLabel.text = "0"
            if device.distanceUnit == 0 {
                distanceUnitLabel.text = LocString("公里")
                if selectedMode == .mountaineering {
                    let str = NSMutableAttributedString(string: "0"+LocString("米"))
                    str.addAttributes([.font: BoldFont(40)], range: NSMakeRange(0, str.length-LocString("米").count))
                    str.addAttributes([.font: RegularFont(15)], range: NSMakeRange(str.length-LocString("米").count, LocString("米").count))
                    totalDistanceLabel.attributedText = str
                } else {
                    let str = NSMutableAttributedString(string: "0"+LocString("公里"))
                    str.addAttributes([.font: BoldFont(40)], range: NSMakeRange(0, str.length-LocString("公里").count))
                    str.addAttributes([.font: RegularFont(15)], range: NSMakeRange(str.length-LocString("公里").count, LocString("公里").count))
                    totalDistanceLabel.attributedText = str
                }
            } else {
                distanceUnitLabel.text = LocString("英里")
                if selectedMode == .mountaineering {
                    let str = NSMutableAttributedString(string: "0"+LocString("英尺"))
                    str.addAttributes([.font: BoldFont(40)], range: NSMakeRange(0, str.length-LocString("英尺").count))
                    str.addAttributes([.font: RegularFont(15)], range: NSMakeRange(str.length-LocString("英尺").count, LocString("英尺").count))
                    totalDistanceLabel.attributedText = str
                } else {
                    let str = NSMutableAttributedString(string: "0"+LocString("英里"))
                    str.addAttributes([.font: BoldFont(40)], range: NSMakeRange(0, str.length-LocString("英里").count))
                    str.addAttributes([.font: RegularFont(15)], range: NSMakeRange(str.length-LocString("英里").count, LocString("英里").count))
                    totalDistanceLabel.attributedText = str
                }
                
            }
     
            return
        }
//        var distanceStr = ""
        if device.distanceUnit == 0 {
            let distanceStr = String(format:"%.2f", Float(array.sum(\.distance))/1000)
            distanceLabel.text = distanceStr
            distanceUnitLabel.text = LocString("公里")
            if selectedMode == .mountaineering {
                let altitudeStr = String(format:"%.2f", Float(array.sum(\.altitude)))
                let str = NSMutableAttributedString(string: "\(altitudeStr)\(LocString("米"))")
                str.addAttributes([.font: BoldFont(40)], range: NSMakeRange(0, str.length-LocString("米").count))
                str.addAttributes([.font: RegularFont(15)], range: NSMakeRange(str.length-LocString("米").count, LocString("米").count))
                totalDistanceLabel.attributedText = str
            } else {
                let str = NSMutableAttributedString(string: "\(distanceStr)\(LocString("公里"))")
                str.addAttributes([.font: BoldFont(40)], range: NSMakeRange(0, str.length-LocString("公里").count))
                str.addAttributes([.font: RegularFont(15)], range: NSMakeRange(str.length-LocString("公里").count, LocString("公里").count))
                totalDistanceLabel.attributedText = str
            }
        } else {
            let distanceStr = (Float(array.sum(\.distance))/1000).mileString()
            distanceLabel.text = distanceStr
            distanceUnitLabel.text = LocString("英里")
            if selectedMode == .mountaineering {
                let altitudeStr = Float(array.sum(\.altitude)).footString()
                let str = NSMutableAttributedString(string: "\(altitudeStr)\(LocString("英尺"))")
                str.addAttributes([.font: BoldFont(40)], range: NSMakeRange(0, str.length-LocString("英尺").count))
                str.addAttributes([.font: RegularFont(15)], range: NSMakeRange(str.length-LocString("英尺").count, LocString("英尺").count))
                totalDistanceLabel.attributedText = str
            } else {
                let str = NSMutableAttributedString(string: "\(distanceStr)\(LocString("英里"))")
                str.addAttributes([.font: BoldFont(40)], range: NSMakeRange(0, str.length-LocString("英里").count))
                str.addAttributes([.font: RegularFont(15)], range: NSMakeRange(str.length-LocString("英里").count, LocString("英里").count))
                totalDistanceLabel.attributedText = str
            }
        }
       
    }
    
    
    
    
    @IBAction func selectMotionMode(_ sender: UIButton) {
        climbBtn.titleLabel?.font = RegularFont(16)
        rideBtn.titleLabel?.font = RegularFont(16)
        walkBtn.titleLabel?.font = RegularFont(16)
        runBtn.titleLabel?.font = RegularFont(16)
        sender.titleLabel?.font = BoldFont(16)
        switch sender.tag {
        case 0:
            selectedMode = .running
            typeImageView.image = UIImage(named: "run_bg")
            detailButton.setTitle(LocString("跑步总里程"), for: .normal)
            runModeView.isHidden = false
            if outdoorBtn.titleColor(for: .normal)! == TintColor {
                selectedMode = .running
                detailLabel.text = LocString("户外跑步总距离")
            } else {
                selectedMode = .run_indoor
                detailLabel.text = LocString("室内跑步总距离")
            }
        case 1:
            selectedMode = .walking
            typeImageView.image = UIImage(named: "walk_bg")
            detailLabel.text = LocString("步行总距离")
            detailButton.setTitle(LocString("步行总里程"), for: .normal)
            runModeView.isHidden = true
        case 2:
            selectedMode = .bicycle
            typeImageView.image = UIImage(named: "ride_bg")
            detailLabel.text = LocString("骑行总距离")
            detailButton.setTitle(LocString("骑行总里程"), for: .normal)
            runModeView.isHidden = true
        case 3:
            selectedMode = .mountaineering
            typeImageView.image = UIImage(named: "climb_bg")
            detailLabel.text = LocString("爬山总距离")
            detailButton.setTitle(LocString("爬升总高度"), for: .normal)
            runModeView.isHidden = true
        default:
            break
        }
        getMotionHistory(selectedMode.rawValue)
        
        UIView.animate(withDuration: 0.2) {
            self.underLine.center.x = sender.center.x
        }
    }
    
    
    @IBAction func selectRunMode(_ sender: UIButton) {
        if sender.tag == 0 {
            outdoorBtn.setTitleColor(TintColor, for: .normal)
            indoorBtn.setTitleColor(.black, for: .normal)
            detailLabel.text = LocString("户外跑步总距离")
            selectedMode = .running
        } else {
            outdoorBtn.setTitleColor(.black, for: .normal)
            indoorBtn.setTitleColor(TintColor, for: .normal)
            detailLabel.text = LocString("室内跑步总距离")
            selectedMode = .run_indoor
        }
        getMotionHistory(selectedMode.rawValue)
    }
    
    
    @IBAction func startMotion(_ sender: Any) {
        SystemAuth.authLocation {[weak self] isAllow, isFirst in
            if !isAllow {
                self?.showAlert(title: LocString("提示"), message: LocString("请打开定位服务以获取您的运动轨迹"))
            } else {
                let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Motion", identifier: "StartMotionVC") as! StartMotionVC
                vc.motionType = (self?.selectedMode)!
                vc.modalPresentationStyle = .fullScreen
                self?.present(vc, animated: false, completion: nil)
            }
        }
      
    }
    
    @IBAction func showDetailInfo(_ sender: Any) {
        let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Motion", identifier: "RecordDetailVC") as! RecordDetailVC
        vc.motionType = selectedMode
        navigationController?.pushViewController(vc, animated: true)
    }
    
    deinit {
        print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!")
    }

}


extension MotionViewController: MAMapViewDelegate {
    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        if !updatingLocation {
            return
        }
        
        let location: CLLocation? = userLocation.location
        
        if location == nil {
            return
        }
        
//        if isRecording {
//            // filter the result
//            if userLocation.location.horizontalAccuracy < 100.0 {
//
//                addLocation(location: userLocation.location)
//            }
//        }
//
//        var speed = location!.speed
//        if speed < 0.0 {
//            speed = 0.0
//        }
//
//        let infoArray: [(String, String)] = [
//            ("coordinate", NSString(format: "<%.4f, %.4f>", location!.coordinate.latitude, location!.coordinate.longitude) as String),
//            ("speed", NSString(format: "%.2fm/s(%.2fkm/h)", speed, speed * 3.6) as String),
//            ("accuracy", "\(location!.horizontalAccuracy)m"),
//            ("altitude", NSString(format: "%.2fm", location!.altitude) as String)]
//
//        statusView!.showStatusInfo(info: infoArray)
        
    }
    func mapViewDidFinishLoadingMap(_ mapView: MAMapView!) {
        print("1111")
    }
    
    func mapViewDidFailLoadingMap(_ mapView: MAMapView!, withError error: Error!) {
        print("111231232111")
    }

    func mapView(_ mapView: MAMapView, didChange mode: MAUserTrackingMode, animated: Bool) {
//        if mode == MAUserTrackingMode.none {
//            locationButton?.setImage(imageNotLocate, for: UIControlState.normal)
//        }
//        else {
//            locationButton?.setImage(imageLocated, for: UIControlState.normal)
//        }
    }

}