<!-- 核心文件 -->
<link href="<?php echo e(URL::asset('bootstrap-table/bootstrap-table.min.css'), false); ?>" rel="stylesheet">
<link href="<?php echo e(URL::asset('bootstrap-table/bootstrap-table-fixed-columns.css'), false); ?>" rel="stylesheet"> 

<style>
    .dashboard-title .links {
        text-align: center;
        margin-bottom: 2.5rem;
    }
    .dashboard-title .links > a {
        width: 25%;
        padding: 0 1rem;
        font-size: 12px;
        font-weight: 600;
        letter-spacing: .1rem;
        text-decoration: none;
        text-transform: uppercase;
        color: #fff;
    }
    .dashboard-title h1 {
        font-weight: 200;
        font-size: 2.5rem;
    }
    .dashboard-title .avatar {
        background: #fff;
        border: 2px solid #fff;
        width: 70px;
        height: 70px;
    }

    /* 隐藏头部 */
    .content-header {
        display: none !important;
    }
    /* 隐藏底部 */
    .main-footer{
        display: none !important;
    }
    /* 隐藏图标 */
    /* .navbar-brand {
        display: none !important;
    } */
    table {
        border-collapse: collapse;
        width: 100%;
    }
    th, td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    th {
        background-color: #f2f2f2;
    }
    tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    #video-container {
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
        background: #000;
        z-index: 1;
    }
    #scan-overlay {
        position: absolute;
        top: 30%;
        left: 1%;
        width: 98%;
        height: 30%;
        border: 2px dashed rgba(255,255,255,0.7);
        z-index: 2;
        pointer-events: none;
    }
    .btn-group {
        position: relative;
        width: 100%;
        display: flex;
        justify-content: center;
        gap: 15px;
        z-index: 3;
    }
    /* 表格响应式优化 */
    @media (max-width: 768px) {
        table {
            font-size: 16px;
        }
        th, td {
            padding: 4px;
        }
    }
    .scan-button{
        position: relative;
        overflow: hidden;
    }
    .scan-modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: rgba(0,0,0,0.9);
        z-index: 9999;
        display: none;
    }
    .scan-content {
        position: relative;
        width: 100%;
        height: 70vh;
        margin-top: 15vh;
    }
    #video-container {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    #scan-overlay {
        position: absolute;
        top:30%;
        left:5%;
        bottom:30%;
        width: 90%;
        /* height: 30%; */
        border: 2px dashed rgba(255,255,255,0.7);
        pointer-events: none;
    }
    .close-scan {
        position: absolute;
        top: 5px;
        right: 10px;
        color: white;
        font-size: 60px;
        cursor: pointer;
        z-index: 100;
    }
    .scan-input {
        margin-bottom: 10px;
    }
    #spid {
        width: 180px;
        height: 35px;
        margin-right: 10px;
    }
    .table tr td:first-child, .table tr th:first-child {
        padding-left: 0rem;
    }
    .navbar-fixed-top .content-wrapper {
        padding-top: 5.5rem;
    }
    .table td {
        padding: 0.075rem;
        height: 3rem;
        line-height: 1.42857;
        border-color: #f0f0f0;
    }


    
    #bottom-div {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background: white;
        padding: 10px 0;
        box-shadow: 0 -2px 5px rgba(0,0,0,0.1);
        z-index: 1000;
        display: flex;
        flex-direction: column;
        gap: 10px;
        /* 新增安全区域适配 */
        padding-bottom: max(10px, env(safe-area-inset-bottom));
    }

    #bottom-table {
        width: 100%;
        max-height: 200px;
        overflow-y: auto;
        margin-bottom: 10px;
    }

    #bottom-table table {
        width: 100%;
        border-collapse: collapse;
    }
    .bottom-buttons {
        display: flex;
        justify-content: center;
        gap: 30px;
    }
    #table {
        margin-bottom: 250px; /* 调整底部边距 */
    }

    @media (max-width: 768px) {
        #bottom-div {
            gap: 10px;
            padding: 8px 0;
        }
        #table {
            margin-bottom: 200px;
        }
        #bottom-table {
            max-height: 130px;
            padding: 0 2%;
            margin: 0 auto;
        }
    }
    datalist option:nth-child(1) {
        font-weight: bold;
        color: #ff0000; /* 红色字体 */
    }


    /* 键盘弹出时自动适配 */
    @media (max-height: 500px) { /* 键盘高度阈值 */
      #bottom-div {
        position: absolute;
        bottom: auto;
        top: 100vh; /* 移到可视区域下方 */
      }
    }

