
var _userdata = require("userdata.js");
var userData = _userdata.userData;
const fs = require("@system.fs");
var systemCtrl = require("systemCtrl.js");
var process = require("@system.process");
var handleSNDataBinFile = require("handleSNDataBinFile.js");
var file = require("file.js");
var that;
var systemInfoTimer = null;
var systemInfo = {};

function getSystemInfo() {
    return systemInfo;
}

// 统一设置颜色
const textValueKeys = [
    "crtsystemId1_TextValue1",
    // "crtsystemId1_TextValue2",
    "crtsystemId1_TextValue3",
    "crtsystemId1_TextValue4",
    "crtsystemId1_TextValue5",

    "crtsystemId2_TextValue1",
    // "crtsystemId2_TextValue2",
    "crtsystemId2_TextValue3",
    "crtsystemId2_TextValue4",
    "crtsystemId2_TextValue5",

    // "crtsystemId3_TextValue1",
    // "crtsystemId3_TextValue2",
    // "crtsystemId3_TextValue3",
    // "crtsystemId3_TextValue4",

    // "crtsystemId3_TextValue5"
];

// function setTextColorByValue(that, fullKey, value) {
//     const color = (value == "NG") ? "#ff0000" : "#00ff00";
//     const key = fullKey.replace(/^crt/, ""); // 去掉前缀 "crt"
//     that.$setTextColor(key, color);
// }




let checkedCount = 0;
let ngCount = 0;

function setTextColorByValue(that, fullKey, value) {
    // 1. 设置颜色
    const color = (value == "NG") ? "#ff0000" : "#00ff00";
    const key = fullKey.replace(/^crt/, "");
    that.$setTextColor(key, color);

    // 2. 更新计数
    checkedCount++;
    if (value == "NG") ngCount++;

    // 3. 等所有项都检测完再写全局变量
    //console.log("textValueKeys.length: " + textValueKeys.length + ", checkedCount: " + checkedCount + ", ngCount: " + ngCount)
    //console.log("factoryTestSystemCheck: " + that.factoryTestSystemCheck)

    if (checkedCount == textValueKeys.length) {
        that.factoryTestSystemCheck = (ngCount == 0) ? 1 : 2;
        // 重置计数器，方便下次调用
        checkedCount = 0;
        ngCount = 0;
    }
}


