MineViewController.swift 17.8 KB
//
//  MineViewController.swift
//  Twear
//
//  Created by yangbin on 2021/12/18.
//

import UIKit
import MBProgressHUD
import Alamofire
import HandyJSON

class MineViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var idLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!
    
//    @IBOutlet weak var medalNumLabel: UILabel!
//    @IBOutlet weak var medalImageView1: UIImageView!
//    @IBOutlet weak var medalImageView2: UIImageView!
//    @IBOutlet weak var medalImageView3: UIImageView!
//    @IBOutlet weak var medalImageView4: UIImageView!
//    @IBOutlet weak var medalImageView5: UIImageView!
//    @IBOutlet weak var locLabel1: UILabel!
    private let mineArray = ["健康报告", "我的数据", "个人资料", "隐私政策", "APP升级", "关于"]
    private let mineDic = ["健康报告": "health_report", "我的数据": "mine_data", "个人资料": "personal_info", "设置": "mine_setting", "APP升级": "app_update", "关于": "mine_about", "隐私政策": "privacy_policy"]
    
    private let user = UserInfo

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()


    }
    
    private func setupUI() {
        let leftButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 28))
        leftButton.setTitle(LocString("我的"), for: .normal)
        leftButton.titleLabel?.font = BoldFont(18)
        leftButton.setTitleColor(.black, for: .normal)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
        
        tableView.bounces = false
        
        if let image = UIImage.getImageFromPath("avatar") {
            avatarImageView.image = image
        } else {
            avatarImageView.image = UIImage(named: user.gender == 1 ? "avatar_male" : "avatar_female")
        }
        
        if user.name == "" {
            nameLabel.text = "YTWatch"//"\(LocString("用户")):\(user.userId)"
        } else {
            nameLabel.text = user.name
        }
        
        idLabel.text = "\(user.gender == 1 ? "男" : "女") \(user.height)cm"
        
//        locLabel1.text = LocString("我的勋章")
        
