//
//  SetUpViewController.swift
//  MobilePortal
//
//  Created by caiyang on 2020/4/6.
//  Copyright © 2020 yin chen. All rights reserved.
//

import UIKit

class SetUpViewController: BaseViewController {
    lazy var myTableView: UITableView = {
        let myTableView = UITableView.init()
        if #available(iOS 11.0, *) {
            myTableView.contentInsetAdjustmentBehavior = .never
            myTableView.scrollIndicatorInsets = myTableView.contentInset
            myTableView.contentInset = UIEdgeInsetsMake(UIApplication.shared.statusBarFrame.size.height+44, 0, 0, 0)
        }else{
            myTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        registerCell(myTableView, cell: MineInfoTableViewCell.self)
        registerCell(myTableView, cell: NormalTableViewCell.self)
        registerCell(myTableView, cell: MineInfoHeadTableViewCell.self)
        registerCell(myTableView, cell: SignOutTableViewCell.self)
        //        myTableView.separatorStyle = .none
        myTableView.backgroundColor = UIColorFromRGB(rgbValue: 0xF4F9FD)
        setExtraCellLineHidden(tableView: myTableView)
        return myTableView
    }()
    var dataSource:NSMutableArray!
    var delegate:MineInfoViewControllerDelegate!
    override func viewDidLoad() {
        super.viewDidLoad()
        initTitleBar()
        self.view.backgroundColor = UIColorFromRGB(rgbValue: 0xF4F9FD)
        self.title = "设置"
        //addRightN()
        addInitTableView()
//        actionHttpGCD()
//        addHeaderFooter()
        //        addInitLoginButton()
        //        wr_setDefaultNavBarShadowImageHidden
        self.wr_setNavBarShadowImageHidden(false)
        // Do any additional setup after loading the view.
    }
    func addInitTableView() {
        self.view.addSubview(myTableView)
        myTableView.snp.makeConstraints { (make) in
            make.width.height.equalToSuperview()
            make.center.equalToSuperview()
        }
        self.dataSource = NSMutableArray()
        initDate()
        self.delegate = MineInfoViewControllerDelegate()
        self.delegate.dataSource = self.dataSource
        self.myTableView.delegate = self.delegate
        self.myTableView.dataSource = self.delegate
    }
    func initDate(){

        /// 夜间模式
//        self.getMineInfoTableViewCellModel(imageName: "email_image", title: "", name: "夜间模式", block: {
//
//        }, accessoryType: .none)
        /// 设置
        self.getMineInfoTableViewCellModel(imageName: "email_image", title: self.getCacheSize(), name: "缓存管理", block: {
            showAlert(title: "提示", message: "确定要清除缓存？", titleCancelBtn: "取消", titleSecondBtn: "确定", blockOtherBtn: {[weak self] in
                self?.clearCache()
            })
        }, accessoryType: .disclosureIndicator)
        /// 添加分割
        self.getNormalTableViewCellModel()
        
        self.getMineInfoTableViewCellModel(imageName: "email_image", title: judgmentStrNil(str: AccountInfo.sharedInstance().appUUID), name: "设备ID", block: {[weak self] in
            self?.copyId()
        }, accessoryType: .disclosureIndicator)
        
//        self.getMineInfoTableViewCellModel(imageName: "email_image", title: judgmentStrNil(str: AccountInfo.sharedInstance().juph_registrationID), name: "推送ID", block: {[weak self] in
//            self?.copyjuph_registrationID()
//        }, accessoryType: .disclosureIndicator)
        
//        self.getMineInfoTableViewCellModel(imageName: "email_image", title: judgmentStrNil(str: AccountInfo.sharedInstance().webViewUrl), name: "网页链接", block: {[weak self] in
//            self?.webViewUrl()
//        }, accessoryType: .disclosureIndicator)
        
        self.getMineInfoTableViewCellModel(imageName: "email_image", title: self.getVersionString(), name: "版本信息", block: {[weak self] in
//            self?.gotoWei()
            self?.webViewUrl()
        }, accessoryType: .disclosureIndicator)
        
    }
    /// 跳转小程序
    func gotoWei(){
        let launchMiniProgramReq = WXLaunchMiniProgramReq.object()
        launchMiniProgramReq.userName = "gh_d9c1c80f9bfa"
        launchMiniProgramReq.path = ""
        launchMiniProgramReq.miniProgramType = WXMiniProgramType.release
        WXApi.send(launchMiniProgramReq) { (bool) in
            
        }
    }
    /// 复制极光ID
    func copyjuph_registrationID(){
        let pasteboard = UIPasteboard.general
        pasteboard.string = AccountInfo.sharedInstance().juph_registrationID
        SMToastView.showMessage("内容已复制！")
    }
    /// 复制设备ID
    func copyId(){
        let pasteboard = UIPasteboard.general
        pasteboard.string = AccountInfo.sharedInstance().appUUID
        SMToastView.showMessage("内容已复制！")
//        self.gotoMessageVC()
    }
    /// 复制设备ID
    func webViewUrl(){
        let pasteboard = UIPasteboard.general
        pasteboard.string = AccountInfo.sharedInstance().webViewUrl
        SMToastView.showMessage("内容已复制！")
    }
    /// 获取版本号
    func getVersionString() -> String {
        let infoDictionary = Bundle.main.infoDictionary!
//        let appDisplayName = infoDictionary["CFBundleDisplayName"] //程序名称
        let majorVersion = infoDictionary["CFBundleShortVersionString"]//主程序版本号
//        let minorVersion = infoDictionary["CFBundleVersion"]//版本号（内部标示）
        let appVersion = majorVersion as! String
        return appVersion
    }
    ///获取APP缓存
    func getCacheSize()-> String {
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        //快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr! {
            
            // 把文件名拼接到路径中
            let path = cachePath! + ("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            // 用元组取出文件大小属性
            for (key, fileSize) in floder {
                // 累加文件大小
                if key == FileAttributeKey.size {
                    size += (fileSize as AnyObject).integerValue
                }
            }
        }
        
        let totalCache = Double(size) / 1024.00 / 1024.00
        return String(format: "%.2f M", totalCache)
    }
    func clearCache() {
//        showHintView()
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        // 遍历删除
        for file in fileArr! {
            let path = (cachePath! as NSString).appending("/\(file)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                    
                }
            }
        }
        self.dataSource = NSMutableArray()
        initDate()
        self.delegate = MineInfoViewControllerDelegate()
        self.delegate.dataSource = self.dataSource
        self.myTableView.delegate = self.delegate
        self.myTableView.dataSource = self.delegate
        self.myTableView.reloadData()
//        hidenHintView()
    }
    func getNormalTableViewCellModel() {
        let model = NormalTableViewCellModel()
        model.className = "NormalTableViewCell"
        self.dataSource.add(model)
        //return model
    }
    func getMineInfoTableViewCellModel(imageName:String,title:String,name:String,block:@escaping selectBlock,accessoryType:UITableViewCellAccessoryType){
        let model = MineInfoTableViewCellModel()
        model.className = "MineInfoTableViewCell"
        model.imageName = imageName
        model.titleStr = title
        model.nameStr = name
        model.block = block
        model.accessoryType = accessoryType
        self.dataSource.add(model)
    }
    func getSignOutTableViewCellModel(){
        let model = MineInfoTableViewCellModel()
        model.className = "SignOutTableViewCell"
        model.block = {
            
        }
        self.dataSource.add(model)
    }
    override func gotoMessageVC(){
        self.actionGotoMessageWeb(messageId: AccountInfo.sharedInstance().messageId!, isHomePushType: .YesIsHomePushType)
    }
}