</style>
<div data-no-pjax> <!-- 添加禁用标记 -->
<div class="scan-input">
    <label>商品:</label>
    <input id="djh" value="<?php echo e($djh, false); ?>" type="hidden">
    <input id="sp" list='sp_Info' name="sp" value=""  type="text">
    <datalist id="sp_Info"></datalist>
    <button class="btn btn-primary" id="tj">查询</button>
</div>
<div class="scan-button">
    <div class="btn-group">
        <!-- <button class="btn btn-primary" id="start-scan">开始扫描</button> -->
        <!-- <button class="btn btn-success" id="submit-data">提交数据</button> -->
    </div>
</div>
<div id="table" style="margin-top: 1rem;width: 100%;">
</div>
<div id="bottom-div">
    <div id="bottom-table">
        <table id="djmx" style="height: 100%;">
        </table>
    </div>
    <div class="bottom-buttons">
        <button class="btn btn-success" id="submit-data">保存</button>
        <button class="btn btn-primary" id="update-mx">修改</button>
        <button class="btn btn-primary" id="delete-mx">删除</button>
    </div>
</div>
<div class="scan-modal">
    <span class="close-scan">&times;</span>
    <div class="scan-content">
        <div id="video-container"></div>
        <div id="scan-overlay"></div>
    </div>
</div>
</div>

