//
//  BaseConfigFounction.swift
//  MobilePortal
//
//  Created by xiejiangbo on 2019/9/11.
//  Copyright © 2019 yin chen. All rights reserved.
//

import UIKit

/**
 从tableView缓存中取出对应类型的Cell
 如果缓存中没有，则重新创建一个
 
 - parameter tableView: tableView
 - parameter cell:      要返回的Cell类型
 - parameter indexPath: 位置
 
 - returns: 传入Cell类型的 实例对象
 */
func getCell<T: UITableViewCell>(_ tableView:UITableView ,cell: T.Type ,indexPath:IndexPath) -> T {
    return tableView.dequeueReusableCell(withIdentifier: "\(cell)", for: indexPath) as! T ;
}

func getCollectionViewCell<T: UICollectionViewCell>(_ collectionView:UICollectionView ,cell: T.Type ,indexPath:IndexPath) -> T {
    
    return collectionView.dequeueReusableCell(withReuseIdentifier: "\(cell)", for: indexPath) as! T ;
}

func registerCollectinViewCell<T: UICollectionViewCell>(_ collectionView:UICollectionView,cell:T.Type){
    collectionView .register(UINib.init(nibName: "\(cell)", bundle: nil), forCellWithReuseIdentifier: "\(cell)")
}

func registerCell<T: UITableViewCell>(_ tableView:UITableView,cell:T.Type){
    tableView .register(UINib.init(nibName: "\(cell)", bundle: nil), forCellReuseIdentifier: "\(cell)")
}

func swiftClassFromString(_ className: String) -> AnyClass! {
    //method1
    //方法 NSClassFromString 在Swift中已经不起作用了no effect，需要适当更改
    //let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName")
    if  let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") {
        let  aaa:String = appName as! String
        let classStringName = "_TtC\(aaa.utf16.count)\(aaa)\(className.count)\(className)"
        
        
        //let classStringName = "_TtC\(appName?.characters.count))\(appName!)\(className.characters.count))\(className)"
        let  cls: AnyClass? = NSClassFromString(classStringName)
        assert(cls != nil, "class not found,please check className")
        return cls
        
    }
    return nil;
}
//隐藏多余线
public func setExtraCellLineHidden(tableView:UITableView){
    let view:UIView=UIView.init()
    view.backgroundColor=UIColor.clear
    tableView.tableFooterView=view
    tableView.tableHeaderView=view
}
//MARK: - 获取字符长度
public func getTextRectSize(text:NSString,font:UIFont,size:CGSize) -> CGRect {
    let attributes = [NSAttributedStringKey.font: font]
    let option = NSStringDrawingOptions.usesLineFragmentOrigin
    let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
    return rect;
}
public func getTextHeigh(textStr:String,font:UIFont,width:CGFloat) -> CGFloat {
    let normalText: NSString = textStr as NSString
    let size = CGSize(width: width, height: 1000)
    let stringSize =  normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying) as? [NSAttributedStringKey : Any], context: nil).size
    return stringSize.height
}

