<?php viewLoad('public/header'); ?>
<link rel="stylesheet" href="<?=Mvc::$cfg['staticUrl']?>/css/washSheet.css">
<script src="<?=Mvc::$cfg['staticUrl']?>/js/lib/dxGrid.js"></script>
<script src="<?=Mvc::$cfg['staticUrl']?>/js/lib/washClean.js"></script>
<?php viewLoad('public/washCleanText'); ?>

<div id="sheetHeader">
    <span class="sheet-no"><?=lg('单号')?> #<?=(int) $sheet['wash_sheet_id']?></span>
    <span class="sheet-title"><?=htmlspecialchars($sheet['wash_sheet_title'])?></span>
    <span class="sheet-remark"><?=htmlspecialchars($sheet['wash_sheet_remark'])?></span>
</div>
<div id="sheetItemGrid"></div>

<script>
$(function () {
    var sheetId = <?=(int) $sheet['wash_sheet_id']?>;
    var vendors = <?=json_encode($vendors, JSON_UNESCAPED_UNICODE)?>;
    // JS 不直接调 lg()，文案统一由 PHP 翻译后注入
    var TEXT = <?=json_encode([
        'import'   => lg('导入数据单'),
        'number'   => lg('号码'),
        'submit'   => lg('提交'),
        'cancel'   => lg('取消'),
        'tip1'     => lg('格式1') . ': ' . lg('OE号'),
        'tip2'     => lg('格式2') . ': ' . lg('厂商') . ':' . lg('号码'),
        'tip3'     => lg('一行一条，可以直接从 Excel 粘贴'),
        'empty'    => lg('请粘贴要导入的号码'),
        'added'    => lg('新增'),
        'existed'  => lg('已存在'),
        'repeated' => lg('重复'),
        'failed'   => lg('失败'),
    ], JSON_UNESCAPED_UNICODE)?>;

    var cleanOptions = {
        host: APP.HOST + '/washSheetItem',
        params: { sheetId: sheetId },
        text: WASH_CLEAN_TEXT
    };

    createDxGrid('#sheetItemGrid', {
        host: APP.HOST + '/washSheetItem',
        key: 'wash_sheet_item_id',
        // 服务端据此把查/增/改/删/导出都锁在这张数据单里
        params: { sheetId: sheetId },
        // 清洗是批量操作，勾选框常驻；点行只做聚焦，不当成选中
        gridOptions: {
            selection: { mode: 'multiple', selectAllMode: 'page', showCheckBoxesMode: 'always', selectByClick: false }
        },
        columns: [
            { dataField: 'wash_sheet_item_id', caption: 'ID', width: 80, allowEditing: false },
            {
                dataField: 'wash_sheet_item_lnk_factory_id',
                caption: '<?=lg('号码厂商')?>',
                width: 160,
                lookup: {
                    dataSource: vendors,
                    valueExpr: 'factory_id',
                    displayExpr: 'factory_name',
                    allowClearing: true
                }
            },
            {
                dataField: 'wash_sheet_item_number',
                caption: '<?=lg('号码')?>',
                validationRules: [{ type: 'required' }]
            }
        ].concat(washCleanColumns(WASH_CLEAN_TEXT), [
            { dataField: 'wash_sheet_item_create_time', caption: '<?=lg('创建时间')?>', dataType: 'datetime', width: 150, allowEditing: false },
            { dataField: 'wash_sheet_item_update_time', caption: '<?=lg('更新时间')?>', dataType: 'datetime', width: 150, allowEditing: false }
        ]),
        toolbar: {
            import: false,
            batchSearch: { fields: ['wash_sheet_item_number'] },
            custom: [
                {
                    icon: 'upload',
                    text: TEXT.import,
                    onClick: function (dataGrid) { openImportPopup(dataGrid); }
                },
                {
                    icon: 'clearformat',
                    text: WASH_CLEAN_TEXT.title,
                    onClick: function (dataGrid) { openWashCleanDialog(dataGrid, cleanOptions); }
                }
            ]
        }
    });

    // ── 粘贴导入弹窗 ─────────────────────────────────────────
    function openImportPopup(dataGrid) {
        var text = '';

        var $content = $('<div>');
        var $field = $('<div class="import-field">').appendTo($content);
        $('<div class="import-field-label">').text(TEXT.number).appendTo($field);

        var $editorCol = $('<div class="import-field-editor">').appendTo($field);
        $('<div class="import-tip">')
            .append($('<div>').text(TEXT.tip1))
            .append($('<div>').text(TEXT.tip2))
            .append($('<div>').text(TEXT.tip3))
            .appendTo($editorCol);

        $('<div>').appendTo($editorCol).dxTextArea({
            height: 220,
            onValueChanged: function (e) { text = e.value; }
        });

        var $failed = $('<div class="import-failed">').appendTo($content);

        var $popup = $('<div>').appendTo('body').dxPopup({
            title: TEXT.import,
            visible: true,
            width: 700,
            height: 430,
            showCloseButton: true,
            contentTemplate: function () { return $content; },
            toolbarItems: [
                {
                    widget: 'dxButton',
                    location: 'after',
                    toolbar: 'bottom',
                    options: {
                        text: TEXT.submit,
                        type: 'default',
                        onClick: function () { submitImport(dataGrid, $popup.dxPopup('instance'), text, $failed); }
                    }
                },
                {
                    widget: 'dxButton',
                    location: 'after',
                    toolbar: 'bottom',
                    options: {
                        text: TEXT.cancel,
                        onClick: function () { $popup.dxPopup('instance').hide(); }
                    }
                }
            ],
            onHidden: function () {
                $popup.dxPopup('instance').dispose();
                $popup.remove();
            }
        });
    }

    // 提交后：有失败行就留在弹窗里把行号列出来，全部成功才关闭
    function submitImport(dataGrid, popup, text, $failed) {
        if (!(text || '').trim()) {
            DevExpress.ui.notify(TEXT.empty, 'warning', 2000);
            return;
        }

        $.ajax({
            url: APP.HOST + '/washSheetItem/import',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ sheetId: sheetId, text: text })
        }).then(function (res) {
            if (res.code !== 0) {
                DevExpress.ui.notify(res.msg, 'error', 3000);
                return;
            }

            var data = res.data;
            var summary = TEXT.added + ' ' + data.added
                + '，' + TEXT.existed + ' ' + data.existed
                + '，' + TEXT.repeated + ' ' + data.repeated
                + '，' + TEXT.failed + ' ' + data.failed.length;

            DevExpress.ui.notify(summary, data.failed.length ? 'warning' : 'success', 4000);
            dataGrid.refresh();

            $failed.empty();
            if (!data.failed.length) {
                popup.hide();
                return;
            }
            data.failed.forEach(function (item) {
                $failed.append($('<div>').text(item.line + '  →  ' + item.reason));
            });
        });
    }
});
</script>

<?php viewLoad('public/footer'); ?>