//        var medalArray = ["单日10000步灰", "单日10000步灰", "单日10000步灰", "累计5万步灰", "累计10万步灰"]
//        var medalNum: Int = 0
//        if let array = RealmTools.objectsWithPredicateAndSorted(object: MedalModel.self, predicate: NSPredicate(format: "date != nil"), sortedKey: "date") as? Array<MedalModel>, array.count > 0 {
//            medalNum = array.count
//            for medal in array {
//                medalArray.insert(medal.title, at: 0)
//            }
//        }
//        medalNumLabel.text = LocString("共1") + "\(medalNum)" + LocString("枚1")
//        medalImageView1.image = UIImage(named: medalArray[0])
//        medalImageView2.image = UIImage(named: medalArray[1])
//        medalImageView3.image = UIImage(named: medalArray[2])
//        medalImageView4.image = UIImage(named: medalArray[3])
//        medalImageView5.image = UIImage(named: medalArray[4])
      
    }
    
    @IBAction func setUserInfo(_ sender: Any) {
        let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Mine", identifier: "UserInfoSettingVC") as! UserInfoSettingVC
        vc.modifyClosure = {[weak self] name, image in
            if image != nil {
                self?.avatarImageView.image = image
            }
            if name != "" {
                self?.nameLabel.text = name
            }
            
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func gotoMedalVC(_ sender: Any) {
        let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Mine", identifier: "MedalViewController") as! MedalViewController
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func checkAppVersion() {
        MBProgressHUD.showLoading(LocString("正在拼命加载..."), icon: "loading_icon")
        let infoDictionary : Dictionary = Bundle.main.infoDictionary!
        let curVersion = infoDictionary["CFBundleShortVersionString"] as? String
        let path = "https://itunes.apple.com/cn/lookup?id=1601611643"//
        var version: String = ""
        Alamofire.request(path, method: .post).response { (responseObj) in
            if responseObj.error == nil {
                let dic:Dictionary = try! JSONSerialization.jsonObject(with: responseObj.data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,Any>
                if  dic["resultCount"] as! Int > 0{
                    let results:Array = dic["results"] as! Array<Any>
                    if results.count > 0 {
                        let resultsDic: Dictionary = results.first as! Dictionary<String,Any>
                        version = resultsDic["version"] as! String
//                        let size = resultsDic["fileSizeBytes"] as! Int
                        let releaseNotes = resultsDic["releaseNotes"] as? String ?? "   "
                        let trackViewUrl = resultsDic["trackViewUrl"] as! String
                        if curVersion!.checkVersion(version) { //发现新版本
                            MBProgressHUD.hide()
                            let updateView = AppVersionView(version: version, detail: releaseNotes)
                            updateView.clickClosure = { [weak self] in
                                self?.gotoAppStore(trackViewUrl)
                            }
                            
                            updateView.show()
                        } else {
                            MBProgressHUD.hide()
                            MBProgressHUD.showh(LocString("当前已是最新版本"))
                        }
                    }
                }
            }
        }
    }
    

    
    
    func gotoAppStore(_ urlString: String) {
        let updateUrl: URL = URL(string: urlString)!
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(updateUrl, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(updateUrl)
        }
    }
    
    deinit {
        print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!")
    }

}


extension MineViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 62
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return mineArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MineCell", for: indexPath) as! MineCell
        cell.label.text = LocString(mineArray[indexPath.row])
        cell.setImageView.image = UIImage(named: mineDic[mineArray[indexPath.row]]!)
        if indexPath.row == mineArray.count-1 {
            cell.lineView.isHidden = true
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch mineArray[indexPath.row] {
        case "APP升级":
            checkAppVersion()
        case "个人资料":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Mine", identifier: "UserInfoSettingVC") as! UserInfoSettingVC
            vc.modifyClosure = {[weak self] name, image in
                self?.avatarImageView.image = image
                self?.nameLabel.text = name
            }
            navigationController?.pushViewController(vc, animated: true)
        case "关于":
            //jtd!
//            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Mine", identifier: "AboutAppVC")
//            navigationController?.pushViewController(vc, animated: true)
            let alert = UIAlertController(title: "plz select", message: nil, preferredStyle: .actionSheet)
            let archiveAction1 = UIAlertAction(title: "newSetTouchSense", style: .default) { action in
                BluetoothManager.shared.newSetTouchSense(bool: true) { error in
                    if error != nil {
                        print("newSetTouchSense" + (error?.description ?? "") )
                    }else {
                        print("newSetTouchSense success")
                    }
                }
            }
            let archiveAction2 = UIAlertAction(title: "newSetLowPowerRemind", style: .default) { action in
                BluetoothManager.shared.newSetLowPowerRemind(bool: true) { error in
                    if error != nil {
                        print("newSetLowPowerRemind" + (error?.description ?? ""))
                    }else {
                        print("newSetLowPowerRemind success")
                    }
                }
            }
            let archiveAction3 = UIAlertAction(title: "newSetRestore", style: .default) { action in
                BluetoothManager.shared.newSetRestore() { error in
                    if error != nil {
                        print("newSetRestore" + (error?.description ?? ""))
                    }else {
                        print("newSetRestore success")
                    }
                }
            }
            let archiveAction4 = UIAlertAction(title: "newSetHeartRateHighRemind", style: .default) { action in
                BluetoothManager.shared.newSetHeartRateHighRemind(maxHr: 120) { error in
                    if error != nil {
                        print("newSetHeartRateHighRemind" + (error?.description ?? ""))
                    }else {
                        print("newSetHeartRateHighRemind success")
                    }
                }
            }
            let archiveAction5 = UIAlertAction(title: "newSetHeartRateLowRemind", style: .default) { action in
                BluetoothManager.shared.newSetHeartRateLowRemind(minHr: 120) { error in
                    if error != nil {
                        print("newSetHeartRateLowRemind" + (error?.description ?? ""))
                    }else {
                        print("newSetHeartRateLowRemind success")
                    }
                }
            }
            let archiveAction6 = UIAlertAction(title: "newSetPressureAutoDetect", style: .default) { action in
                BluetoothManager.shared.newSetPressureAutoDetect(bool: true) { error in
                    if error != nil {
                        print("newSetPressureAutoDetect" + (error?.description ?? ""))
                    }else {
                        print("newSetPressureAutoDetect success")
                    }
                }
            }
            let archiveAction7 = UIAlertAction(title: "newSetBloodOxygenAutoDetect", style: .default) { action in
                BluetoothManager.shared.newSetBloodOxygenAutoDetect(bool: true) { error in
                    if error != nil {
                        print("newSetBloodOxygenAutoDetect" + (error?.description ?? ""))
                    }else {
                        print("newSetBloodOxygenAutoDetect success")
                    }
                }
            }
            let archiveAction8 = UIAlertAction(title: "newSetUserInfo", style: .default) { action in
                BluetoothManager.shared.newSetUserInfo(AdminHelper.shared.loadLocalAdminData().userInfo) { error in
                    if error != nil {
                        print("newSetUserInfo" + (error?.description ?? ""))
                    }else {
                        print("newSetUserInfo success")
                    }
                }
            }
            let archiveAction9 = UIAlertAction(title: "getSleepHistoryData", style: .default) { action in
                BluetoothManager.shared.getSleepHistoryData() { sleepArray, error in
                    if error != nil {
                        print("getSleepHistoryData" + (error?.description ?? ""))
                    }else {
                        print("getSleepHistoryData success")
                        SleepModel.addArray(sleepArray)
                    }
                }
            }
            let archiveAction10 = UIAlertAction(title: "getBloodOxygenHistoryData", style: .default) { action in
                BluetoothManager.shared.getBloodOxygenHistoryData() { boArray, error in
                    if error != nil {
                        print("getBloodOxygenHistoryData" + (error?.description ?? ""))
                    }else {
                        print("getBloodOxygenHistoryData success")
                    }
                }
            }
            
            let archiveAction11 = UIAlertAction(title: "queryDeviceInfo", style: .default) { action in
                BluetoothManager.shared.queryDeviceInfo(queryItems: [0x02,0x03]) { error in
                    if error != nil {
                        print("queryDeviceInfo" + (error?.description ?? ""))
                    }else {
                        print("queryDeviceInfo success")
                    }
                }
            }
            
            let archiveAction12 = UIAlertAction(title: "newSetNotDisturb", style: .default) { action in
                BluetoothManager.shared.newSetNotDisturb(remind: CurDevice.disturb) { error in
                    if error != nil {
                        print("newSetNotDisturb" + (error?.description ?? ""))
                    }else {
                        print("newSetNotDisturb success")
                    }
                }
            }
            
            let archiveAction13 = UIAlertAction(title: "newSetFindWatch", style: .default) { action in
                BluetoothManager.shared.newSetFindWatch(bool: true) { error in
                    if error != nil {
                        print("newSetFindWatch" + (error?.description ?? ""))
                    }else {
                        print("newSetFindWatch success")
                    }
                }
            }
            
            let archiveAction14 = UIAlertAction(title: "getHeartRateHistoryData", style: .default) { action in
                BluetoothManager.shared.getHeartRateHistoryData() { boArray, error in
                    if error != nil {
                        print("getHeartRateHistoryData" + (error?.description ?? ""))
                    }else {
                        print("getHeartRateHistoryData success")
                    }
                }
            }
            
            let archiveAction15 = UIAlertAction(title: "getStepHistoryData", style: .default) { action in
                BluetoothManager.shared.getStepHistoryData() { boArray, error in
                    if error != nil {
                        print("getStepHistoryData" + (error?.description ?? ""))
                    }else {
                        print("getStepHistoryData success")
                    }
                }
            }
            
            let archiveAction16 = UIAlertAction(title: "getTrainHistoryData", style: .default) { action in
                BluetoothManager.shared.getTrainHistoryData() { boArray, error in
                    if error != nil {
                        print("getTrainHistoryData" + (error?.description ?? ""))
                    }else {
                        print("getTrainHistoryData success")
                    }
                }
            }
            
            let archiveAction17 = UIAlertAction(title: "getPressureHistoryData", style: .default) { action in
                BluetoothManager.shared.getPressureHistoryData() { boArray, error in
                    if error != nil {
                        print("getPressureHistoryData" + (error?.description ?? ""))
                    }else {
                        print("getPressureHistoryData success")
                    }
                }
            }
            
            let archiveAction18 = UIAlertAction(title: "newSetTime", style: .default) { action in
                BluetoothManager.shared.newSetTime { error in
                    if error != nil {
                        print("newSetTime" + (error?.description ?? ""))
                    }else {
                        print("newSetTime success")
                    }
                }
            }
            
            alert.addAction(archiveAction1)
            alert.addAction(archiveAction2)
            alert.addAction(archiveAction3)
            alert.addAction(archiveAction4)
            alert.addAction(archiveAction5)
            alert.addAction(archiveAction6)
            alert.addAction(archiveAction7)
            alert.addAction(archiveAction8)
            alert.addAction(archiveAction9)
            alert.addAction(archiveAction10)
            alert.addAction(archiveAction11)
            alert.addAction(archiveAction12)
            alert.addAction(archiveAction13)
            alert.addAction(archiveAction14)
            alert.addAction(archiveAction15)
            alert.addAction(archiveAction16)
            alert.addAction(archiveAction17)
            alert.addAction(archiveAction18)
            present(alert, animated: true, completion: nil)
        case "我的数据":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Mine", identifier: "HealthDataVC")
            navigationController?.pushViewController(vc, animated: true)
        case "健康报告":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Mine", identifier: "HealthReportVC")
            navigationController?.pushViewController(vc, animated: true)
        case "隐私政策":
            let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Mine", identifier: "PrivacyViewController")
            navigationController?.pushViewController(vc, animated: true)
            
        default:
            break
        }
    }
    
}