$(function(){
    var dataOriginUrl = 'https://www.seerfar.com/admin';
    var webSite = 'https://www.seerfar.ru/', webSiteEn = 'https://www.seerfar.com/', webSiteCn = 'https://www.seerfar.cn/';
    let vip = true
    // 活动内容页/插件偏好 语言 维护
    var initLang = function (lang){
        // 语言国际化
        $.ajax({
            url: `../i18n/${lang}.json`,
            async: false,
            success: function (result){
                window.propI18nTextList = result;
                // 普通文本类的
                $('[data-i18n-text]').each(function(){
                    var attrName = $(this).attr('data-i18n-text');
                    var value = result[attrName];
                    if (value !== ''){
                        // 有值才替换
                        $(this).text(value);
                    }
                });
                if (lang === 'ru'){
                    $('.pop-con-right').css('width', '350px');
                }
            }
        });
    };
    var propI18nText = function (key){
        return window.propI18nTextList[key] || '';
    };
    chrome.storage.sync.get(['ext_lang'], function (items) {
        var ext_lang = items.ext_lang;
        if (!ext_lang){
            let navigatorLang = navigator.language;
            if ($.inArray(navigatorLang, ['zh', 'en', 'ru']) < 0){
                if (navigatorLang.includes('zh')){
                    navigatorLang = 'zh';
                }else if (navigatorLang.includes('en')){
                    navigatorLang = 'en';
                }else if (navigatorLang.includes('ru')){
                    navigatorLang = 'ru';
                }else {
                    navigatorLang = 'en';
                }
            }
            
            
            ext_lang = navigatorLang;

        }
        initLang(ext_lang);
        propI18nText();
        // 建立插件相关菜单选项
        var menuList = [
            {'icon': 'fa fa-home', 'name': propI18nText('seerfar_website'), 'id': 'website'},
            {'icon': 'fa fa-gear', 'name': propI18nText('preference_setting'), 'id': 'setting'}
        ];
        menuList.forEach(item => {
            let menuItem = `<div class="title-node"><i class="${item.icon}"></i><span id="${item.id}" title="${item.name}" class="bs-text">${item.name}</span></div>`;
            $('.menu-list').append(menuItem);
        });
        // 登录按钮
        var loginBox = '<div class="title-node login-box"><button class="btn btn-primary login-btn" style="width: 100%;background-color: #9E15BF;border-color: #9E15BF;">' + propI18nText('sign_in_now') + '</button></div>';
        // 约仓按钮
        var Warehouse_assistantBox = `<div id="WarehouseBox" class="title-node">
          <i class="bi bi-wb"></i>
          <span  class="bs-text Warehouse_assistant" id="Warehouse_assistantSet">${propI18nText('Warehouse_assistant')}</span>
          <a href="https://e1p7i0bkkue.feishu.cn/docx/Rfezd0K6GomIsVxugHucltEGnqc" target="_blank"  style="margin-left:5px;">
            <i class="fa fa-question-circle text-muted" style="font-size:16px;"></i>
          </a>
        </div>`
        //退出登录  
        let logoutMenu =  `<div class="title-node"><i class="fa fa-sign-out"></i><span class="bs-text logout">${propI18nText('logout')}</span></div>`;
        var loginUserBox = $('<div>', {'class': 'title-node flex-user-info'}).append(
            '<i class="fa fa-sign-out"></i>',
            $('<span>', {'class': 'bs-text logout', 'style': 'margin-left:5px'}).append(
                propI18nText('logout')
            ),
            $('<div>', {'class': 'nickname-member-grade'}).append(
                $('<span>', {'class': 'hide-nickname-more'})
            )
        );
        
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs){
            const currentUrl = (tabs && tabs[0] && tabs[0].url) ? tabs[0].url : '';
            let isWbSellerBackend = false;
            try{
                isWbSellerBackend = (new URL(currentUrl)).hostname === 'seller.wildberries.ru';
            }catch (e){
                isWbSellerBackend = false;
            }
            if (isWbSellerBackend){
                $(".menu-list > :eq(0)").after(Warehouse_assistantBox);
            }
        });
        chrome.storage.sync.get(['userId', 'username', 'reLogin', 'isSub','wbVip','ozVip'], function (item){
            if (item.userId && item.username && !item.reLogin){
                $('.menu-list').append(logoutMenu);
                chrome.tabs.query(
                  { active: true, currentWindow: true },
                  function (tabs) {
                    // tabs 是数组，tabs[0] 是当前激活的标签页
                    const currentTab = tabs[0];
                    const currentUrl = currentTab && currentTab.url ? currentTab.url : '';
                    let isWbSellerBackend = false;
                    try{
                        isWbSellerBackend = (new URL(currentUrl)).hostname === 'seller.wildberries.ru';
                    }catch (e){
                        isWbSellerBackend = false;
                    }
                    console.log("当前页面地址：", currentUrl); // 示例：https://www.google.com/
                    
                    if (isWbSellerBackend) {
                      if (!item.wbVip) {
                        $("#WarehouseBox").tooltip({
                          title: "您是免费用户无法使用该功能，请升级套餐",
                          placement: "top",
                        });
                         
                        vip = false;
                      }
                    }
                  }
                );
     
                let loginUserInfo = `<div class="title-node flex-user-info"><div>${item.username} (${item.isSub ? 'SID' : 'ID'}: ${item.userId})</div></div>`;
                $('.pop-con-right-context').append(loginUserInfo);
            }else{
                $('.pop-con-right-context').append(loginBox);
            }
        });
        // 登录按钮点击事件
        let ozInitUrl = 'https://www.ozon.ru/category/sistemnye-bloki-15704/'; // OZON默认页面
        let wbInitUrl = 'https://seller.wildberries.ru/';
        chrome.tabs.query({active: true, currentWindow: true}, function (tabs){
            chrome.storage.sync.get(['ozVip', 'wbVip', 'userId', 'username', 'reLogin'], (items) => {
                let currentWindowUrl = tabs[0].url;
                let isLogin = items.userId && items.username && !items.reLogin;//判断用户是否已经登录
                let vipBadge = `<span class="badge-primary">${propI18nText('vip')}</span>`;
                let freeBadge = `<span class="badge-primary">${propI18nText('free_user')}</span>`;
                if (currentWindowUrl.match(/wildberries\.ru|wildberries\.by|wildberries\.am|wildberries\.kg/ig)){
                    $('#product-search').prev().attr('class', 'bi bi-wb');
                    if (isLogin){
                        $('.con-title').append(items.wbVip ? vipBadge : freeBadge);
                    }
                }else if (currentWindowUrl.match(/ozon\.ru|ozon\.by|ozon\.kz|ozon\.com/ig)){
                    $('#product-search').prev().attr('class', 'bi bi-ozon');
                    if (isLogin){
                        $('.con-title').append(items.ozVip ? vipBadge : freeBadge);
                    }
                }
            });
        });
        $(document).on('click', '.login-btn', function (){
            sendMessageToContent({showMainBox: 1});
        });
        $(document).on('click', '#WarehouseBox', function (){
            chrome.storage.sync.get(['userId', 'username', 'reLogin', 'isSub','wbVip','ozVip'], function (item){
                if (item.userId && item.username && !item.reLogin){
                    if(!vip) return
                    // 打开侧边栏
                    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                        if (tabs[0]) {
                            chrome.sidePanel.setOptions({
                                enabled: true
                            });
                            chrome.sidePanel.open({ tabId: tabs[0].id });
                            window.close()
                        }
                    });
                } else {
                    sendMessageToContent({showMainBox: 1});
                }
            });
        });
        // 退出登录
        $(document).on('click', '.logout', function (){
            if ($(this).parent().hasClass('disabled')){
                return false;
            }
            $(this).parent('.title-node').remove();
            $('.con-title .badge-primary').remove();
            chrome.storage.sync.remove(['userId', 'username', 'token'], function (){
                $('.flex-user-info').remove();
                $('.menu-list').after(loginBox);
                chrome.sidePanel.setOptions({
                    enabled: false
                });
              
                chrome.runtime.sendMessage({target: "sidePanel"});
                sendMessageToContent({logout: 1});
            });
        });
        function sendMessageToContent(message)
        {
            let filterUrls = ['*://www.ozon.ru/*', '*://ozon.ru/*', '*://*.ozon.com/*', '*://www.ozon.kz/*', '*://ozon.kz/*', '*://www.ozon.by/*', '*://ozon.by/*', '*://www.wildberries.ru/*', '*://global.wildberries.ru/*', '*://www.wildberries.by/*', '*://www.wildberries.kg/*', '*://www.wildberries.am/*'];
            const sellerBackendUrls = ['*://seller.wildberries.ru/*', '*://seller.wildberries.cn/*', '*://seller.ozon.ru/*'];
            if (message.hasOwnProperty('active') || message.hasOwnProperty('logout')){
                filterUrls = [...filterUrls, ...sellerBackendUrls];
                chrome.tabs.query({ url: filterUrls }, function (tabs) {
                  if (tabs.length > 0) {
                    tabs.forEach(function (tab) {
                      chrome.tabs.sendMessage(tab.id, message);
                    });
                  }
                });
            }else if (message.hasOwnProperty('showMainBox')){
                chrome.tabs.query({active: true, currentWindow: true}, function (tabs){
                    const tabUrl = tabs[0].url;
                    const tabUrlObj = new URL(tabUrl);
                    let ozUrlMatch = tabUrl.match(/ozon\.ru|ozon\.by|ozon\.kz|ozon\.com/ig);
                    let wbUrlMatch = tabUrl.match(/wildberries\.ru|wildberries\.by|wildberries\.am|wildberries\.kg/ig);
                    if (ozUrlMatch || wbUrlMatch){
                        if (!tabUrl.includes('seller.wildberries')){
                            chrome.storage.sync.set({'showMainBox': 1}, function (){
                                // chrome.tabs.create({url: tabUrl.includes('seller.wildberries') ? wbInitUrl : ozInitUrl});
                                chrome.tabs.create({url: wbInitUrl});
                            });
                        }else{
                            chrome.tabs.sendMessage(tabs[0].id, message);
                        }
                    }else{
                        // 打开默认页面
                        chrome.storage.sync.set({'showMainBox': 1}, function (){
                            chrome.tabs.create({url: wbInitUrl});
                        });
                    }
                });
            }
        }
        var config = localStorage.getItem('_config') ? JSON.parse(localStorage.getItem('_config')) : {};
        // 开关控制事件
        switchEvent('#switch', function (){
            $('.menu-list .title-node').removeClass('disabled');
            $('.login-btn').removeAttr('disabled');
            $('.flex-user-info').removeClass('disabled');
            config['active'] = 1;
            localStorage.setItem('_config', JSON.stringify(config));
            sendMessageToContent({active: 1}); // 激活插件
            chrome.storage.sync.set({active: 1}, function () {

            });
        }, function (){
            $('.menu-list .title-node').addClass('disabled');
            $('.login-btn').attr('disabled', true);
            $('.flex-user-info').addClass('disabled');
            config['active'] = 0;
            localStorage.setItem('_config', JSON.stringify(config));
            sendMessageToContent({active: 0}); // 禁用插件
            chrome.storage.sync.set({active: 0}, function () {

            });
        });
        // 监听插件激活状态
        chrome.storage.sync.get(['active'], function (item){
            if (item.active && item.active == 1 || item.active === undefined){
                honeySwitch.showOn($('#switch'));
                $('.menu-list .title-node').removeClass('disabled');
                $('.login-btn').removeAttr('disabled');
                $('.flex-user-info').removeClass('disabled');
                if (item.active === undefined){
                    chrome.storage.sync.set({active: 1});
                }
            }else{
                honeySwitch.showOff($('#switch'));
                $('.menu-list .title-node').addClass('disabled');
                $('.login-btn').attr('disabled', true);
                $('.flex-user-info').addClass('disabled');
            }
        });

        $(document).on('click', '.menu-list .title-node span', function (){
            var menuId = $(this).attr('id');
            let parentStatus = $(this).parent().hasClass('disabled');
            if (parentStatus){
                return false;
            }
            let menuActionMap = new Map([
                ['product-search', () => {
                    sendMessageToContent({showMainBox: 1});
                }],
                ['website', () => {
                    let webSiteUrlMap = {
                        'zh': webSiteCn,
                        'en': webSiteEn,
                        'ru': webSite
                    };
                    let openUrl = webSiteUrlMap[ext_lang] || webSite;
                    window.open(openUrl);
                }],
                ['setting', () => {
                    chrome.tabs.create({url: 'options/options.html'});
                }],
            ]);
            let menuAction = menuActionMap.get(menuId);
            if (menuAction){
                menuAction.call(this);
            }
        });
    });
    // 插件偏好语言切换
//     chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
//     if (message.changeLang === 1) {
//         console.log('来自 options.js 的消息:', message.lang);
//          PageExt_lang = message.lang
//           if(PageExt_lang !== 'zh'){
//              if ($('#WarehouseBox').length) {
//                      $('#WarehouseBox').remove();
//                  }
//             }
//     }
//    });
});