// 获取系统信息
function updateSystemInfo() {


    // var total = getTotalStorageInfo();

    // total.totalSizeMB

    // total.totalAvailableMB

    systemInfo.softwareVersion = userData.softwareVersion;
    systemInfo.hardwareVersion = userData.hardwareVersion;
    systemInfo.factorywareVersion = userData.factorywareVersion;

    if (process.platform == "win32") {

        systemInfo.cpuTemperature = "NG";
        systemInfo.cpuFrequency = "NG";
        systemInfo.storageInfo = {
            totalSizeMB: "NG",
            totalAvailableMB: "NG"
        }
        systemInfo.wifiMac = "NG";
        systemInfo.licenseRegistered = "NG";
        systemInfo.wifiIp = "NG";
        systemInfo.screenVendor = "";
        systemInfo.ddrFrequency = "NG";
        systemInfo.sn = userData.aboutSNValue || "NG";
    } else {

        systemInfo.cpuTemperature = getCPUTemperature();
        systemInfo.cpuFrequency = getCPUFrequency();
        systemInfo.storageInfo = getTotalStorageInfo();
        systemInfo.wifiMac = getWifiInfo("address");
        systemInfo.licenseRegistered = (checkLicense() == 1 ? "Pass" : "NG"); // 需根据实际实现
        systemInfo.wifiIp = getWifiInfo("ip_address"); //前提wifi要连接    
        systemInfo.screenVendor = getScreenVendor(); // 需根据实际实现
        systemInfo.ddrFrequency = getDDRFrequency();
        systemInfo.sn = handleSNDataBinFile.readStrFromBinFile() || "NG";
    }
    // systemInfo.sn = userData.aboutSNValue || "NG";
    // systemInfo.sn = userData.aboutInnerSNValue || "NG";
    systemInfo.tpVersion = userData.tpFirmwareVersion; // 示例值

    systemInfo.wifiModel = "AP62212"; // 示例值





    // that.crtsystemId1_TextHeader1: "SN码:",
    // that.crtsystemId1_TextHeader2: "固件版本号:",
    // that.crtsystemId1_TextHeader3: "硬件版本号:",
    // that.crtsystemId1_TextHeader4: "DSP固件版本:",
    // that.crtsystemId1_TextHeader5: "DSP算法版本:",
    that.crtsystemId1_TextValue1 = systemInfo.sn;
    that.crtsystemId1_TextValue2 = systemInfo.softwareVersion;
    that.crtsystemId1_TextValue3 = systemInfo.hardwareVersion;
    that.crtsystemId1_TextValue4 = systemInfo.tpVersion,
        that.crtsystemId1_TextValue5 = (systemInfo.ddrFrequency != "NG") ? systemInfo.ddrFrequency + "MHz" : systemInfo.ddrFrequency;

    // that.crtsystemId2_TextHeader1: "WiFi MAC:",
    // that.crtsystemId2_TextHeader2: "蓝牙MAC:",
    // that.crtsystemId2_TextHeader3: "语音license:",
    // that.crtsystemId2_TextHeader4: "CPU温度:",
    // that.crtsystemId2_TextHeader5: "存储空间:",
    that.crtsystemId2_TextValue1 = systemInfo.wifiMac;
    // that.crtsystemId2_TextValue2: "NG",
    that.crtsystemId2_TextValue3 = systemInfo.licenseRegistered;
    that.crtsystemId2_TextValue4 = (systemInfo.cpuTemperature != "NG") ? systemInfo.cpuTemperature + "℃" : systemInfo.cpuTemperature;
    that.crtsystemId2_TextValue5 = (systemInfo.storageInfo.totalAvailableMB != "NG" && systemInfo.storageInfo.totalSizeMB != "NG") ? systemInfo.storageInfo.totalAvailableMB + "MB" + "/" + systemInfo.storageInfo.totalSizeMB + "MB" : "NG";

    // that.crtsystemId3_TextHeader1: "产测版本:",
    // that.crtsystemId3_TextHeader2: "屏模组信息:",
    // that.crtsystemId3_TextHeader3: "CPU频率:",
    // that.crtsystemId3_TextHeader4: "IP地址:",
    // that.crtsystemId3_TextHeader5: "IP地址:",
    that.crtsystemId3_TextValue1 = systemInfo.factorywareVersion;
    that.crtsystemId3_TextValue2 = systemInfo.screenVendor;
    that.crtsystemId3_TextValue3 = (systemInfo.cpuFrequency != "NG") ? systemInfo.cpuFrequency + "MHz" : systemInfo.cpuFrequency;
    that.crtsystemId3_TextValue4 = systemInfo.wifiIp;
    // that.crtsystemId3_TextValue5: "NG",

    softVersionEvent();
    textValueKeys.forEach(key => {
        const value = that[key];
        if (value !== undefined) {
            setTextColorByValue(that, key, value);
        }
    });


    //     //console.log(`
    // 系统信息已更新：
    // 固件版本: ${systemInfo.softwareVersion}
    // 硬件版本: ${systemInfo.hardwareVersion}
    // 产测版本: ${systemInfo.factorywareVersion}
    // CPU温度: ${systemInfo.cpuTemperature}  ℃
    // CPU频率: ${systemInfo.cpuFrequency}  MHz
    // 存储总容量: ${systemInfo.storageInfo.totalSizeMB} MB
    // 存储剩余空间: ${systemInfo.storageInfo.totalAvailableMB} MB
    // WiFi MAC地址: ${systemInfo.wifiMac}
    // SN序列号: ${systemInfo.sn}
    // TP固件版本: ${systemInfo.tpVersion}
    // 屏厂家名: ${systemInfo.screenVendor}
    // WiFi型号: ${systemInfo.wifiModel}
    // License注册状态: ${systemInfo.licenseRegistered}
    // `);
}
function softVersionEvent() {
    var color = "#ff0000";
    var state = checkSoftVersion();
    if (!state) {
        ngCount++;
        color = "#ff0000";
    }
    else {
        color = "#00ff00";
    }

    //console.log("color==" + color)
    that.$setTextColor("systemId1_TextValue2", color);
}
// 启动定时器
function startSystemInfoTimer(obj) {
    that = obj;
    if (systemInfoTimer != null) {
        clearInterval(systemInfoTimer);
    }
    updateSystemInfo();
    systemInfoTimer = setInterval(() => {
        updateSystemInfo();
    }, 5000);
    //console.log("系统信息定时器已启动(5000ms)");
}

