MyViewController.swift 13.7 KB
//
//  MyViewController.swift
//  ParentAssistant
//
//  Created by 葛建军 on 2018/3/5.
//  Copyright © 2018年 HANGZHOUTEAM. All rights reserved.
//

import UIKit
import CoreData
class MyViewController: UIViewController {
    @IBOutlet var currentInfoTableView: UITableView!
    @IBOutlet var titleViewHeight: NSLayoutConstraint!
    @IBOutlet var headerBackGroundImageView: UIImageView!//整个header的背景图
    @IBOutlet var personIconImageView: UIImageView!//用户头像
    @IBOutlet var currentInfoView: UIView!
    @IBOutlet var personNameLabel: UILabel!//用户名称
    @IBOutlet var personNumberLabel: UILabel!//用户账号
    @IBOutlet var loginBtn: UIButton!//登录按钮
    @IBOutlet var currentInfoBtn: UIButton!//查看个人信息按钮
    @IBOutlet var logoutBtn: UIButton!
    var titleDataSet:[String]=["消息","订购详情","订购中心","我的孩子","空白","意见与反馈","清除缓存","关于"]
    var iconDataSet:[String] = ["my_icon_orderMessage","my_icon_orderDetail","my_icon_order","my_icon_children","","my_icon_service","my_icon_cachingClear","my_icon_about"]
    override func viewDidLoad() {
        super.viewDidLoad()
        layoutSubViews()
    }
    // MARK: - 设置控件属性
    func layoutSubViews(){
        let backImage = UIImage(named: "navigationBar_backgrounImage")
        self.navigationController?.navigationBar.setBackgroundImage(backImage, for: UIBarMetrics.default)
        // MARK: - 是否是iPhoneX顶部刘海
        if UIApplication.shared.statusBarFrame.size.height>20 {
            titleViewHeight.constant = 88
        }else{
            titleViewHeight.constant = 64
        }
        personIconImageView.layer.borderWidth = 1.0
        personIconImageView.layer.borderColor = UIColor.white.cgColor
        self.navigationController?.isNavigationBarHidden = true
        let backButton = UIBarButtonItem()
        backButton.title = "个人中心"
        self.navigationItem.backBarButtonItem = backButton
        self.configTheme()
        //添加退出登录的通知,防止在本页面时账号被顶 不能及时刷新页面
        NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.loginOutNotificationAction), name: NSNotification.Name(rawValue: "loginOutSuccess"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.receivedNewNotificationAction), name: NSNotification.Name(rawValue: MessageNotification.receiveMessage), object: nil)
    }
    // MARK: - 页面将要显示时隐藏navigationbar显示自定义的顶部view
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
        // MARK: - 设置是否登录及个人信息
        setupCurrentInfo()
    }
    // MARK: - 页面将要消失时显示navigationbar
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.isNavigationBarHidden = false
    }
    // MARK: - 设置是否登录及个人信息
    func setupCurrentInfo() {
        if AccountManager.shared.isOnline() {
            logoutBtn.isHidden = false
            personNameLabel.isHidden = false
            personNumberLabel.isHidden = false
            loginBtn.isHidden = true
            currentInfoBtn.isHidden = false
            //赋值
            headerBackGroundImageView.image = UIImage(named: "my_headerView_backgroundimageView")
            let info = AccountManager.shared
            personNameLabel.text = info.name()
            personNumberLabel.text = info.phone()
            personIconImageView.sd_setImage(with: URL(string: AccountManager.shared.photo().addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "defphoto"))
        }else{
            logoutBtn.isHidden = true
            personNameLabel.isHidden = true
            personNumberLabel.isHidden = true
            loginBtn.isHidden = false
            currentInfoBtn.isHidden = true
            headerBackGroundImageView.image = UIImage(named: "navigationBar_backgrounImage")
            personIconImageView.image = UIImage(named: "my_defphoto")
        }
        currentInfoTableView.reloadData()
    }
    // MARK: - 登录按钮点击方法
    @IBAction func showLoginAction(_ sender: UIButton) {
        let vc = Story.instantiateViewControllerWithIdentifier("LoginViewController", storyName: "My") as! LoginViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK: - 个人信息按钮点击方法
    @IBAction func showCurrentInfoAction(_ sender: UIButton) {
        let vc = Story.instantiateViewControllerWithIdentifier("CurrentInfoViewController", storyName: "My") as! CurrentInfoViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK: - 退出登录按钮点击方法
    @IBAction func loginOutAction(_ sender: UIButton) {
        SVProgressHUD.show()
        YXMessageManager.share.loginOut { (finish) in
            SVProgressHUD.dismiss()
            if finish {
                AccountManager.shared.logOut()
            }else{
                appDelegate.window!.makeToast("云信退出登录失败", duration: 1, position: CSToastPositionCenter)
            }
        }
    }
    // MARK: - 退出登录时
    @objc func loginOutNotificationAction(){
        self.setupCurrentInfo()
        self.currentInfoTableView.reloadData()
    }
    // MARK: - 收到新通知时
    @objc func receivedNewNotificationAction(){
        let array = NSManagedObject.fetchAllUnReadModel(identifier: "Message", ownid: AccountManager.shared.id()) as! [Message]
        let cell = currentInfoTableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! MyTableViewCell
        if array.count>0 {
            cell.newLabel.text = "\(array.count)"
        }else{
            cell.newLabel.text = ""
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}
extension MyViewController: UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
            return cell!
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell") as! MyTableViewCell
        cell.iconImageView.image = UIImage(named: iconDataSet[indexPath.row])
        cell.nameLabel.text = titleDataSet[indexPath.row]
        switch indexPath.row {
        case 0:
            cell.newLabel.isHidden = false
            //如果有未读消息
            if AccountManager.shared.isOnline() {
                let array = NSManagedObject.fetchAllUnReadModel(identifier: "Message", ownid: AccountManager.shared.id()) as! [Message]
                if array.count>0 {
                    cell.newLabel.text = "\(array.count)"
                }else{
                    cell.newLabel.text = ""
                }
            }else{
                cell.newLabel.text = ""
            }
        case 3:
            cell.newLabel.isHidden = false
            //如果家长未绑定孩子
            if AccountManager.shared.isOnline() {
                if AccountManager.shared.rawUserInfo!.contentData()["studentClass"].arrayValue.count == 0 {
                    cell.newLabel.text = "未绑定"
                }else{
                    cell.newLabel.text = ""
                }
            }else{
                cell.newLabel.text = ""
            }
        default:
            cell.newLabel.isHidden = true
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleDataSet.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.row {
        case 5,6,7:
            return 44
        case 0,1,2,3:
            if !AccountManager.shared.isOnline() {
                return 0
            }
            if AccountManager.shared.isOnline() && AccountManager.shared.name()=="葛建军" && (indexPath.row == 1 || indexPath.row == 2){//隐藏支付相关功能
                return 0
            }else{
                return 44
            }
        default:
            return 16
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 0://消息
            if AccountManager.shared.isOnline() {
                let vc = Story.instantiateViewControllerWithIdentifier("MessageViewController", storyName: "My") as! MessageViewController
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                appDelegate.window!.makeToast("请先登录", duration: 1, position: CSToastPositionCenter)
            }
        case 1://订购详情
            if AccountManager.shared.isOnline() {
                let vc = Story.instantiateViewControllerWithIdentifier("OrderDetailViewController", storyName: "My") as! OrderDetailViewController
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                appDelegate.window!.makeToast("请先登录", duration: 1, position: CSToastPositionCenter)
            }
        case 2://家校通订购
            if AccountManager.shared.isOnline() {
                let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController
                vcs.borderline = true
                vcs.webURL = "\(HTTPServer.HOSTWAP!)/ParentOrderCenter.aspx?userid=\(AccountManager.shared.id())"
                self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil)
            }else{
                appDelegate.window!.makeToast("请先登录", duration: 1, position: CSToastPositionCenter)
            }
        case 3://我的孩子
            if AccountManager.shared.isOnline() {
                let vc = Story.instantiateViewControllerWithIdentifier("MyChildrenViewController", storyName: "My") as! MyChildrenViewController
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                appDelegate.window!.makeToast("请先登录", duration: 1, position: CSToastPositionCenter)
            }
        case 5://意见与反馈
            let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController
            vcs.webURL = HTTPServer.HOSTWAP+"/FeedBack.aspx?userid=\(AccountManager.shared.userid)"
            self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil)
        case 6://清除缓存
            clearCache()
        case 7://关于
            let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController
            vcs.webURL = HTTPServer.HOSTWAP+"/About.html"
            self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil)
        default:
            break
        }
    }
    //MARK: - 清除缓存
    func clearCache(){
        // 取出cache文件夹路径
        let cachePath = NSSearchPathForDirectoriesInDomains(Foundation.FileManager.SearchPathDirectory.cachesDirectory, Foundation.FileManager.SearchPathDomainMask.userDomainMask, true).first
        // 打印路径,需要测试的可以往这个路径下放东西
//        print(cachePath)
        // 取出文件夹下所有文件数组
        let files = Foundation.FileManager.default.subpaths(atPath: cachePath!)
        // 用于统计文件夹内所有文件大小
        var big = Int();
        
        
        // 快速枚举取出所有文件名
        for p in files!{
            // 把文件名拼接到路径中
            let path = cachePath!.appendingFormat("/\(p)")
            // 取出文件属性
            let floder = try! Foundation.FileManager.default.attributesOfItem(atPath: path)
            // 用元组取出文件大小属性
            for (abc,bcd) in floder {
                // 只去出文件大小进行拼接
                if abc == FileAttributeKey.size{
                    big += (bcd as AnyObject).intValue
                }
            }
        }
        
        // 提示框
        let message = "\(big/(1024*1024))M缓存"
        let alert = UIAlertController(title: "清除缓存", message: message, preferredStyle: UIAlertControllerStyle.alert)
        
        let alertConfirm = UIAlertAction(title: "确定", style: UIAlertActionStyle.default) { (alertConfirm) -> Void in
            // 点击确定时开始删除
            for p in files!{
                // 拼接路径
                let path = cachePath!.appendingFormat("/\(p)")
                // 判断是否可以删除
                if(Foundation.FileManager.default.fileExists(atPath: path)){
                    if path.contains("/Caches/Snapshots") {
                        return
                    }
                    // 删除
                    do {
                        try Foundation.FileManager.default.removeItem(atPath: path)
                    }
                    catch {
                        fatalError("不能删除:\(error)")
                    }
                }
            }
        }
        alert.addAction(alertConfirm)
        let cancle = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (cancle) -> Void in
            
        }
        alert.addAction(cancle)
        // 提示框弹出
        present(alert, animated: true) { () -> Void in
            
        }
    }
}