//
//  String-Extension.swift
//  BaiSiSMApp
//
//  Created by davidhuang on 2022/10/12.
//  Copyright © 2022 www.davidhuang.com. All rights reserved.
//

import UIKit
extension String {
    /// JSONString转换为字典
    func toDictionary() -> Dictionary<String, Any>? {
        guard let jsonData:Data = data(using: .utf8) else { return nil }
        if let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
            if let temp = dict as? Dictionary<String, Any> {
                return temp
            }
        }
        return nil
    }

    /// JSONString转换为数组
    func toArray() -> Array<Any>? {
        guard let jsonData:Data = data(using: .utf8) else { return nil }
        if let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
            if let temp = array as? Array<Any> {
                return temp
            }
        }
        return nil
    }
}

extension String {
    
    // MARK: - 拨打电话
    func makePhone() {
        let phone = "telprompt://" + self
        if UIApplication.shared.canOpenURL(URL(string: phone)!) == true {
            UIApplication.shared.open(URL(string: phone)!, options: [:], completionHandler: nil)
        }
    }
    
    
    // MARK: - 判断是否为手机号码
    func isMobile() -> Bool {
        let reg = "^1[3456789]\\d{9}$"
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",reg)
        return regextestmobile.evaluate(with: self);
    }
    
    // MARK: - 判断密码是否合法
    //密码至少包含一个数字，一个字母，一个特殊字符
    func isPwdLegal() -> Bool {
        let reg = "^(?=.*)(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[-~!@#$%^&*:;,.=?$\\x22]).{8,20}$"
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",reg)
        return regextestmobile.evaluate(with: self);
    }
    
    // MARK: - 是否包含字符
    func isIncludeChinese() -> Bool {
        for char in self {
            if ("\u{4E00}" <= char  && char <= "\u{9FA5}") {
                return true
            }
        }
        return false
    }
    
    
    func phoneNumberForUI() -> String {
        let phone = self.replacingOccurrences(of: " ", with: "")
        if phone.count == 11 {
            let st1 = phone.slicing(from: 0, length: 3)
            let st2 = phone.slicing(from:7,length: 4)
            return st1! + "****" + st2!
        }
        return self
    }
    
    
    
    var unicodeDescription: String {
        return self.stringByReplaceUnicode
    }
    
    var stringByReplaceUnicode: String {
        let jsonDict = try? JSONSerialization.jsonObject(
            with: self.data(using: String.Encoding.utf8, allowLossyConversion: true)!,
            options: JSONSerialization.ReadingOptions.mutableLeaves)
        
        let jsonData = try? JSONSerialization.data(withJSONObject: jsonDict as Any, options: .prettyPrinted)
        let string_r = String(data: jsonData!, encoding: String.Encoding.utf8)
        return string_r ?? self
    }
    
    //时间戳转Date
    func stringConvertDate(dateFormat:String="yyyy-MM-dd HH:mm:ss") -> Date {
        let timeZone = TimeZone.init(identifier: "UTC") //这是重点
        let dateFormatter = DateFormatter.init()
        dateFormatter.timeZone = timeZone
        dateFormatter.dateFormat = dateFormat
        let date = dateFormatter.date(from: self)
        return date!
    }
    
    //时间戳转Date
    func convertDate(dateFormat:String="yyyy-MM-dd HH:mm:ss") -> Date {
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = dateFormat
        let date = dateFormatter.date(from: self) ?? Date()
        return date
    }
    
    //时间戳转 DateString
    func timeStampToString()->String {
        guard let timeStamp = self.cgFloat() else {
            return "--"
        }
        
        //时间戳为毫秒级要 ／ 1000， 秒就不用除1000，参数带没带000
        let timeSta:TimeInterval = TimeInterval(timeStamp)
        let date = NSDate(timeIntervalSince1970: timeSta)
        let dateformatter = DateFormatter()
        dateformatter.dateFormat="yyyy-MM-dd HH:mm:ss"
        return dateformatter.string(from: date as Date)
    }
}

// MARK: - 计算文字的宽高
extension String {
    
    /// 计算文字的宽高
    ///
    /// - Parameters:
    ///   - font: 字体大小
    ///   - lineSpacing: 行高
    ///   - constraintRect: 大小范围
    /// - Returns: 宽高
    public func bs_sizeWithConstrained(_ font: UIFont,
                                       lineSpacing: CGFloat? = nil,
                                       constraintRect: CGSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) -> CGSize {
        var attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: font]
        if let lineSpacing = lineSpacing {
            //格式调整
            let style = NSMutableParagraphStyle()
            /**调行间距*/
            style.lineSpacing = lineSpacing
            style.alignment = .left
            attributes[.paragraphStyle] = style
        }
        let boundingBox = self.boundingRect(
            with: constraintRect,
            options: NSStringDrawingOptions.usesLineFragmentOrigin,
            attributes: attributes,
            context: nil)
        return boundingBox.size
    }
    
}

// MARK: - 正则获取http
extension String {
    
    //获取http链接字符串的参数
    public var urlParameters: [String: String] {
        guard let url = URL(string: self) else {
            return [:]
        }
        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
              let queryItems = components.queryItems else { return [:] }
        return queryItems.reduce(into: [String: String]()) { (result, item) in
            result[item.name] = item.value
        }
    }
    
    ///获取http链接字符串的range
    public func getHttpRangeOfString() -> [NSTextCheckingResult]? {
        let regulaStr = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"
        do {
            let regex = try NSRegularExpression(pattern: regulaStr, options: .caseInsensitive)
            let arrayOfAllMatches = regex.matches(in: self, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, self.count))
            return arrayOfAllMatches
        } catch {
            return nil
        }
    }
    
}

/// 打印
///
/// - Parameters:
///   - message: 打印内容
///   - file: 所在文件
///   - method: 所在方法
///   - line: 所在行
public func printLog<T>(_ message: T, file: String = #file, method: String = #function, line: Int = #line) {
    print("\n[文件]:\((file as NSString).lastPathComponent) [所在行]:\(line),[方法名称]:\(method),[具体信息]:\(message)")
}