// 停止定时器
function stopSystemInfoTimer() {
    if (systemInfoTimer) {
        clearInterval(systemInfoTimer);
        systemInfoTimer = null;
        //console.log("系统信息定时器已停止");
    } else {
        //console.log("定时器未启动");
    }
}
function compareVersionStrings(str1, str2) {
    // 从字符串中提取数字部分
    var num1 = str1.substring(1).split('.').map(Number);
    var num2 = str2.substring(1).split('.').map(Number);
    //console.log("num1=" + num1);
    //console.log("num2=" + num2);

    for (let i = 0; i < num1.length; i++) {
        if (num1[i] > num2[i]) {
            return 1;
        } else if (num1[i] < num2[i]) {
            return -1;
        }
    }
    return 0;
}
function checkSoftVersion() {

    var obj = file.readBasicPath("../../../../../mnt/exUDISK/swuUpdate/swuVersion.json", "json");
    if (obj == undefined) {
        //console.log("swuVersion.json is not exist!");
        return 1;
    }
    //console.log("obj.version=" + obj.version);
    var comparativeResult = compareVersionStrings(obj.version, systemInfo.softwareVersion);
    //console.log("comparativeResult=" + comparativeResult);
    if (comparativeResult == 1) {

        return 0;//表示U盘里的baner版本号比当前版本号大
    }
    else {
        return 1;
    }
}



function getWifiInfo(options) {

    // wpa_state=SCANNING
    // p2p_device_address=c2:f5:35:81:41:8e
    // address=c0:f5:35:81:41:8e
    // uuid=e1a83a1d-97b6-52eb-93f8-d323a8c9badf
    var switchOption = options + "="
    systemCtrl.executeSystemCommand("wpa_cli -p /tmp/wpa_supplicant/sockets -i wlan0 status > /tmp/wifi_status.txt");
    const statusContent = fs.read("/tmp/wifi_status.txt", "r");
    if (statusContent) {
        const statusLines = statusContent.split('\n');
        for (let i = 0; i < statusLines.length; i++) {
            const line = statusLines[i].trim();
            if (line.startsWith(switchOption)) {
                const state = line.split('=')[1];
                // if (state == "COMPLETED") {
                //     isConnected = true;
                //     break;
                // }
                return state;
            }
        }
    }
    return "NG";
}
function getTotalStorageInfo() {
    // 执行 df 命令获取所有挂载点的存储信息
    systemCtrl.executeSystemCommand("df -h > /tmp/storage_status.txt");
    const storageContent = fs.read("/tmp/storage_status.txt", "r");

    let totalSizeMB = 0;
    let totalAvailableMB = 0;

    // 定义需要统计的真实 Flash 挂载点
    const validMountPoints = [
        "/",
        "/dev",
        // "/tmp",
        "/mnt/userdataA",
        "/mnt/userdataB",
        "/mnt/advconfigA",
        "/mnt/advconfigB",
        "/mnt/app",
        "/etc/resolv.conf",
        "/tmp/private",
        "/mnt/UDISK",
        "/mnt/extsd"
    ];

    if (storageContent) {
        const lines = storageContent.split('\n');

        for (let i = 1; i < lines.length; i++) { // 跳过表头
            const line = lines[i].trim();
            if (line == "") continue;

            const parts = line.split(/\s+/);
            if (parts.length < 6) continue;

            const mountPoint = parts[5];

            // 只统计真实 Flash 挂载点
            if (!validMountPoints.includes(mountPoint)) continue;

            const size = parts[1];
            const available = parts[3];

            // 转换为 MB 并累加
            totalSizeMB += convertToMB(size);
            totalAvailableMB += convertToMB(available);
        }

        //  //console.log(`总容量: ${totalSizeMB.toFixed(2)} MB`);
        //  //console.log(`总剩余空间: ${totalAvailableMB.toFixed(2)} MB`);

        return {
            totalSizeMB: totalSizeMB.toFixed(2),
            totalAvailableMB: totalAvailableMB.toFixed(2)
        };
    } else {
        //  //console.log("无法读取存储信息");
        return {
            totalSizeMB: "NG",
            totalAvailableMB: "NG"
        };
    }
}

