//
//  String+.swift
//  YTBase_Example
//
//  Created by YouT on 2020/9/16.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import Foundation
import CommonCrypto
import UIKit

public extension String {
    
    func intValue() -> Int {
        if self.isEmpty || self == "" {
            return 0
        }else{
            return NSString(string: self).integerValue
        }
    }
    
    func floatValue() -> CGFloat {
        if self.isEmpty {
            return 0.0
        }else{
            return CGFloat(NSString(string: self).floatValue)
        }
    }
    
    func doubleValue() -> Double {
        return number().doubleValue
    }
    
    func number() -> NSNumber {
        let format = NumberFormatter()
        return format.number(from: self) == nil ? 0 : format.number(from: self)!
    }
    
    func languageString() -> String {
       return NSLocalizedString(self, comment: self)
    }
    
    static func getFileNameWithCurDate(prefixStr: String = "") -> String {
        return prefixStr+Date().getDateStr()
    }
    
    static func getFileNameWithTimestamp(prefixStr: String = "") -> String {
        let intTime = Int(Date().timeIntervalSince1970)
        return prefixStr+"\(intTime)"
    }
    
    //获取拼音首字母（大写字母）
    func firstLetter() -> String {
        //转变成可变字符串
        let mutableString = NSMutableString.init(string: self)
        //将中文转换成带声调的拼音
        CFStringTransform(mutableString as CFMutableString, nil, kCFStringTransformToLatin, false)
        //去掉声调
        let pinyinString = mutableString.folding(options:          String.CompareOptions.diacriticInsensitive, locale:   NSLocale.current)
        //将拼音首字母换成大写
        let strPinYin = pinyinString.uppercased()
        //截取大写首字母
        guard let firstString = strPinYin.first else { return "#" }
        //判断首字母是否为大写
        let regexA = "^[A-Z]$"
        let predA = NSPredicate.init(format: "SELF MATCHES %@", regexA)
        let newFirstStr = String(firstString)
        return predA.evaluate(with: newFirstStr) ? newFirstStr : "#"
    }
    
    // MD5
    var md5: String
    {
        let ccharArray = self.cString(using: String.Encoding.utf8)
        var uint8Array = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        CC_MD5(ccharArray, CC_LONG(ccharArray!.count - 1), &uint8Array)
        return uint8Array.reduce("") { $0 + String(format: "%02x", $1)
        }
    }
    
    //  获取宽度
    func getLabelWidth(h:CGFloat,f:UIFont) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: 2000, height: h), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : f], context: nil)
        return rect.width
    }
    
    //  获取高度
    func getLabelHeight(w:CGFloat,f:UIFont) -> CGFloat {
        let rect = NSString(string: self).boundingRect(with: CGSize(width: w, height: 300), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : f], context: nil)
        return rect.height
    }
    
    func getAttriFromHtmlString() -> NSMutableAttributedString {
         let attStr = try? NSMutableAttributedString.init(data: self.data(using: String.Encoding.utf8)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
         return attStr ?? NSMutableAttributedString()
      }
    
    
    // 计算高度与长度的类函数
    func getTextRectSize(_ font:UIFont,size:CGSize) -> CGRect {
         let attributes = [NSAttributedString.Key.font: font]
         let option = NSStringDrawingOptions.usesLineFragmentOrigin
         let rect = NSString(string: self).boundingRect(with: size, options: option,
                      attributes: attributes, context: nil)
         return rect;
    }
    
    //textView_aotoHeight
    // ex: sizeofString(font: UIFont.systemFont(ofSize: 13), maxSize: CGSize(width: screenW-Ratio(x: 136), height: 1000))
    func sizeofString(_ font: UIFont?, maxSize: CGSize) -> CGSize {
        return self.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font as Any], context: nil).size
        }
    
    //做二维码
    func generateQRCode() -> UIImage? {
        let data = self.data(using: String.Encoding.ascii)
        guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
        filter.setValue(data, forKey: "inputMessage")
        
        let transform = CGAffineTransform(scaleX: 9, y: 9)
        guard let output = filter.outputImage?.transformed(by: transform) else { return nil }
        return UIImage(ciImage: output)
    }
    
    
   //Mark - 字段校验
    
    //手机号
    func isValidatePhoneNumber() -> Bool {
        let phoneNumber = self
        if phoneNumber.count != 11 {
            return false
        }
        let regextestall = NSPredicate(format: "SELF MATCHES %@", "^1[0-9]{10}")
        if regextestall.evaluate(with: phoneNumber) {
            return true
        } else {
            return false
        }
    }
    
    //是否数字
    func isValidateIsNumber() -> Bool {
        let targetStr = self
        if targetStr.isEmpty {
            return false
        }
        let scan: Scanner = Scanner(string: targetStr)
        var val:Int = 0
        return scan.scanInt(&val) && scan.isAtEnd
    }
    //是否字母
    func isValidateIsLetter() -> Bool {
        let targetStr = self
        let letterRegex = NSPredicate(format:"SELF MATCHES %@", "^[A-Za-z]*$")
        if letterRegex.evaluate(with: targetStr) {
            return true
        } else {
            return false
        }
    }
    
    //是否邮箱
    func isValidateEmail() -> Bool {
        let email = self
        if email.isEmpty {
            return false
        }
        do {
            let regex = try NSRegularExpression(pattern: "^[A-Za-z0-9._%+-]+@[A-Za-z0-9._%+-]+\\.[A-Za-z0-9._%+-]+$", options: .caseInsensitive)
            let numberOfMatches = regex.numberOfMatches(in: email, options: .reportProgress, range: NSRange(location: 0, length: email.count))
            if numberOfMatches != 0 {
                return true
            } else {
                return false
            }
        } catch {
            return false
        }
    }

}

extension String: YTBaseCompatible {}
public extension YTBase where Base == String  {
    var base64Str:String {
        guard let strData = self.base.data(using: String.Encoding.utf8) else { return "" }
        return strData.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
    }
    
}
