/**Background是用于后台执行的js程序**/
importScripts('crypto-js.min.js', 'config.js', '../plugins/lodash/lodash.min.js');
const CLIENT_TYPE = 'APPOINTMENT_STOCK_PLUGIN';
const EXT_VERSION = chrome.runtime.getManifest().version;//插件当前版本
const CODE_SUCCESS = 200, CODE_UNAUTHORIZED = 401;
const axiosApi = (url, type, requestData = '', headers = {}) => {
    let requestConfig = {'method': type};
    const urlObj = new URL(url);
    if (headers.hasOwnProperty('Content-Type') && headers['Content-Type'] === 'application/json' && requestData){
        headers['Cache-Id'] = CryptoJS.MD5(`${urlObj.pathname}:${requestData}`).toString();
    }
    if (!_.isEmpty(headers)){
        requestConfig['headers'] = headers;
    }
    if (requestData){
        requestConfig['body'] = requestData;
    }
    return fetch(url, requestConfig).then((response) => {
        if (response.ok){
            return response.json()
        }else{
            return Promise.reject(response);
        }
    });
};
// 获取图片验证码
const getCaptcha = (port) => {
    axiosApi(config.captchaApi, 'get').then((res) => {
        if (res.code === CODE_SUCCESS){
            port.postMessage({'success':true, 'data':res.data});
        }else{
            port.postMessage({'errorCode':res.code});
        }
    }).catch(error => {
        if (error && error.status){
            port.postMessage({'errorCode':error.status});
        }
    });
};
// 获取系统相关配置
const getSystemConfigs = (port) =>{
    axiosApi(config.systemVariablesApi, 'get').then((res) => {
        if (res.code === CODE_SUCCESS && res.data) {
            port.postMessage({'data': res.data});
        }
    });
};
// 获取用户相关信息
const getUserInfo = (port) => {
    chrome.storage.sync.get(['userId', 'username', 'token'], function (items) {
        let headers = {};
        if (items.token) {
            headers = {...headers, 'Authorization': `Bearer ${items.token}`};
        }
        axiosApi(config.userInfoApi, 'get', '', headers).then((res) => {
            if (res.code && res.code === CODE_SUCCESS && res.data){
                let responseData = res.data;
                //  更新token
                  if(responseData.newToken){
                     chrome.storage.sync.set({'token': responseData.newToken}) 
                  }
                  chrome.storage.sync.set({'messageEmail': responseData.messageEmail}) 
                port.postMessage({'userInfo': responseData});
            }else{
                switch (res.code){
                    case CODE_UNAUTHORIZED:
                        chrome.storage.sync.set({'reLogin': 1});
                        break;
                }
                port.postMessage({'errorCode': res.code});
            }
        }).catch(err => {
            switch (err.status){
                case CODE_UNAUTHORIZED:
                    chrome.storage.sync.set({'reLogin': 1});
                    break;
            }
            port.postMessage({'errorCode': err.status});
        });
    });
};
// 获取浏览器当前语言
const getBrowserLang = () => {
    let navigatorLang = navigator.language;
    if (!['zh', 'en', 'ru'].includes(navigatorLang)){
        if (navigatorLang.includes('zh')){
            navigatorLang = 'zh';
        }else if (navigatorLang.includes('en')){
            navigatorLang = 'en';
        }else if (navigatorLang.includes('ru')){
            navigatorLang = 'ru';
        }else {
            navigatorLang = 'en';
        }
    }
    return navigatorLang;
};
// 系统用户登录
const userLogin = (port, message) => {
    chrome.storage.sync.get(['ext_lang'],  (items) => {
        let sysLang = items.ext_lang || getBrowserLang();
        let clientLangMap = {
            'zh': 'zh-CN',
            'en': 'en-US',
            'ru': 'ru-RU',
        };
        let clientLang = clientLangMap[sysLang] || 'en-US';
        let loginData = {'loginName': message.account, 'captchaId': message.captchaId, 'captcha': message.captcha, 'password': message.password, type: 0, 'clientType': CLIENT_TYPE};
        if (message.captchaVO){
            loginData = {...loginData, 'captchaVO':message.captchaVO};
        }
        let headers = {'Content-Type': 'application/json', 'Plugin-Version': EXT_VERSION, 'Client-Language': clientLang};
        axiosApi(config.loginApi, 'post', JSON.stringify(loginData), headers).then((res) => {
            if (res.code === CODE_SUCCESS){
                let responseData = res.data;
                port.postMessage({'userInfo': responseData});
                chrome.tabs.query({url: ['https://www.ozon.ru/*']}, function (tabs){
                    if (tabs.length > 0){
                        tabs.forEach((tab) => {
                            chrome.tabs.sendMessage(tab.id, {'userLogin': 1});
                        });
                    }
                });
            }else{
                port.postMessage({'errorCode': res.code, 'data': res.data, 'msg': res.msg});
            }
        });
    });
};
// 发送约仓邮件
const sendNotify = (port, message) => {
    chrome.tabs.query({}, (tabs) => {
        tabs.forEach((item) => {
            if(Number(item.id) === Number(message.tabId)){
                chrome.storage.sync.get(["token"], (items) => {
                    let requestApi = config.sendNotifyApi;
                    let params = {
                        orderId: message.orderId,
                        taskName: message.taskName,
                        enterprise: message.enterprise,
                        appointmentDate: message.appointmentDate,
                    }
                    fetch(requestApi, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        Authorization: "Bearer " + items.token,
                    },
                    body: JSON.stringify(params), // ✅ 正确：body 在 headers 外面
                    });
                });
            }
        })
    });
};
let visitTabId;
let activeTabIds = [];
let tabUrlsFilters = ['*://*.ozon.ru/*', '*://ozon.ru/*', '*://*.ozon.com/*', '*://www.ozon.kz/*', '*://ozon.kz/*', '*://www.ozon.by/*', '*://ozon.by/*', '*://*.wildberries.ru/*', "*://*.wildberries.am/*", "*://*.wildberries.by/*", "*://*.wildberries.eu/*", "*://*.wildberries.kg/*", "*://*.wildberries.kz/*", "*://*.wildberries.ru/*", "*://*.wildberries.tj/*"];
chrome.runtime.onInstalled.addListener(function (){
    chrome.tabs.query({url: tabUrlsFilters}, function (tabs){
        if (tabs.length > 0){
            tabs.forEach((tab) => {
                chrome.tabs.reload(tab.id);
            });
        }
    });
    chrome.storage.sync.set({'active': 1});
    //判断扩展是否重复安装
    chrome.management.getAll(extensions => {
        let currExtId = chrome.runtime.id;
        let similarExtensions = extensions.filter(ext => {
            return ext.id !== currExtId && ext.enabled && ext.type === 'extension' && (ext.name.includes('Seerfar') || (ext.description && ext.description.includes('Seerfar')));
        });
        if (similarExtensions.length){
            let navigatorLang = navigator.language;
            let notifyTitle = '', notifyMsg = '';
            if (navigatorLang.includes('zh')){
                notifyTitle = '发现相似扩展程序';
                notifyMsg = '检测到您可能安装了多个Seerfar的扩展，同时运行可能导致功能冲突，建议保留最常用的一个扩展以获得最佳体验。'
            }else if (navigatorLang.includes('en')){
                notifyTitle = 'Similar extensions detected.';
                notifyMsg = 'Multiple Seerfar extensions detected. To avoid conflicts, please keep only your preferred one.';
            }else if (v.includes('ru')){
                notifyTitle = 'Обнаружены похожие расширения.';
                notifyMsg = 'Найдены несколько расширений Seerfar. Во избежание конфликтов оставьте только одно.';
            }
            chrome.notifications.create({
                type: 'basic',
                iconUrl: `chrome-extension://${chrome.i18n.getMessage("@@extension_id")}/assets/images/seerfar/seefarlogo2-trans.png`,
                title: notifyTitle,
                message: notifyMsg,
            });
        }
    });
});
// 插件加载时才注册该监听事件
let listenFilterUrls = [
    "*://*.ozon.ru/api/entrypoint-api.bx/page/json/v2*",
    "*://ozon.ru/api/entrypoint-api.bx/page/json/v2*",
    "*://*.ozon.com/api/entrypoint-api.bx/page/json/v2*",
    "*://*.ozon.kz/api/entrypoint-api.bx/page/json/v2*",
    "*://ozon.kz/api/entrypoint-api.bx/page/json/v2*",
    "*://ozon.by/api/entrypoint-api.bx/page/json/v2*",
    "*://*.ozon.by/api/entrypoint-api.bx/page/json/v2*",
    "*://*.wb.ru/personal/ru/common/*/search*",
    "*://*.wb.ru/catalog/*/*/catalog*",
    "*://*.wb.ru/exactmatch/ru/*/*/search*",
    "*://*.wb.ru/brands/*/catalog*",
    "*://*.wb.ru/sellers/*/catalog*",
    "*://*.wb.ru/cards/*/detail*",
    "*://*.wb.ru/cards/*/list*",
    "*://*.wb.ru/recom/ru/common/*/search*",
    "*://*.wildberries.ru/*/personal/ru/common/*/search*",
    "*://*.wildberries.ru/*/catalog/*/*/catalog*",
    "*://*.wildberries.ru/*/exactmatch/ru/*/*/search*",
    "*://*.wildberries.ru/*/brands/*/catalog*",
    "*://*.wildberries.ru/*/sellers/*/catalog*",
    "*://*.wildberries.ru/*/cards/*/detail*",
    "*://*.wildberries.ru/*/cards/*/list*",
    "*://*.wildberries.ru/*/recom/ru/common/*/search*"
];
let tempThreads = [];
let threadsInfo = {};
let mutexTab = function (id){
    const tempTimestamp = Date.now();
    if (!tempThreads.includes(id)) {
        tempThreads.push(id);
        threadsInfo[id] = {};
        threadsInfo[id]['t'] = tempTimestamp;
        return true;
    } else {
        // время ожидания реакции в милисекундах
        if ((tempTimestamp - threadsInfo[id]['t']) > 500) {
            threadsInfo[id]['t'] = tempTimestamp;
            return true;
        }
    }
    return false;
};// 建立service worker和content script之间的消息通信
chrome.runtime.onConnect.addListener(function (port){
    port.onMessage.addListener(function (message){
        let portActionMap = new Map([
            ['options', () => {
                if (message.redirectToOptions && message.redirectToOptions === 1){
                    chrome.tabs.create({url: 'options/options.html'});
                }
            }],
            ['captcha', () => {
                if (message.status && message.status === 1){
                    //获取图片验证码
                    getCaptcha(port);
                }
            }],
            ['login', () => {
                userLogin(port, message);
            }],
            ['sysConfig', () => {
                if (message.status && message.status === 1){
                    getSystemConfigs(port);
                }
            }],
            ['userInfo', () => {
                if (message.status && message.status === 1){
                    getUserInfo(port);
                }
            }],
            ['reviewsAnalysis', () => {
                reviewAnalysis(port, message);
            }],
            ['sendNotify', () => {
                sendNotify(port, message);
            }],
            ['checkPicCaptcha', () => {
                checkPictureCaptcha(port, message);
            }],
        ]);
        let portAction = portActionMap.get(port.name);
        if (portAction){
            portAction.call(this);
        }
    });
});
// 监听浏览器新标签创建
let tabUpdateListen = function (tabId, changeInfo, tab){
    if (tab.status == 'complete'){
        chrome.storage.sync.get(['showMainBox'], function (items) {
            // 只有点击插件菜单栏才会发送消息
            if (items.showMainBox){
                let message = {showMainBox: 1};
                chrome.tabs.sendMessage(tabId, message);
                // 发送完消息后清理缓存，防止多个页面共用
                chrome.storage.sync.remove(['showMainBox']);
            }
        });
    }
};
// 标签页创建监听事件
chrome.tabs.onCreated.addListener(function (tab){
    if (tab.pendingUrl !== 'chrome://newtab/'){
        chrome.tabs.onUpdated.addListener(tabUpdateListen);
    }
});
chrome.windows.onRemoved.addListener(function (windowId){
    chrome.storage.sync.remove(['is_close', 'ozCloseAdv', 'wbCloseAdv']);
});
chrome.tabs.onActivated.addListener(function (activeInfo){
    if (activeInfo.tabId === visitTabId || activeTabIds.includes(activeInfo.tabId)){
        if (tempThreads.includes(activeInfo.tabId)) {
            threadsInfo[activeInfo.tabId]['t'] = 0;
        }
        chrome.tabs.sendMessage(activeInfo.tabId, {actionId: 'changeTab', 'diffTab': true});
    }
});
// 监听popup.js 通信
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('message.target',message.target);
    
 if (message.target === "sidePanel") {
    // 1. 查询当前激活标签页的侧边栏（侧边栏依附于标签页）
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const currentTabId = tabs[0]?.id;
      if (!currentTabId) {
        sendResponse({ success: false, msg: "无激活标签页" });
        return;
      }
      console.log('回传之前');
      // 2. 转发消息给侧边栏（通过 tabs.sendMessage，指定标签页 ID）
      chrome.tabs.sendMessage(
        currentTabId,
        { ...message }, // 转发 Popup 的消息内容
      );
    });
    // 异步响应，必须返回 true
    return true;
  }
});
// 监听约仓侧边栏关闭事件
chrome.sidePanel.onClosed.addListener(({ windowId }) => {
    chrome.tabs.query({}, (tabs) => {
        tabs.forEach((item) => {
            if(item.url.includes('https://seller.wildberries.ru/')) {
                chrome.tabs.sendMessage(item.id, {type: 'cancel'});
            }
        });
	});
});