<script type="text/javascript" src="<?php echo e(URL::asset('bootstrap-3.3.7/js/bootstrap.min.js'), false); ?>"></script>
<script type="text/javascript" src="<?php echo e(URL::asset('bootstrap-table/bootstrap-table.js'), false); ?>"></script>
<script type="text/javascript" src="<?php echo e(URL::asset('bootstrap-table/bootstrap-table-fixed-columns.js'), false); ?>"></script>
<script type="text/javascript" src="<?php echo e(URL::asset('bootstrap-table/bootstrap-select.min.js'), false); ?>"></script>
<script type="text/javascript" src="<?php echo e(URL::asset('js/quagga.min.js'), false); ?>"></script>
<script type="text/javascript">
Dcat.ready(function() {
    function getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }

    $(document).ready(function() {
        // 监听select变化事件
        $('#sddm').change(function() {
            var sddm = $(this).val();
            if ($("#djh").length > 0) {
                // 发送AJAX请求
                $.ajax({
                    url: 'dh/change',
                    method: 'POST',
                    data: {sddm:sddm,_token: Dcat.token },
                    success: function(res) {
                        //替换单据编号
                        $('#djh').val(res.djh);
                        djh=$("#djh").val();
                        djhmxGet();
						if($('#spdm').text()){
							$('#sp').val($('#spdm').text());
						}
						if ($('#sp').val()!=null && $('#sp').val()!='') {
                            spcx();
                        }
                    },
                });
            }
        });

        if(getQueryParam('code')){
            $('#sp').val(getQueryParam('code'));
            $('#tj').click();
        }
        djhmxGet();
    });
    console.log('Pjax状态:', typeof $.pjax !== 'undefined' ? '已加载' : '未加载');
    console.log('Dcat版本:', Dcat.version);
    const isMobile = /Android|iPhone|iPad/i.test(navigator.userAgent);
    const modal = document.querySelector('.scan-modal');
    const startBtn = document.getElementById('start-scan');
    const videoContainer = document.getElementById('video-container');
    var djh=$("#djh").val();
    let scannerActive   =   false;
    var spcode          =   '';
    var spckj           =   '';
    var selectedRow     =   null; // 存储当前选中行

    // 显示扫码弹窗
    function showScanner() {
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }
    // 隐藏扫码弹窗
    function hideScanner() {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    }

    // 优化后的扫描配置
    const optimizedConfig = {
        inputStream: {
            name: "Live",
            type: "LiveStream",
            target: videoContainer,
            constraints: {
                width: { ideal:500},
                height: { ideal:500},
                facingMode: "environment",
            },
            area:{
                top:"30%",
                right:"5%",
                left:"5%",
                bottom:"30%",
            },
            willReadFrequently: true
        },
        decoder: {
            readers: ["ean_reader", "code_128_reader"],
            multiple: false
        },
        locator: {
            patchSize: "medium",//small medium large
            halfSample: true
        },
        locate: true,
        frequency: 10
    };
    // 资源释放保护
    function cleanupScanner() {
        try {
            if (Quagga && scannerActive) {
                Quagga.stop();
                const stream = videoContainer.srcObject;
                if (stream) {
                    stream.getTracks().forEach(track => track.stop());
                }
            }
        } catch (e) {
            console.error('清理异常:', e);
        }
        scannerActive = false;
    }
    // 优化识别处理
    Quagga.onDetected(function(result) {
        if (!result || !result.codeResult) return;
        //隐藏弹窗
        hideScanner();
        const code = result.codeResult.code;
        if (scannerActive) {
            $('#sp').val(code);
            $('#tj').click();
            //释放扫码资源
            cleanupScanner();
        }
    });

    $('#start-scan').click(function() {
        if (scannerActive) return;
        showScanner();
        Quagga.init(optimizedConfig, function(err) {
            if (err) {
                hideScanner();
                cleanupScanner();
                Dcat.error('摄像头初始化失败: ' + err.message);
                return;
            }
            scannerActive = true;
            Quagga.start();
            // 30秒自动关闭保护
            setTimeout(() => {
                if (scannerActive) {
                    hideScanner();
                    cleanupScanner();
                    Dcat.warning('扫描已超时15s自动关闭');
                }
            }, 15000);
        });
    });

    $("#submit-data").click(function() {
        if (spcode=='') {
            Dcat.error('请扫描货码或输入商品ID查询');
            return;
        }
        if (djh=='') {
            Dcat.error('无对应单号！');
            return;
        }
        const array = $('[id^="SL_"]').map(function() {
            if(this.value != 'null' && this.value > 0){
                return {[this.id.replace('SL_','')]: this.value};
            }
        }).get();
        $.ajax({
            url: 'submit',
            method: 'POST',
            data: {djh:djh,sp: array, code:spcode,ckj:spckj,_token: Dcat.token },
            success: function(res) {
                if(res.error == 1){
                    Dcat.error(res.msg);
                }else{
                    spcode='';
                    //$('#sp').val('');
					if($('#spdm').text()){
						$('#sp').val($('#spdm').text());
					}
                    $("#table").html('');
                    Dcat.success('成功');
                    djhmxGet();
                }
            },
        });
    })

    // 关闭扫码窗口 停止扫描 释放资源
    $('.close-scan').click(cleanupScanner);
    $('.close-scan').click(hideScanner);

    // 页面离开时释放资源
    $(window).on('beforeunload', cleanupScanner);

    var res=true;
    // 监听输入框内容变化
    $('#sp').on('input', function() {
        const searchText = $(this).val();
        const dataList = $('#sp_Info');
        // 清空现有选项
        dataList.empty();  
        // 只有输入内容长度≥2时才发起请求
        if(searchText.length >= 2 && res) {
            res=false;
            $.ajax({
                url: 'dh/getsp', // 替换为实际API地址
                method: 'GET',
                data: { code: searchText },
                dataType: 'json',
                success: function(response) {
                    // 遍历返回数据并添加选项
                    $.each(response, function(index, item) {
                        dataList.append(
                            $('<option>', {
                                value: item.spdm,
                                text: item.xh
                            })
                        );
                    });
                    res=true;
                },
                error: function(xhr, status, error) {
                    console.error('请求失败:', status, error);
                    res=true;
                }
            });
        }
    });

    //商品查询 
    function spcx() {
        $("#table").html('');
        var table2Html = "<table class='table-sm' id='table2'></table>";
        $("#table").append(table2Html);
        var table3Html = "<table class='table-sm' id='table3'></table>";
        $("#table").append(table3Html);
        var code = $('#sp').val();
        var sddm = $('#sddm').val();
        if(code == '' || code==null || code=='null'){
            Dcat.error('请选择输入商品!');
            return;
        }
        if (sddm=='') {
            Dcat.error('商店为空！');
            return;
        }
        if (djh=='') {
            Dcat.error('无对应单号！');
            return;
        }

        var option = [],
            optionls = [],
            max_row = 1,
            max_col = 1;
        $.ajax({
            url: 'searchYp',
            method: 'POST',
            data: {sddm:sddm,code:code,djh:djh,_token: Dcat.token },
            success: function(res) {
                var size_arr = res.size_arr;
                Dcat.loading(false);
                if(res.error){
                    Dcat.error(res.msg);
                }else{

                    if (Object.keys(size_arr).length > 0) {
                        max_row = size_arr['max_row'] + 1;
                        max_col = size_arr['max_col'];
                        for (key in size_arr['list']) {
                            option[key] = [];
                            optionls[key] = [];
                            for (var i = 0; i < size_arr['ggwz2_arr'].length; i++) {
                                option[key].push({
                                    field: 'SL_'+size_arr['ggwz2_arr'][i],
                                    align: 'center',
                                    title: size_arr['list'][key][size_arr['ggwz2_arr'][i]],
                                    formatter:function(value, row, index, field){
                                        if(value==0 || value==null || value=='null'){
                                            value='';
                                        }
                                        return '<input type="number" step="1" min="1" max="999" oninput="this.value=this.value.replace(/[^0-9]/g,\'\').substr(0,3);if(this.value>999)this.value=999;if(this.value<1&&this.value!=\'\')this.value=1" gg1dm="'+row.gg1dm+'" id="SL_'+row.gg1dm+'_'+this.title+'" value="'+value+'" style="width:3rem">';
                                    }
                                });

                                optionls[key].push({
                                    field: 'SL_'+size_arr['ggwz2_arr'][i],
                                    align: 'center',
                                    title: size_arr['list'][key][size_arr['ggwz2_arr'][i]],
                                });
                            }
                        }
                    }
                    spckj=res.data[0].CKJ;
                    spcode=res.data[0].YPDM;
                    // 先插入标题
                    $("#table").prepend("<br><h3 style='text-align:center' class='table-title'><B>"+spcode+'('+res.data[0].YPMC+')'+"<B><span id='spdm' style='display:none'>"+spcode+"</span></h3>");
                    if(res.fjsx!=null){
                        $("#table").prepend("<div style='text-align:left' class='table-title'><B>"
                        +'品牌:'+res.fjsx.品牌+' 品牌:'+res.fjsx.大类+' 类别:'+res.fjsx.类别+' 品类:'+res.fjsx.品类+'<br>面料:'+res.fjsx.面料+' 跟型:'+res.fjsx.跟型+' 里料:'+res.fjsx.里料+'<br>单价:'+spckj+
                        "<B></div>");
                    }

                    var sp_options = {
                        showLoading: false,
                        responsive: true,
                        height: '',
                        data: '',
                        columns: [
                            [
                                {
                                    field: 'gg1mc',
                                    title: '颜色',
                                    rowspan:max_row,
                                    align: 'center',
                                    valign: 'middle',
                                    cellStyle: {
                                        css: {
                                            "white-space": "nowrap",
                                            "text-overflow": "ellipsis",
                                            "position": "sticky",
                                            "left": '-0.1px',
                                            "background": "#fff",
                                            "z-index": 100
                                        }
                                    }
                                },
                                {
                                    title: '尺码',
                                    align: 'center',
                                    valign: 'middle',
                                    colspan: max_col
                                },{
                                    field: 'HJ_SL',
                                    title: '合计',
                                    rowspan:max_row,
                                    align: 'center',
                                    valign: 'middle',
                                    formatter:function(value, row, index, field){
                                        return "<span id=SL_"+row.gg1dm+">" + value + "</span>";
                                    }
                                }
                            ]
                        ],
                        //设置没数据时提示语
                        formatNoMatches: function() {
                            return '没有数据';
                        },
                        onPostBody: function() {
                            $(this).css('font-size', '16px');
                            $('#table2 thead tr:first-child th:first-child').css({
                                'text-align': 'center',
                                'vertical-align': 'middle', 
                                'position': 'sticky',
                                "background": "#fff",
                                "left": '-0.1px',
                                'top': 0,
                                'z-index': 102
                            });
                            
                        }
                    };
                    var spls_options = {
                        showLoading: false,
                        responsive: true,
                        height: '',
                        data: '',
                        columns: [
                            [
                                {
                                    field: 'gg1mc',
                                    title: '颜色(历史)',
                                    rowspan:max_row,
                                    align: 'center',
                                    valign: 'middle',
                                    cellStyle: {
                                        css: {
                                            "white-space": "nowrap",
                                            "text-overflow": "ellipsis",
                                            "position": "sticky",
                                            "left": '-0.1px',
                                            "background": "#fff",
                                            "z-index": 100
                                        }
                                    }
                                },
                                {
                                    title: '尺码(历史)',
                                    align: 'center',
                                    valign: 'middle',
                                    colspan: max_col
                                },{
                                    field: 'HJ_SL',
                                    title: '合计',
                                    rowspan:max_row,
                                    align: 'center',
                                    valign: 'middle',
                                }
                            ]
                        ],
                        //设置没数据时提示语
                        formatNoMatches: function() {
                            return '没有数据';
                        },
                        onPostBody: function() {
                            $(this).css('font-size', '16px');
                            $('#table2 thead tr:first-child th:first-child').css({
                                'text-align': 'center',
                                'vertical-align': 'middle', 
                                'position': 'sticky',
                                "background": "#fff",
                                "left": '-0.1px',
                                'top': 0,
                                'z-index': 102
                            });
                            
                        }
                    };
                    
                    for (key in option) {
                        if (key != undefined) {
                            sp_options['columns'].push(option[key]);
                            spls_options['columns'].push(optionls[key]);    
                        }
                    }
                    
                    sp_options.data = res.data;
                    $("#table2").bootstrapTable(sp_options);
                    $("#table2").bootstrapTable('hideLoading');

                    spls_options.data = res.lsdh;
                    $("#table3").bootstrapTable(spls_options);
                    $("#table3").bootstrapTable('hideLoading');
                    
                    //监控表格input
                    $("#table2").on('input','input',function() {
                         // 获取当前行
                        var $tr = $(this).closest('tr');
                        var gg1dm=$(this).attr('gg1dm');
                        // 获取行内所有input的值
                        var num = 0;
                        $tr.find('input').each(function() {
                            var v = parseInt(this.value-0);
                            if(v){}else{v=0}
                            num+= v;
                        });
                        $("#SL_"+gg1dm).text(num);
                    });
                }
            },
            error: function() {
                Dcat.loading(false);
                Dcat.error('请求失败');
            }
        });
    }
    //单据明细
    function djhmxGet() {
        var mx_options = {
            height: '',
            data: '',
            columns: [
                {field:'SPDM',title:'款号',align:'center',valign: 'middle',},
                {field:'CKJ',title:'单价',align:'center',valign: 'middle',},
                {field:'SL',title:'数量',align:'center',valign: 'middle',},
                {field:'JE',title:'金额',align:'center',valign: 'middle',},
            ],
            //设置没数据时提示语
            formatNoMatches: function() {
                return '没有数据';
            },
            onClickRow: function(row, $element) {
                // 移除之前选中行的样式
                $('.table-success').removeClass('table-success');
                // 添加当前行选中样式
                $element.addClass('table-success');
                selectedRow = row; // 存储选中行数据
            }
        };
        var djh=$("#djh").val();
        $.ajax({
            url: 'dh/getdjspmx',
            method: 'POST',
            data: {djh:djh,_token: Dcat.token },
            success: function(res) {
                mx_options.data = res;
                //删除之前表格
                $("#djmx").bootstrapTable('destroy');
                $("#djmx").bootstrapTable(mx_options);
                $("#djmx").bootstrapTable('resetView');
            },
        });
    }

    
    $('#tj').click(function() {
        spcx();
    })




    // 修改按钮事件
    $("#update-mx").click(function() {
        if(!selectedRow) {
            alert('请先选择要修改的行');
            return;
        }
        $('#sp').val(selectedRow.SPDM);
        spcx();
    });

    // 删除按钮事件
    $("#delete-mx").click(function() {
        if(!selectedRow) {
            alert('请先选择要删除的行');
            return;
        }
        if(confirm('确定要删除选中的行吗？')) {
            var djh=$("#djh").val();
            $.ajax({
                url: 'dh/deldjspmx',
                method: 'POST',
                data: {spdm: selectedRow.SPDM,djh:djh, _token: Dcat.token},
                success: function(res) {
                    if(!res.error) {
                        Dcat.success(res.msg);
                        $("#djmx").bootstrapTable('remove', {
                            field: 'SPDM',
                            values: [selectedRow.SPDM]
                        });
                        $("#djmx").bootstrapTable('resetView');
                        selectedRow = null;
                    }else{
                        Dcat.error(res.msg);
                    }
                }
            });
        }
    });
});
</script>
<?php /**PATH D:\phpstudy_pro\WWW\qr250\resources\views/dh.blade.php ENDPATH**/ ?>