let iv = "2134123412ABCDEF";
let secret_key = "BACDEF1234123412";
function parse(string) {
    return CryptoJS.enc.Utf8.parse(string);
}
function encrypt(data) {
    // Encrypt   
    return CryptoJS.AES.encrypt(parse(data), parse(secret_key), {
        iv: parse(iv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    }).toString();
}


//查看ID是否合规，不符合即404
function GetQueryString(name) {
    // 获取当前网页链接str
    var LocString = String(window.document.location.href);
    var rs = new RegExp("(^|)" + name + "=([^&]*)(&|$)", "gi").exec(LocString), tmp;
    if (tmp = rs) {
        return decodeURI(tmp[2]);
    }
    return "";
}
function isValidJsonObject(jsonObj) {
    // 确保输入是一个对象且不是 null
    if (jsonObj && typeof jsonObj === 'object') {
        // 获取对象的键数组
        const keys = Object.keys(jsonObj);
        // 检查对象是否有键，并且键的数量大于1
        return keys.length > 0;
    }
    // 处理非对象或 null 的情况
    return false;
}

let scanning = false;
let success = 0;
let failure = 0;

// cocoMessage.config({duration: 2000});

var id_en = GetQueryString('id')
// 获取遮罩层元素
const bloodMask = document.getElementById('bloodMask');
const successCount = document.getElementById('successCount');
const failureCount = document.getElementById('failureCount');

document.getElementById('yy-link').href = './call?id=' + encodeURIComponent(id_en);
document.getElementById('dk-link').href = './sign?id=' + encodeURIComponent(id_en);
document.getElementById('xd-link').href = './scan?id=' + encodeURIComponent(id_en);
document.getElementById('gr-link').href = './info?id=' + encodeURIComponent(id_en);

// 振动初始化
// navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;


var token=''
var httpRequest = new XMLHttpRequest();
toast.style.display = "flex";
httpRequest.open('GET', './zy_login_check?id=' + encodeURIComponent(id_en), true);
httpRequest.send();
httpRequest.onreadystatechange = function () {
    if (httpRequest.readyState == 4) {// 请求已完成
        if (httpRequest.status === 200) { // 请求成功
            var 凭证 = httpRequest.responseText;
            if ((凭证 || "").indexOf('有效') > -1) {
                toast.style.display = "none";
                token=凭证.replace("凭证有效","")
                
                //document.getElementById('pda_scan').addEventListener('click', pda_scan_click);

                //document.getElementById('pda_scan2').addEventListener('click', pda_scan_click("12.12.12.12"));

                document.getElementById('pda_scan').addEventListener('click', function() {
                    pda_scan_click("http://212.64.26.98:15656",1);
                });

                document.getElementById('pda_scan2').addEventListener('click', function() {
                    pda_scan_click("http://free.frp.vip:10724",2);
                });


                document.getElementById('pda_scan3').addEventListener('click', function() {
                    pda_scan_click("http://xjbxd.hb750700.cn",3);
                });

            } else {
                toast.style.display = "none";
                window.location = './login'
                // window.location = 'https://gz.360300.xyz/?redirect=1&id='+encodeURIComponent(id_en)
            }

        } else {
            toast.style.display = "none";
            swal("", "网络繁忙,请重试!", "warning");
        }
    }
};

var url_str="";
function pda_scan_click(link,action) {
    if (!scanning) {
        scanning = true;
        url_str=link;
        if(action==1){
            document.getElementById('pda_scan2').style.display = 'none';
            document.getElementById('pda_scan3').style.display = 'none';
            document.getElementById('pda_scan').style.display = 'none';

            // document.getElementById('pda_scan').disabled = true;
            // document.getElementById('pda_scan').innerText = '扫描中,请不要点击页面';
        }else if(action==2){
            document.getElementById('pda_scan').style.display = 'none';
            document.getElementById('pda_scan3').style.display = 'none';

            document.getElementById('pda_scan2').style.display = 'none'
            // document.getElementById('pda_scan2').disabled = true;
            // document.getElementById('pda_scan2').innerText = '扫描中,请不要点击页面';
        }else if(action==3){
            document.getElementById('pda_scan').style.display = 'none';
            document.getElementById('pda_scan2').style.display = 'none';

            document.getElementById('pda_scan3').style.display = 'none';
            // document.getElementById('pda_scan3').disabled = true;
            // document.getElementById('pda_scan3').innerText = '扫描中,请不要点击页面';
        }
        
        document.getElementById('saoma').focus();
        //我这里监听的是keypress事件，他可以区分大小写，使用keyedown事件好像不行。
        document.getElementById('saoma').addEventListener("keypress",keypress_event,true);
    }
}


function keypress_event(event) {

    var code = event.which || event.keyCode;

    //如果捕获到回车键，则扫码结束，将保存的字符串解析并展示到页面上
    if (code == 13 || code == 108) {
        document.getElementById('saoma').focus();
        var inputValue = document.getElementById('saoma').value;
        onScanSuccess(inputValue.replace(/[^a-zA-Z0-9]/g, ''),token);
        document.getElementById('saoma').value = '';
    }

}


const listContainer = document.getElementById('listContainer');
function addItem(订单号,结果) {
    const item = document.createElement('div');
    item.className = 'listItem';
    
    const title = document.createElement('h3');
    const span1 = document.createElement('span');
    const span2 = document.createElement('span');


    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    span1.textContent = "单号: "+订单号;
    span2.textContent = `${hours}:${minutes}:${seconds}`;
    // title.textContent = 订单号 + (listContainer.children.length + 1);
    title.appendChild(span1);
    title.appendChild(span2);

    const description = document.createElement('p');
    description.textContent = 结果;
    
    if ((结果 || "").indexOf('成功') == -1) {
        description.style.color = "red";
    }

    item.appendChild(title);
    item.appendChild(description);
    // 将新项目插入到列表的最前面
    if (listContainer.firstChild) {
        listContainer.insertBefore(item, listContainer.firstChild);
    } else {
        listContainer.appendChild(item);
    }
    // 平滑滚动到顶部
    listContainer.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
    // resetClearTimer();
}


//闪烁
function reduceHealth() {
    bloodMask.classList.remove('hidden');
    // 闪烁3秒后停止
    setTimeout(() => {
        // 3 秒后完全隐藏遮罩层
        setTimeout(() => {
            bloodMask.classList.add('hidden');
        }, 500); // 等待一小段时间确保透明度为0后再隐藏
    }, 1000); // 3 秒后停止闪烁
}

function onScanSuccess(decodedText, token) {
    if(decodedText==""){
        cocoMessage.error("无法识别PDA扫描结果", {duration:2000});
        return
    }
    toast.style.display = "flex";
    httpRequest.open('GET', url_str+'/zy_scan?id=' + encodeURIComponent(id_en) + "&token=" + token + "&waybillNos=" + decodedText, true);
    // httpRequest.open('GET', 'http://xd.hb750700.cn:15656/zy_scan?id=' + encodeURIComponent(id_en) + "&token=" + token + "&waybillNos=" + decodedText, true);
    httpRequest.send();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4) {// 请求已完成
            toast.style.display = "none";
            if (httpRequest.status === 200) { // 请求成功
                var 下段结果 = httpRequest.responseText;
                if ((下段结果 || "").indexOf('核查失败') > -1) {
                    cocoMessage.error(下段结果, {duration:2000});
                    addItem(decodedText,下段结果);
                    reduceHealth();
                    document.getElementById('jhsb').play();
                    failure++;
                    // if (navigator.vibrate) {navigator.vibrate(2000);} 
                }else if ((下段结果 || "").indexOf('下段成功') > -1) {
                    cocoMessage.success(下段结果, {duration:2000});
                    addItem(decodedText,下段结果);
                    document.getElementById('cg').play();
                    success++;
                }else if ((下段结果 || "").indexOf('撤单') > -1) {
                    cocoMessage.error(下段结果, {duration:2000});
                    addItem(decodedText,下段结果);
                    reduceHealth();
                    document.getElementById('xdsb').play();
                    failure++;
                    // if (navigator.vibrate) {navigator.vibrate(2000);} 
                }else if ((下段结果 || "").indexOf('特殊字符') > -1) {
                    cocoMessage.error(下段结果, {duration:2000});
                    addItem(decodedText,下段结果);
                    reduceHealth();
                    document.getElementById('jhsb').play();
                    // if (navigator.vibrate) {navigator.vibrate(2000);} 
                }else{
                    cocoMessage.error(下段结果, {duration:2000});
                    addItem(decodedText,下段结果);
                    reduceHealth();
                    document.getElementById('xdsb').play();
                    failure++;
                    // if (navigator.vibrate) {navigator.vibrate(2000);} 
                }

                // 更新状态
                successCount.textContent = success;
                failureCount.textContent = failure;

            } else {
                swal("", "网络繁忙,请重试!", "warning");
            }
        }
    };
}