
var _userdata = require("userdata.js");
var userData = _userdata.userData;
const fs = require("@system.fs");
var systemCtrl = require("systemCtrl.js");
var lvgl = require("@native.lvgl7");
var id_testRtcTimer = null;
var that;
var rtcCtl = require("factory_rtc.js");
var cntTime = 0;
var cntSuccess = 0;
var checkClockPath = '../../../../../mnt/UDISK/checkClock.txt';
var checktmpClockPath = '../../../../../tmp/checkClock.txt';
var Path = "/mnt/UDISK/checkClock.txt";
var tmpPath = "/tmp/checkClock.txt";
function system(str) {
    systemCtrl.executeSystemCommand(str);
}


function exitTestRTC() {
    if (id_testRtcTimer != null) {
        clearInterval(id_testRtcTimer);
        id_testRtcTimer == null;
    }
}

function factoryTestRTCInit(obj) {
    that = obj;
    if (id_testRtcTimer != null) {
        clearInterval(id_testRtcTimer);
        id_testRtcTimer == null;
        cntTime = 0;
        cntSuccess = 0;
    }
    updateRtcInfo();
    id_testRtcTimer = setInterval(() => {
        cntTime += 1;
        updateRtcInfo();
    }, 1000);
}
function setTextColorById(that, id, value) {
    const color = (value === "NA") ? "#ff0000" : "#00ff00";
    that.$setTextColor(id, color);
}
function setTextColorByText(that, id, value) {
    var color;
    if (value === "测试失败") {
        color = "#ff0000";
    }
    else if (value === "检测中...") {
        color = "#ff8400";
    }
    else {
        color = "#00ff00";
    }
    that.$setTextColor(id, color);
}
var testCnt = 3
function updateRtcInfo() {
    var rtc = getRtcTime();
    that.crtLocalTime = rtc;
    //console.log("hwRtc:" + rtc);



    setTextColorById(that, 'id_crtLocalTime', that.crtLocalTime);


    var values = [that.crtLocalTime];
    var allValuesValid = values.every(value => value !== "NA");
    console.log("allValuesValid:" + allValuesValid);
    // 根据检查结果设置烧录测试状态

    that.crtfilesLocalTime = "NA";


    console.log(`[RTC] 第 ${cntTime} 次检测，状态：${allValuesValid == true ? "有效" : "无效"}`);
    if (allValuesValid == 1) {
        cntSuccess += 1;
    } else {
        cntSuccess = 0;
    }
    if (cntTime < testCnt) {
        that.crtTextRtcText = "检测中...";
        setTextColorByText(that, 'id_crtTextRtcText', that.crtTextRtcText);
        that.$setY("id_yes", -480);
        return; // 不继续判断
    }

    // 第2次检测完成，设置最终结果
    if (cntSuccess > testCnt) {
        if (!fs.exists(checktmpClockPath)) {

            if (fs.exists(checkClockPath)) {

                var fileContent = fs.read(Path, "r")
                if (fileContent) {

                    that.crtfilesLocalTime = fileContent.trim();

                    var fileYMD = parseYMDHM(fileContent.trim());
                    var currYMD = parseYMDHM(that.crtLocalTime);
                    if (!timeGT(currYMD, fileYMD)) {
                        console.log("[RTC] 时钟未前进，测试失败");
                        cntSuccess = 0;
                        var state = 0;
                        that.crtTextRtcText = state ? "测试通过" : "测试失败";
                        setTextColorByText(that, 'id_crtTextRtcText', that.crtTextRtcText);
                        globalThis.factoryTest.rtc = state ? 1 : 2;
                        that.$setY("id_yes", state ? 0 : -480);
                        console.log("[RTC] 测试完成，最终状态：" + (state ? "通过" : "失败"));
                    } else {
                        console.log("fileYMD" + fileContent.trim());
                        console.log("currYMD:" + that.crtLocalTime);
                        console.log("[RTC] 时钟已前进，继续通过流程");
                        system("rm -fr " + Path);
                        var state = 1;
                        that.crtTextRtcText = state ? "测试通过" : "测试失败";
                        setTextColorByText(that, 'id_crtTextRtcText', that.crtTextRtcText);
                        globalThis.factoryTest.rtc = state ? 1 : 2;
                        that.$setY("id_yes", state ? 0 : -480);
                        console.log("[RTC] 测试完成，最终状态：" + (state ? "通过" : "失败"));
                    }
                } else {
                    oneTest();
                }

            } else {
                oneTest();
            }
        } else {

            oneTest();
        }
        exitTestRTC();
    }
    // that.crtTextRtcText = cntSuccess > testCnt ? "测试通过" : "测试失败";
    // setTextColorByText(that, 'id_crtTextRtcText', that.crtTextRtcText);
    // globalThis.factoryTest.rtc = cntSuccess > testCnt ? 1 : 2;
    // that.$setY("id_yes", cntSuccess > testCnt ? 0 : -480);
    // console.log("[RTC] 测试完成，最终状态：" + (cntSuccess > testCnt ? "通过" : "失败"));


    // cntTime = 0;
    // 可选：停止定时器
    // exitTestRTC();
    checkAutoFactory();

}

