// Bridge Panda ERP order page actions to the extension background worker.
(function() {
    'use strict';

    if (window.__QYDZ_ORDER_PAGE_BRIDGE__) return;
    window.__QYDZ_ORDER_PAGE_BRIDGE__ = true;

    function reply(action, requestId, response) {
        window.postMessage({
            source: 'qydz-order-extension',
            action: action + 'Result',
            requestId: requestId,
            response: response || {}
        }, '*');
    }

    function runtimeSend(message, callback) {
        try {
            chrome.runtime.sendMessage(message, function(response) {
                if (chrome.runtime.lastError) {
                    callback({ success: false, message: chrome.runtime.lastError.message });
                    return;
                }
                callback(response || {});
            });
        } catch (error) {
            callback({ success: false, message: error.message || String(error) });
        }
    }

    function trackingActionFromUrl(url) {
        var text = String(url || '').toLowerCase();
        if (text.indexOf('taobao.com') >= 0 || text.indexOf('tmall.com') >= 0) return 'getTrackingNumberTB';
        return 'getTrackingNumber1688';
    }

    window.addEventListener('message', function(event) {
        if (event.source !== window) return;
        var data = event.data || {};
        if (data.source !== 'qydz-order-page') return;

        var payload = data.payload || {};
        if (data.action === 'pluginBatchPrint') {
            runtimeSend({
                action: 'openPrintOrders',
                ids: Array.isArray(payload.ids) ? payload.ids : [],
                printUrl: payload.printUrl || ''
            }, function(response) {
                reply(data.action, data.requestId, response);
            });
            return;
        }

        if (data.action === 'fetchDomesticTracking') {
            if (!payload.url) {
                reply(data.action, data.requestId, { success: false, message: '缺少采购链接' });
                return;
            }
            runtimeSend({
                action: trackingActionFromUrl(payload.url),
                url: payload.url
            }, function(response) {
                if (response && response.trackingNumber) {
                    reply(data.action, data.requestId, {
                        success: true,
                        trackingNumber: response.trackingNumber
                    });
                } else {
                    reply(data.action, data.requestId, {
                        success: false,
                        message: (response && (response.error || response.message)) || '未获取到快递单号'
                    });
                }
            });
        }
    });

    window.postMessage({
        source: 'qydz-order-extension',
        action: 'ready',
        response: { success: true }
    }, '*');
})();
