$(function (){
    class SellerBackend{
        constructor() {
            this.pageUrlObj = new URL(location.href);
            this.initLang();
        }
        getBrowserLang(){
            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';
                }
            }
            return navigatorLang;
        }
        initLang(){
            chrome.storage.sync.get(['ext_lang'], items => {
                this.changeLang(items.ext_lang || this.getBrowserLang());
            });
        }
        changeLang(lang, isAsync = false){
            chrome.storage.sync.set({'ext_lang':lang}, () => {
                this.sysLang = lang;
            });
            // 语言国际化
            this.getLangConfig(lang).then(res => {
                this.changeLangCallback(res, isAsync);
            });
        }
        getLangConfig(lang){
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: chrome.runtime.getURL('i18n/' + lang + '.json'),
                    success: (result) => {
                        resolve(result)
                    }
                });
            });
        }
        changeLangCallback(result, isAsync){
            this.propI18nTextList = result;
            // 普通文本类的
            $.each($('[data-i18n-text]'), (index, item) => {
                let attrName = $(item).attr('data-i18n-text');
                var value = this.propI18nText(attrName);
                if (value !== ''){
                    // 有值才替换
                    $(item).text(value);
                }
            });
            //HTML文本
            $.each($('[data-i18n-html]'), (index, item) => {
                let attrName = $(item).attr('data-i18n-html');
                let value = this.propI18nText(attrName);
                if (value !== ''){
                    $(item).html(value);
                }
            });
        }
        propI18nText(key){
            return this.propI18nTextList[key] || '';
        }
        waitForElement(layoutObj, selector){
            let mutationObserver = window.MutationObserver || window.webkitMutationObserver || window.MozMutationObserver;
            return new Promise(resolve => {
                if (document.querySelectorAll(selector).length > 0){
                    return resolve(document.querySelectorAll(selector));
                }
                let observer = new mutationObserver(mutations => {
                    if (document.querySelectorAll(selector).length > 0){
                        resolve(document.querySelectorAll(selector));
                        // observer.disconnect();
                    }
                });
                observer.observe(layoutObj, {
                    childList: true, // 子节点的变动（新增、删除或者更改）
                    /*attributes: true, // 属性的变动
                    characterData: true, // 节点内容或节点文本的变动*/
                    subtree: true, // 是否将观察器应用于该节点的所有后代节点
                });
            });
        }
        getUserInfo(){
            return new Promise((resolve, reject) => {
                let userInfoPort = chrome.runtime.connect({name: 'userInfo'});
                userInfoPort.postMessage({'status': 1});
                userInfoPort.onMessage.addListener(function (message){
                    resolve(message);
                });
                userInfoPort.disconnect;
            });
        }
        injectAdvTag(){
            let thisHandler = this;
            this.getUserInfo().then(response => {
                if (response.userInfo){
                    if (response.userInfo.hasOwnProperty('wbVip')){
                        chrome.storage.sync.set({'wbVip': response.userInfo.wbVip});
                    }
                    if (response.userInfo.hasOwnProperty('ozVip')){
                        chrome.storage.sync.set({'ozVip': response.userInfo.ozVip});
                    }
                    chrome.storage.sync.get(['ozCloseAdv', 'wbCloseAdv', 'reLogin', 'active', 'userId', 'ozVip', 'wbVip', 'ext_lang'], (items) => {
                        let logoImg = `chrome-extension://${chrome.i18n.getMessage("@@extension_id")}/img/seefarlogo-trans.png`;
                        let advTag = `
                   <div class="alert alert-info alert-dismissable fade in" role="alert" style="background-color: rgba(210,210,210,0.3);border: none;margin-top: 1rem;" id="sf-adv-tag">
                       <button type="button" class="close" data-dismiss="alert" aria-label="Close" id="close-adv-tag"><span aria-hidden="true">×</span></button>
                       <div class="d-flex align-items-center justify-content-between">
                           <div class="d-flex align-items-center" style="gap:10px">
                               <img src="${logoImg}" style="width:150px;">
                               <div class="flex-fill" style="line-height: 1.5;color: #000;">
                                   <div style="font-size: 16px;font-weight: bold;" data-i18n-text="tag_title">${this.propI18nText('tag_title')}</div>
                                   <div style="font-size: 14px;" data-i18n-text="tag_sub_title">${this.propI18nText('tag_sub_title')}</div>
                               </div>
                           </div>
                           <div class="col-auto">
                              <button class="btn btn-primary" data-i18n-text="learn_more" id="learn-more-btn">${this.propI18nText('learn_more')}</button>
                           </div>
                       </div>
                   </div>
                `;
                        if ((!items.reLogin || items.reLogin !== 1) && items.userId && items.active === 1){
                            if (this.pageUrlObj.host.includes('wildberries')){
                                //WB 卖家后台逻辑
                                if (!items.wbCloseAdv && !items.wbVip){
                                    this.waitForElement($('#root')[0], '.HeaderView__container').then(headerViewRes => {
                                        if (headerViewRes && headerViewRes.length){
                                            $(headerViewRes).after(advTag);
                                        }
                                    });
                                }
                            }else if (this.pageUrlObj.host.includes('ozon')){
                                let isDashboard = this.pageUrlObj.pathname.includes('app/dashboard');
                                let layoutObj = isDashboard ? $('#layoutPage')[0] : $('#app')[0];
                                let findSelector = isDashboard ? '[data-widget="menu"]' : '[data-widget="header"]';
                                //OZON卖家后台逻辑
                                if (!items.ozCloseAdv && !items.ozVip){
                                    this.waitForElement(layoutObj, findSelector).then(headerViewRes => {
                                        if (headerViewRes && headerViewRes.length){
                                            isDashboard ? $(headerViewRes).after(advTag) : $(headerViewRes).append(advTag);
                                        }
                                    });
                                }
                            }
                            //记录关闭信息
                            $(document).on('click', '#close-adv-tag', function (){
                                if (thisHandler.pageUrlObj.host.includes('wildberries')){
                                    chrome.storage.sync.set({'wbCloseAdv': true});
                                }else if (thisHandler.pageUrlObj.host.includes('ozon')){
                                    chrome.storage.sync.set({'ozCloseAdv': true});
                                }
                            });
                            $(document).on('click', '#learn-more-btn', function (){
                                chrome.storage.sync.get(['ext_lang'], (items) => {
                                    let webSiteMap = {
                                        'zh': 'https://www.seerfar.cn',
                                        'en': 'https://www.seerfar.com',
                                        'ru': 'https://www.seerfar.ru',
                                    };
                                    window.open(webSiteMap[items.ext_lang]);
                                });
                            });
                        }
                    });
                }else {

                }
            });
        }
        removeAdvTag(){
            $('#sf-adv-tag').remove();
        }
        run(){
            let timer;
            timer = setInterval(() => {
                if (this.propI18nTextList){
                    clearInterval(timer);
                    this.injectAdvTag();
                }
            }, 100);
            //监听消息通信
            chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
                if (message.active && message.active === 1){
                    this.injectAdvTag();
                }else if (message.active === 0 || message.logout === 1) {
                    this.removeAdvTag();
                }
                //从option页面传递的消息
                if (message.changeLang === 1 && message.lang){
                    this.changeLang(message.lang, true);
                }
            });
        }
    }
    let backendObj = new SellerBackend();
    backendObj.run();
});