//
//  PDInfoViewController.swift
//  PrinterDemo
//
//  Created by ios on 2021/11/13.
//  Copyright © 2021 XiamenHY. All rights reserved.
//

import UIKit
import PrinterSDK
import SVProgressHUD
import CoreTelephony
import SystemConfiguration
import Network
import SystemConfiguration.CaptiveNetwork

class PDInfoViewController: PDBaseViewController {

    lazy var textView : UITextView = {
        let temp = UITextView.init()
        temp.text = ""
        temp.font = UIFont.systemFont(ofSize: 15)
        temp.textColor = UIColor.black
        temp.clipsToBounds = true
        temp.layer.cornerRadius = 10
        temp.layer.borderColor = UIColor.theme.cgColor
        temp.layer.borderWidth = 0.5
        return temp
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "设备状态信息".localized
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "复制", style: UIBarButtonItem.Style.plain, target: self, action: #selector(copyAllText))
        
        view.addSubview(textView)
        textView.snp.makeConstraints {
            $0.left.equalTo(15)
            $0.top.equalTo(20)
            $0.width.equalTo(kScreenWidth - 30)
            $0.bottom.equalTo(-kSafeAreaBottomHeight - 30)
        }
        
        // 开始读取设备状态信息
        readDeviceStatusInfo()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }

}

extension PDInfoViewController {
    
    @objc private func copyAllText() {
        let paste = UIPasteboard.general
        paste.string = textView.text
        SVProgressHUD.showSuccess(withStatus: "复制成功")
    }
    
    // MARK: - 设备状态信息读取
    private func readDeviceStatusInfo() {
        var statusInfo = ""
        let totalSteps = 8
        var currentStep = 0
        
        // 显示初始进度
        textView.text = "✅ 正在读取设备状态信息...\n"
        
        // 步骤1: 读取SIM卡状态
        readSIMStatus { [weak self] simInfo in
            currentStep += 1
            statusInfo += simInfo
            self?.updateProgress(currentStep: currentStep, totalSteps: totalSteps, statusInfo: statusInfo)
            
            // 步骤2: 读取WiFi状态
            self?.readWiFiStatus { wifiInfo in
                currentStep += 1
                statusInfo += wifiInfo
                self?.updateProgress(currentStep: currentStep, totalSteps: totalSteps, statusInfo: statusInfo)
                
                // 步骤3-6: 读取打印机WiFi配置信息
                self?.readPrinterWiFiConfig { printerWifiInfo in
                    currentStep += 3
                    statusInfo += printerWifiInfo
                    self?.updateProgress(currentStep: currentStep, totalSteps: totalSteps, statusInfo: statusInfo)
                    
                    // 步骤7-8: 读取4G RSSI信息
                    self?.read4GRSSI { rssi4GInfo in
                        currentStep += 2
                        statusInfo += rssi4GInfo
                        
                        self?.readMAC { mac in
                            currentStep += 1
                            statusInfo += mac
                            
                            self?.readSignalStrength { strength in
                                currentStep += 1
                                statusInfo += strength
                                statusInfo += "\n✅ 所有设备状态信息读取完成！"
                                self?.updateProgress(currentStep: currentStep, totalSteps: totalSteps, statusInfo: statusInfo)
                            }
                        }
                    }
                }
            }
        }
    }
    
    private func updateProgress(currentStep: Int, totalSteps: Int, statusInfo: String) {
        DispatchQueue.main.async { [weak self] in
            self?.textView.text = statusInfo
        }
    }
    
    // MARK: - SIM卡状态读取
    private func readSIMStatus(completion: @escaping (String) -> Void) {
        var simInfo = "\n===SIM卡信息===\n"
        
        if #available(iOS 12.0, *) {
            let telephonyInfo = CTTelephonyNetworkInfo()
            
            if let carriers = telephonyInfo.serviceSubscriberCellularProviders {
                if carriers.isEmpty {
                    simInfo += "SIM卡状态: 未检测到SIM卡\n"
                } else {
                    simInfo += "SIM卡状态: 已就绪\n"
                    
                    for (carrierId, carrier) in carriers {
                        simInfo += "运营商: \(carrier.carrierName ?? "未知")\n"
                        simInfo += "国家代码: \(carrier.isoCountryCode ?? "未知")\n"
                        simInfo += "移动国家代码: \(carrier.mobileCountryCode ?? "未知")\n"
                        simInfo += "移动网络代码: \(carrier.mobileNetworkCode ?? "未知")\n"
                    }
                }
            } else {
                simInfo += "SIM卡状态: 获取失败\n"
            }
        } else {
            simInfo += "SIM卡状态: 系统版本不支持\n"
        }
        