// 辅助函数：将 df 命令的输出单位转换为 MB
function convertToMB(value) {
    const unit = value.slice(-1); // 获取单位（如 G、M、K）
    const number = parseFloat(value.slice(0, -1)); // 获取数字部分

    switch (unit) {
        case 'G':
            return number * 1024;
        case 'M':
            return number;
        case 'K':
            return number / 1024;
        default:
            return 0;
    }
}
function getCPUTemperature() {
    systemCtrl.executeSystemCommand("cat /sys/class/thermal/thermal_zone0/temp > /tmp/cpu_temp.txt");
    const tempStr = fs.read("/tmp/cpu_temp.txt", "r");
    if (tempStr) {
        const tempC = parseInt(tempStr.trim()) / 1000;
        //  //console.log(`CPU温度: ${tempC.toFixed(2)} ℃`);
        return tempC.toFixed(2);
    } else {
        //   //console.log("无法读取CPU温度");
        return "NG";
    }
}
function getDDRFrequency() {
    // 1. 把 clk_summary 里 dram-clk 那一行抓出来存临时文件
    systemCtrl.executeSystemCommand(
        "awk '/dram-clk/ {print $5}' /sys/kernel/debug/clk/clk_summary > /tmp/ddr_freq.txt");

    // 2. 读文件
    const freqHzStr = fs.read("/tmp/ddr_freq.txt", "r");
    if (freqHzStr) {
        const freqHz = parseInt(freqHzStr.trim(), 10);   // 单位 Hz
        const freqMHz = (freqHz / 1e6).toFixed(0);       // 转 MHz，保留整数
        // console.log(`DDR频率: ${freqMHz} MHz`);
        return freqMHz;
    } else {
        // console.log("无法读取DDR频率");
        return "NG";
    }
}




function getCPUFrequency() {
    systemCtrl.executeSystemCommand("cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq > /tmp/cpu_freq.txt");
    const freqStr = fs.read("/tmp/cpu_freq.txt", "r");
    if (freqStr) {
        const freqMHz = parseInt(freqStr.trim()) / 1000;
        // //console.log(`CPU频率: ${freqMHz.toFixed(0)} MHz`);
        return freqMHz.toFixed(0);
    } else {
        // //console.log("无法读取CPU频率");
        return "NG";
    }
}


function getScreenVendor() {
    systemCtrl.executeSystemCommand("cat /sys/devices/platform/soc@3000000/2502800.twi/i2c-2/2-0014/id > /tmp/tp_id.txt");
    const vendorStr = fs.read("/tmp/tp_id.txt", "r");
    if (vendorStr) {

        const trimmedVendorStr = vendorStr.trim();
        //console.log(`Screen Vendor: ${trimmedVendorStr}`);
        return trimmedVendorStr;
    } else {
        //console.log("无法读取屏幕厂商信息");
        return "NG";
    }
}

// 检查 License 是否注册（示例函数，需根据实际授权机制实现）
function checkLicense() {
    const fs = require("@system.fs")
    var filenm = "operation_license"
    // var partFilePath = "../../../../../mnt/extsd/msdkFiles/" + filenm
    var partFilePath = "../../../../../tmp/" + filenm
    if (fs.exists(partFilePath)) {
        //console.log("the " + filenm + " is exists.")
        return 1;
        // return "已注册!";
    }
    return 0;
    // return "未注册"; // 或 "已注册"
}


module.exports = {
    getTotalStorageInfo: getTotalStorageInfo,
    getWifiInfo: getWifiInfo,
    getCPUTemperature: getCPUTemperature,
    getCPUFrequency: getCPUFrequency,
    startSystemInfoTimer: startSystemInfoTimer,
    stopSystemInfoTimer: stopSystemInfoTimer,
    getSystemInfo: getSystemInfo,

}