$(function(){
    const BASE_URL = 'https://www.seerfar.com';
    const CN_BASE_URL = 'https://www.seerfar.cn';
    const RU_BASE_URL = 'https://www.seerfar.ru';
    let extVersion = chrome.runtime.getManifest().version;
    var changeLang = function (lang, async = false){
        let regUrl = '', title = '';
        let langMap = {
            'zh': {
                'regUrl': `${CN_BASE_URL}/sign-up/`,
                'title': 'Seerfar - 偏好设置'
            },
            'en': {
                'regUrl': `${BASE_URL}/sign-up/`,
                'title': 'Seerfar - Preference Setting'
            },
            'ru': {
                'regUrl': `${RU_BASE_URL}/sign-up/`,
                'title': 'Seerfar - Настройка предпочтений'
            },
        };
        title = langMap[lang]['title'] || '';
        regUrl = langMap[lang]['regUrl'] || '';
        $('title').text(title);
        $('.sign-up-now').attr('href', regUrl);
        $('.title-version').text(`v${extVersion}`);
        // 语言国际化
        $.getJSON('../i18n/'+lang+'.json', function (res){
            // 普通文本类的
            $('[data-i18n-text]').each(function(){
                var attrName = $(this).attr('data-i18n-text');
                var value = res[attrName];
                if (value !== ''){
                    // 有值才替换
                    $(this).text(value);
                }
            });
        });
    };
    let toastErrorMsg = function (container, content, isBody = false){
        let toastOptions = {
            'background': '#fff',
            'color': '#000',
            'content': `<div class="d-flex align-items-center"><span class="fa fa-close" style="color:red;font-size:1.2rem;margin-right:5px"></span>${content}</div>`
        };
        if (isBody){
            toastOptions = {...toastOptions, 'position':'fixed'};
        }
        container.toast(toastOptions);
    };
    chrome.storage.sync.get(['ext_lang', 'active', 'extSearchReview', 'extDetailReview'], 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;
        }
        changeLang(ext_lang);
        $('.change-lang').selectpicker('val', ext_lang);
    });
    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/*'];
    const otherPlatformUrls = ["https://www.amazon.com/*/dp/*", "https://www.amazon.com/dp/*", "https://www.amazon.pl/*/dp/*", "https://www.amazon.pl/dp/*", "https://www.amazon.de/*/dp/*", "https://www.amazon.de/dp/*", "https://www.amazon.co.uk/*/dp/*", "https://www.amazon.co.uk/dp/*", "https://*.amazon.de/*/dp/*", "https://*.amazon.de/dp/*", "https://*.amazon.co.uk/*/dp/*", "https://*.amazon.co.uk/dp/*", "https://*.amazon.fr/*/dp/*", "https://*.amazon.fr/dp/*", "https://*.amazon.es/*/dp/*", "https://*.amazon.es/dp/*", "https://*.amazon.it/*/dp/*", "https://*.amazon.it/dp/*", "https://*.amazon.ca/*/dp/*", "https://*.amazon.ca/dp/*", "https://*.amazon.in/*/dp/*", "https://*.amazon.in/dp/*", "https://*.amazon.sg/*/dp/*", "https://*.amazon.sg/dp/*", "https://*.amazon.ae/*/dp/*", "https://*.amazon.ae/dp/*", "https://*.amazon.nl/*/dp/*", "https://*.amazon.nl/dp/*", "https://*.amazon.com.mx/*/dp/*", "https://*.amazon.com.mx/dp/*", "https://*.amazon.com.au/*/dp/*", "https://*.amazon.com.au/dp/*", "https://*.amazon.com.br/*/dp/*", "https://*.amazon.com.br/dp/*", "https://*.amazon.com.tr/*/dp/*", "https://*.amazon.com.tr/dp/*", "https://*.amazon.co.jp/*/dp/*", "https://*.amazon.co.jp/dp/*", "https://*.amazon.com/*/dp/*", "https://*.amazon.com/dp/*", "https://*.amazon.cn/*/dp/*", "https://*.amazon.cn/dp/*", "https://*.amazon.sa/*/dp/*", "https://*.amazon.sa/dp/*", "https://*.amazon.se/*/dp/*", "https://*.amazon.se/dp/*", "https://detail.1688.com/*", "https://mobile.pinduoduo.com/*", "https://mobile.yangkeduo.com/*", "https://market.yandex.ru/card/*"];
    $('.change-lang').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue){
        var lang = $(this).val();
        $(this).next().blur();
        // 防止首次加载时执行两次
        if (clickedIndex !== null && isSelected === true){
            changeLang(lang, true);
            chrome.storage.sync.set({'ext_lang': lang}, function (){
                // 切换语言后同步到ozon相关注入页面
                let newFilterUrls = [...filterUrls, ...sellerBackendUrls, ...otherPlatformUrls];
                chrome.tabs.query({url: newFilterUrls}, function (tabs){
                    if (tabs.length > 0){
                        tabs.forEach((tab) => {
                            chrome.tabs.sendMessage(tab.id, {'changeLang': 1, 'lang': lang});
                        });
                    }
                });
                // 通知 popup.js
                // chrome.runtime.sendMessage({ 'changeLang': 1, 'lang': lang });
            });
        }
    });
    var sendMessageToContent = function (message){
        chrome.tabs.query({url: filterUrls}, function (tabs){
            tabs.forEach(function (tab){
                chrome.tabs.sendMessage(tab.id, message);
            });
        });
    };
    /*****开关配置相关逻辑*****/
    var saveConfig = function (config){
        var port =  chrome.runtime.connect({name: 'saveConfig'});
        port.postMessage(config);
        port.onMessage.addListener(function (message) {

        });
    };
    var config = localStorage.getItem('_config') ? JSON.parse(localStorage.getItem('_config')) : {};
    switchEvent('.switch-item', function (obj){
        var switchKey = obj.attr('data-key');
        var message = {};
        message[switchKey] = 1;
        config[switchKey] = 1; // 保存配置到localstorage中
        localStorage.setItem('_config', JSON.stringify(config));
        chrome.storage.sync.set(message, function () {
            sendMessageToContent(message);
        });
        saveConfig(config);
    }, function (obj){
        var switchKey = obj.attr('data-key');
        var message = {};
        message[switchKey] = 0;
        var keys = [];
        keys.push(switchKey);
        config[switchKey] = 0; // 保存配置到localstorage中
        localStorage.setItem('_config', JSON.stringify(config));
        chrome.storage.sync.set(message, function (){
            sendMessageToContent(message);
        });
    });
    //通知邮箱
    $(".ruleError").hide();
    console.log('ssssssssssssssssssssss');
    $("<div id='warning-dialog' style='display: none;'>操作失败</div>").appendTo("body");
   $(document).on("click", ".confirm-notification", function () {
      let value = $(".mailbox").val();
      // 基础邮箱校验
      function validateEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
      }

      // 使用
      if (validateEmail(value)) {
        $("ruleError").hide();
        chrome.storage.sync.get(["token"], function (result) {
          fetch(
            // "http://115.190.78.110:10010/user-center/browserPlugin/wbAppointmentStock/user/bindMessageEmail",
            "https://www.seerfar.cn/user-center/browserPlugin/wbAppointmentStock/user/bindMessageEmail",
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + result.token,
              },
              'body': JSON.stringify({'email':value})
            }
          )
            .then((data) => data.json())
            .then((res) => {
                if(res.code === 200){
                 $('.confirm-notification').hide()
                chrome.storage.sync.set({'messageEmail': value}) 
                }else{
            
                  if(res.code === 4001){
                      $('.confirm-notification').hide()
             
                   }else{
                        toastErrorMsg($('body'), res.msg  , true);
                   }
                }
            }).catch((err) => {
                  toastErrorMsg($('body'),err  , true);
                });
        });
      } else {
        $(".ruleError").show();
      }
    });
    $('.confirm-notification').hide()
     $(document).on("input", ".mailbox", function () {
         $('.confirm-notification').show()
     })
                // 获取当前用户的相关信息
    let getUserInfo = function (){
        return new Promise((resolve, reject) => {
            let userInfoPort = chrome.runtime.connect({name: 'userInfo'});
            userInfoPort.postMessage({'status': 1});
            userInfoPort.onMessage.addListener(function (message){
               $(".mailbox").val(message.userInfo?.messageEmail || ''   );
               console.log($(".mailbox").val(),'sssssssmailbox');
               
                resolve(message);
            });
            userInfoPort.disconnect;
        });

    };
    getUserInfo()
    //     let showModalTips = function (headerTitle, bodyContent, footerContent){
    //     let commonModal = $('#common-modal');
    //     commonModal.find('.modal-title').removeClass('text-start').addClass('text-center').html(headerTitle);
    //     commonModal.find('.modal-body').removeClass('text-start').addClass('text-center').html(bodyContent);
    //     commonModal.find('.modal-footer').removeClass('text-end').addClass('text-center').html(footerContent);
    //     commonModal.modal('show');
    // }
  
});