public func getTexWidth(textStr:String,font:UIFont,height:CGFloat) -> CGFloat {
    let normalText: NSString = textStr as NSString
    let size = CGSize(width: 1000, height: height)
    let dic = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying as NSCopying)
    let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any], context:nil).size
    return stringSize.width
}
//public func loadString(resId:String, tableId:String?)->String{
//    let str=(FGLanguageTool.sharedInstance() as AnyObject).getStringForKey(resId, withTable: tableId)
//
//    return str!
//}
public func md5(strs:String) ->String!{
    let str = strs.cString(using: String.Encoding.utf8)
    let strLen = CUnsignedInt(strs.lengthOfBytes(using: String.Encoding.utf8))
    let digestLen = Int(CC_MD5_DIGEST_LENGTH)
    let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
    CC_MD5(str!, strLen, result)
    let hash = NSMutableString()
    for i in 0 ..< digestLen {
        hash.appendFormat("%02x", result[i])
    }
//    result.deinitialize()
    free(result)
    return String(format: hash as String)
}
public func judgmentStrNil(str:String?) -> String{
    if str == nil {
        return ""
    }
    return str!
}
//字典转Data
public func jsonToData(jsonDic:Dictionary<String, Any>) -> Data? {
    if (!JSONSerialization.isValidJSONObject(jsonDic)) {
        print("is not a valid json object")
        return nil
    }
    //利用自带的json库转换成Data
    //如果设置options为JSONSerialization.WritingOptions.prettyPrinted，则打印格式更好阅读
    let data = try? JSONSerialization.data(withJSONObject: jsonDic, options: [])
    //Data转换成String打印输出
    let str = String(data:data!, encoding: String.Encoding.utf8)
    //输出json字符串
    print("Json Str:\(str!)")
    return data
}
/// 计算时间间隔
public func dateInterval(startTime:String) -> Int{
    let dateformatter = DateFormatter()
    dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"// 自定义时间格式
    let endTime = newDateStr()
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    guard let date1 = dateFormatter.date(from: startTime),
        let date2 = dateFormatter.date(from: endTime) else {
            return -1
    }
    let components = NSCalendar.current.dateComponents([.second], from: date1, to: date2)
    //如果需要返回月份间隔，分钟间隔等等，只需要在dateComponents第一个参数后面加上相应的参数即可，示例如下：
    //    let components = NSCalendar.current.dateComponents([.month,.day,.hour,.minute], from: date1, to: date2)
    //        print(components.month!,components.day!,components.hour!,components.minute!)
    return components.second!
}
/// 获取当前时间字符串
public func newDateStr() ->String {
//    let dateformatter = DateFormatter()
//    dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"// 自定义时间格式
//    guard let date:String = dateformatter.string(from: Date()) else {
//        return ""
//    }
//    return date
    //获取当前时间
    let  now =  NSDate ()
    //当前时间的时间戳
    let  timeInterval: TimeInterval  = now.timeIntervalSince1970
    let  timeStamp =  Int (timeInterval)
    //转换为时间
    let  timeInt: TimeInterval  =  TimeInterval (timeStamp)
    let  date =  NSDate (timeIntervalSince1970: timeInt)
    let dateformatter = DateFormatter()
    dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"// 自定义时间格式
    let dateStr:String = dateformatter.string(from: date as Date)
    if dateStr == nil {
        return ""
    }
//    guard let dateStr:String? = dateformatter.string(from: date as Date) else {
//        return ""
//    }
    return dateStr
}

/// 是否退出单点登录
public func isSingOutAction() ->Bool {
//    print(AccountInfo.sharedInstance().singlePoint_startTime!)
//    if dateInterval(startTime: judgmentStrNil(str: AccountInfo.sharedInstance().singlePoint_startTime)) < 20*24*60 {
//        return true
//    }
    
    return false
}
/// 数字判断是否大于 99
public func numBigData(numStr: String?) -> String {
    var numBerStr = numStr!.replacingOccurrences(of:" ", with: "")
    if (numBerStr.contains("+")) {
        numBerStr = numBerStr.replacingOccurrences(of:"+", with: "")
    }
    if !isPurnInt(string: numBerStr) { return "" }
    if Int(numBerStr)! >= 99 { return "99+" }
    return numBerStr
}
///判断输入的字符串是否为数字，不含其它字符
func isPurnInt(string: String) -> Bool {
    let scan: Scanner = Scanner(string: string)
    var val:Int = 0
    return scan.scanInt(&val) && scan.isAtEnd
}
// MARK: 字典转字符串
public func dicValueString(_ dic:[String : Any]) -> String?{
    let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
    let str = String(data: data!, encoding: String.Encoding.utf8)
    return str
}
// MARK: 字符串转字典
public func stringValueDic(_ str: String) -> [String : Any]?{
    let data = str.data(using: String.Encoding.utf8)
    if let dict = try? JSONSerialization.jsonObject(with: data!,
                                                    options: .mutableContainers) as? [String : Any] {
        return dict
    }
    return nil
}
//extension String{
//    func md5() ->String!{
//        let str = self.cString(using: String.Encoding.utf8)
//        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
//        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
//        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
//        CC_MD5(str!, strLen, result)
//        let hash = NSMutableString()
//        for i in 0 ..< digestLen {
//            hash.appendFormat("%02x", result[i])
//        }
//        result.deinitialize()
//        return String(format: hash as String)
//    }
//}
///全局函数 T是泛型 传入不同的参数
//public func CCLog<T>(_ message:T,file:String = #file,funcName:String = #function,lineNum:Int = #line){
//    #if DEBUG
//    let file = (file as NSString).lastPathComponent;
//    // 文件名：行数---要打印的信息
//    print("\(file):(\(lineNum))--\(message)");
//    #endif
//}