function oneTest() {
    var iso = that.crtLocalTime;
    system("echo '" + iso + "' > " + Path);
    system("echo '" + iso + "' > " + tmpPath);
    system("sync");
    that.crtfilesLocalTime = iso;
    setTimeout(() => {
        that.crtTextRtcText = "请断电重启 测试第二阶段掉电保存"
    }, 300);
}

function checkAutoFactory() {
    require("factory_testAuto.js").autoFactoryNextPage("factoryTestRtc");
}
function parseYMDHM(str) {
    // str = "2025-10-03T19:41:38"
    var p = str.split('T');
    var d = p[0].split('-').map(Number);   // [y, m, d]
    var t = p[1].split(':').map(Number);   // [h, m, s]
    return { y: d[0], m: d[1], d: d[2], h: t[0], min: t[1], s: t[2] };
}

function timeGT(a, b) {
    // a > b 返回 true
    if (a.y !== b.y) return a.y > b.y;
    if (a.m !== b.m) return a.m > b.m;
    if (a.d !== b.d) return a.d > b.d;
    if (a.h !== b.h) return a.h > b.h;
    if (a.min !== b.min) return a.min > b.min;
    return a.s > b.s;
}

function getRtcTime() {
    var partFilePath = "../../../../../dev/rtc1";
    if (!fs.exists(partFilePath)) {
        return "NA";
    }
    system('hwclock -f /dev/rtc1 > /tmp/hwRtc.txt');
    const raw = fs.read('/tmp/hwRtc.txt');
    if (!raw) return 'NA';

    /* 典型行：Thu Jan  1 18:22:21 1970  0.000000 seconds */
    var p = 0;

    // 星期
    while (p < raw.length && raw[p] !== ' ') p++;
    while (p < raw.length && raw[p] === ' ') p++;

    // 月
    var monSt = p;
    while (p < raw.length && raw[p] !== ' ') p++;
    var mon = raw.slice(monSt, p);
    while (p < raw.length && raw[p] === ' ') p++;

    // 日
    var daySt = p;
    while (p < raw.length && raw[p] !== ' ') p++;
    var day = raw.slice(daySt, p).trim();
    while (p < raw.length && raw[p] === ' ') p++;

    // 时间  HH:MM:SS[.xxxxxx]
    var timeSt = p;
    while (p < raw.length && raw[p] !== ' ') p++;
    var timeFull = raw.slice(timeSt, p);   // 可能 19:38:24.123456
    var time = timeFull.split('.')[0];   // 只取 19:38:24
    while (p < raw.length && raw[p] === ' ') p++;

    // 年
    var yearSt = p;
    while (p < raw.length && raw[p] !== ' ') p++;
    var year = raw.slice(yearSt, p);

    const monTbl = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const mo = monTbl.indexOf(mon) + 1;
    if (mo === 0) return 'NA';

    const mm = String(mo).padStart(2, '0');
    const dd = String(day).padStart(2, '0');
    return `${year}-${mm}-${dd}T${time}:00`;
}




module.exports = {
    factoryTestRTCInit: factoryTestRTCInit,
    exitTestRTC: exitTestRTC


}