//
//  Int+Ext.swift
//  PQSpeed
//
//  Created by SanW on 2020/7/20.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import Foundation

public extension Int {
    /// 分数字格式化如413200->4,132.09

    /// 是否保留2位小数
    /// - Parameter isDecimal: <#isDecimal description#>
    /// - Returns: <#description#>
    func paraseDecimalFormatterValue(isDecimal: Bool = false) -> String? {
        let decimal = self % 100
        let nonDecimal = self / 100
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        if let title = formatter.string(from: NSNumber(value: nonDecimal)) {
            if isDecimal {
                return title + String(format: ".%02d", decimal)
            } else {
                return title
            }
        }
        return nil
    }

    /// 改变单位为万
    /// @param originUnit <#originUnit description#>
    func changeUnit() -> String {
        var unitStr: String = ""
        if self < 10000 {
            unitStr = "\(self)"
        } else if self <= 1_000_000 {
            let divisor = pow(10.0, Double(1))
            let decimal = ((Double(self) / 10000) * divisor).rounded() / divisor
            unitStr = "\(decimal)万"
        } else {
            unitStr = "\(self / 10000)万"
        }
        return unitStr
    }
}

// MARK: - Float64 double类型扩展

/// Float64 double类型扩展

public extension Float64 {
    /// 时长转化为分秒 62'52"
    /// - Returns: <#description#>
    func formatDurationToMS() -> String {
        let duration = lround(self)
        var text = ""
        let min = duration / 60
        let second = duration % 60
        if min > 0, second > 0 {
            text = "\(min)" + "\'" + "\(second)" + "\""
        } else if min > 0 {
            text = "\(min)" + "\'" + "0\""
        } else {
            text = "\(second)" + "\""
        }
        return text
    }

    /// 时长转化成时分秒 01:02:52
    /// - Parameter value: <#value description#>
    /// - Returns: <#description#>
    func formatDurationToHMS() -> String {
        var theTime = lround(self)
        var theTime1 = 0 // 分
        var theTime2 = 0 // 小时
        if theTime < 60 {
            if theTime < 10 {
                return "00:0\(theTime)"
            }
            return "00:\(theTime)"
        }
        theTime1 = theTime / 60
        theTime = theTime % 60
        if theTime1 > 60 {
            theTime2 = theTime1 / 60
            theTime1 = theTime1 % 60
        }
        var result = "\(theTime)"
        if theTime < 10 {
            result = "0" + result
        }
        if theTime1 > 0 {
            result = "\(theTime1):" + result
            if theTime1 < 10 {
                result = "0" + result
            }
        }
        if theTime2 > 0 {
            result = "\(theTime2):" + result
            if theTime2 < 10 {
                result = "0" + result
            }
        }
        return result
    }
}