        completion(simInfo)
    }
    
    // MARK: - WiFi状态读取
    private func readWiFiStatus(completion: @escaping (String) -> Void) {
        var wifiInfo = "\n===WiFi信息===\n"
        
        // 检查WiFi是否启用
        if let wifiInterface = CNCopySupportedInterfaces() {
            let interfaces = wifiInterface as! [String]
            
            if interfaces.isEmpty {
                wifiInfo += "WiFi状态: 未启用\n"
            } else {
                wifiInfo += "WiFi状态: 已启用\n"
                
                // 获取当前WiFi信息
                if let interface = interfaces.first {
                    if let wifiInfoDict = CNCopyCurrentNetworkInfo(interface as CFString) {
                        let wifiData = wifiInfoDict as! [String: Any]
                        
                        if let ssid = wifiData["SSID"] as? String {
                            wifiInfo += "WiFi SSID: \(ssid)\n"
                        }
                        
                        if let bssid = wifiData["BSSID"] as? String {
                            wifiInfo += "BSSID: \(bssid)\n"
                        }
                    }
                }
                
                // 获取IP地址
                if let ipAddress = getWiFiIPAddress() {
                    wifiInfo += "IP地址: \(ipAddress)\n"
                }
                
//                // iOS系统限制：无法获取WiFi信号强度
//                wifiInfo += "信号强度: iOS系统限制，无法获取\n"
            }
        } else {
            wifiInfo += "WiFi信息获取失败\n"
        }
        
        completion(wifiInfo)
    }
    
    private func getWiFiIPAddress() -> String? {
        var address: String?
        var ifaddr: UnsafeMutablePointer<ifaddrs>?
        
        guard getifaddrs(&ifaddr) == 0 else { return nil }
        guard let firstAddr = ifaddr else { return nil }
        
        for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
            let interface = ifptr.pointee
            
            // 检查接口名称是否为WiFi
            let name = String(cString: interface.ifa_name)
            if name == "en0" {
                let addr = interface.ifa_addr.pointee
                if addr.sa_family == UInt8(AF_INET) {
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(interface.ifa_addr, socklen_t(addr.sa_len),
                               &hostname, socklen_t(hostname.count),
                               nil, socklen_t(0), NI_NUMERICHOST)
                    address = String(cString: hostname)
                }
            }
        }
        
        freeifaddrs(ifaddr)
        return address
    }
    
    // MARK: - 打印机WiFi配置信息读取
    private func readPrinterWiFiConfig(completion: @escaping (String) -> Void) {
        var printerWifiInfo = "\n===打印机WiFi配置信息===\n"
        
        guard let printer = PrinterManager.instance.accessory, printer.connected else {
            printerWifiInfo += "打印机未连接\n"
            completion(printerWifiInfo)
            return
        }
        
        // 获取WiFi工作模式
        printer.getWifiWorkMode { [weak self] (mode, error) in
            if let error = error {
                printerWifiInfo += "工作模式获取失败: \(error.localizedDescription)\n"
                completion(printerWifiInfo)
                return
            }
            
            let modeText = mode == 1 ? "AP模式" : mode == 2 ? "STA模式" : "未知模式(\(mode))"
            printerWifiInfo += "工作模式: \(modeText)\n"
            
            if mode == 1 {
                // AP模式：读取AP配置信息
                self?.readAPConfig(printer: printer) { apConfig in
                    printerWifiInfo += apConfig
                    self?.readWiFiRSSI(printer: printer) { rssi in
                        printerWifiInfo += rssi
                        completion(printerWifiInfo)
                    }
                }
            } else if mode == 2 {
                // STA模式：读取STA配置信息
                self?.readSTAConfig(printer: printer) { staConfig in
                    printerWifiInfo += staConfig
                    self?.readWiFiRSSI(printer: printer) { rssi in
                        printerWifiInfo += rssi
                        completion(printerWifiInfo)
                    }
                }
            } else {
                self?.readWiFiRSSI(printer: printer) { rssi in
                    printerWifiInfo += rssi
                    completion(printerWifiInfo)
                }
            }
        }
    }
    
    private func readAPConfig(printer: S1V1ProtocolPrinter, completion: @escaping (String) -> Void) {
        var apConfig = ""
        
        printer.getWifiKey(122, bytes: 64) { (ssid, error) in
            apConfig += "AP SSID: \(ssid ?? "获取失败")\n"
            
            printer.getWifiKey(123, bytes: 64) { (password, error) in
                apConfig += "AP 密码: \(password ?? "获取失败")\n"
                
                printer.getWifiIP(128) { (ip, error) in
                    apConfig += "AP IP地址: \(ip ?? "获取失败")\n"
                    
                    printer.getWifiIP(155) { (subnet, error) in
                        apConfig += "AP 子网掩码: \(subnet ?? "获取失败")\n"
                        completion(apConfig)
                    }
                }
            }
        }
    }
    
    private func readSTAConfig(printer: S1V1ProtocolPrinter, completion: @escaping (String) -> Void) {
        var staConfig = ""
        
        printer.getWifiKey(124, bytes: 64) { (ssid, error) in
            staConfig += "STA SSID: \(ssid ?? "获取失败")\n"
            
            printer.getWifiKey(125, bytes: 64) { (password, error) in
                staConfig += "STA 密码: \(password ?? "获取失败")\n"
                
                printer.getWifiIP(129) { (ip, error) in
                    staConfig += "STA IP地址: \(ip ?? "获取失败")\n"
                    
                    printer.getWifiIP(134) { (subnet, error) in
                        staConfig += "STA 子网掩码: \(subnet ?? "获取失败")\n"
                        completion(staConfig)
                    }
                }
            }
        }
    }
    
    private func readWiFiRSSI(printer: S1V1ProtocolPrinter, completion: @escaping (String) -> Void) {
        printer.getWifiRSSI { (rssi, error) in
            var rssiInfo = ""
            if let rssi = rssi, !rssi.isEmpty {
                rssiInfo += "WiFi \(rssi) dBm\n"
            } else {
                rssiInfo += "WiFi RSSI: 获取失败\n"
            }
            completion(rssiInfo)
        }
    }
    
    // MARK: - 4G RSSI信息读取
    private func read4GRSSI(completion: @escaping (String) -> Void) {
        var rssi4GInfo = "\n===4G信息===\n"
        
        guard let printer = PrinterManager.instance.accessory, printer.connected else {
            rssi4GInfo += "4G RSSI: 打印机未连接\n"
            completion(rssi4GInfo)
            return
        }
        
        // 使用PrinterSDK的getPrinter4GRSSI方法获取4G RSSI
        printer.getPrinter4GRSSI { (rssi, error) in
            if let error = error {
                rssi4GInfo += "4G RSSI: 获取失败 - \(error.localizedDescription)\n"
            } else if let rssi = rssi, !rssi.isEmpty {
                rssi4GInfo += "4G RSSI: \(rssi) dBm\n"
            } else {
                rssi4GInfo += "4G RSSI: 获取失败\n"
            }
            completion(rssi4GInfo)
        }
    }
    // MARK: - MAC信息读取
    private func readMAC(completion: @escaping (String) -> Void) {
        var macInfo = "\n===MAC信息===\n"
        
        guard let printer = PrinterManager.instance.accessory, printer.connected else {
            macInfo += "MAC: 打印机未连接\n"
            completion(macInfo)
            return
        }
        
        printer.getMAC(.bt) { (btMac, error) in
            macInfo += "蓝牙 MAC: \(btMac ?? "获取失败")\n"
            printer.getMAC(.wifi) { (wifiMac, error) in
                macInfo += "Wifi MAC: \(wifiMac ?? "获取失败")\n"
                completion(macInfo)
            }
        }
    }
    // MARK: - wifi信号强度
    private func readSignalStrength(completion: @escaping (String) -> Void) {
        var signalStrengthInfo = "\n===Wifi信号强度===\n"
        
        guard let printer = PrinterManager.instance.accessory, printer.connected else {
            signalStrengthInfo += "MAC: 打印机未连接\n"
            completion(signalStrengthInfo)
            return
        }
        
        printer.getWifiLink() { (strength, error) in
            signalStrengthInfo += "Wifi信号强度: \(strength)%\n"
            completion(signalStrengthInfo)
        }
    }
}
