//
//  Double+Extension.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/26.
//

import Foundation


extension Double {
    var toDisplay: String {
        let formatter = NumberFormatter()
        formatter.maximumFractionDigits = 2
        return formatter.string(from: self as NSNumber) ?? "\(self)"
    }
    
    var currencyDisplay: String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.usesGroupingSeparator = false
        formatter.maximumFractionDigits = 2
        formatter.minimumFractionDigits = 0
        return formatter.string(from: self as NSNumber) ?? "\(self)"
    }
    
    var cashDisplay: String {
        let formatter = NumberFormatter()
        formatter.locale = Locale(identifier: "id_ID")
        formatter.numberStyle = .decimal
        formatter.usesGroupingSeparator = true
        formatter.maximumFractionDigits = 2
        formatter.minimumFractionDigits = 0
        return formatter.string(from: self as NSNumber) ?? "\(self)"
    }
    
    var durationDisplay: String {
        "\(toDuration)“"
    }
    
    var toDuration: Int {
        Int(rounded())
    }
    
    var timeCountDisplay: String {
        toDuration.timeCountDisplay
    }
    
    func formattedAsShortNumber(fractionDigits: Int = 1) -> String {
        let absNum = abs(self)
        
        // 定义量级：(基数, 单位)，按中文/英文区分
        let units: [(Double, String)] = [
            (1e12, "T"),  // 万亿
            (1e9, "B"),   // 十亿
            (1e6, "M"),   // 百万
            (1e3, "K")    // 千
        ]
        
        // 遍历量级，找到匹配的单位
        for (threshold, unit) in units {
            if absNum >= threshold {
                let formattedNum = self / threshold
                // 格式化小数，去掉无意义的尾缀（如 5.0 → 5）
                let formatter = NumberFormatter()
                formatter.maximumFractionDigits = fractionDigits
                formatter.minimumFractionDigits = formattedNum.truncatingRemainder(dividingBy: 1) == 0 ? 0 : fractionDigits
                
                guard let str = formatter.string(from: NSNumber(value: formattedNum)) else {
                    return "\(Int(formattedNum))\(unit)"
                }
                return "\(str)\(unit)"
            }
        }
        
        // 小于1000，直接显示原数字（无单位）
        let formatter = NumberFormatter()
        formatter.maximumFractionDigits = fractionDigits
        formatter.minimumFractionDigits = 0
        return formatter.string(from: NSNumber(value: self)) ?? "\(Int(self))"
    }
}
