$(function (){
    class wbServer {
        // 构造方法
        constructor() {
            wbServer.BASE_URL = 'https://www.seerfar.com';
            wbServer.CN_BASE_URL = 'https://www.seerfar.cn';
            wbServer.RU_BASE_URL = 'https://www.seerfar.ru';
            wbServer.EXT_VERSION = parseInt(chrome.runtime.getManifest().version.replaceAll('.', ''));// 插件当前版本
            wbServer.API_HOST = 'https://www.seerfar.cn';
            // wbServer.API_HOST = 'http://115.190.78.110:10010';

            this.isGlobalSite = location.href.includes('global.wildberries');
            this.productColumns = ['product_info', 'sku', 'brand', 'category', 'price', 'sales', 'revenue', 'inventory', 'creation_date', 'ratings', 'review_count', 'q_and_a', 'seller', 'volume'];
            this.isVip = false;
            this.isVipOz = false;
            this.isSub = false;
            this.hasShopCredit = false;
            this.hasShopCreditOz = false;
            this.logoDrag = false;
            this.mainOffStatus = false;
        }
        /****工具类方法****/
        setCookie(name, value, expires = 0, path = ''){
            let expireTime = '', savePath = '';
            if (expires){
                expireTime = ';expires=' + expires;
            }
            if (path){
                savePath = ';path=' + path;
            }
            document.cookie = name + "=" + escape(value) + expireTime + savePath;
        }
        getCookie(name){
            if (document.cookie.length > 0) {
                var c_start = document.cookie.indexOf(name + "=");
                if (c_start != -1) {
                    c_start = c_start + name.length + 1;
                    var c_end = document.cookie.indexOf(";", c_start);
                    if (c_end == -1) c_end = document.cookie.length;
                    return unescape(document.cookie.substring(c_start, c_end));
                }
            }
            return "";
        }
        //Toast成功和失败提示
        toastSuccessMsg(container, content, isBody = false){
            let toastOptions = {
                'background': '#fff',
                'color': '#000',
                'duration': 1500,
                'content': `<div class="d-flex align-items-center"><span class="fa fa-check" style="color:green;font-size:1.2rem;margin-right:5px"></span>${content}</div>`
            };
            if (isBody){
                toastOptions = {...toastOptions, 'position':'fixed'};
            }
            container.toast(toastOptions);
        };
        toastErrorMsg(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);
        };
        assignStatData(records){
            let productData = this.productTableObj.bootstrapTable('getData');
            let num = 0, totalSales = 0, totalPrice = 0, totalReviews = 0;
            num = productData.length;
            if (_.isArray(productData)){
                productData.forEach((item, index) => {
                    if (item.sales || item.sales !== '-'){
                        totalSales += item.sales;
                    }
                    if (!_.isNaN(parseFloat(item.price))){
                        totalPrice = _.add(totalPrice, parseFloat(item.price));
                    }
                    if (item.reviewCount !== null && item.reviewCount !== '-'){
                        totalReviews += parseInt(item.reviewCount);
                    }
                });
            }
            $('#products').text(num);
            $('#sales-total').text(totalSales);
            $('#price-avg').text(num ? _.round(_.divide(totalPrice, num), 2) : 0);
            $('#review-count-avg').text(num ? _.round(_.divide(totalReviews, num), 2) : 0);
        }
        /****工具类方法end****/
        // 获取当前浏览器的语言
        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;
        }
        getLangConfig(lang){
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: chrome.runtime.getURL('i18n/' + lang + '.json'),
                    success: (result) => {
                        resolve(result)
                    }
                });
            });
        }
        changeLang(lang, isAsync = false){
            chrome.storage.sync.set({'ext_lang':lang}, () => {
                this.sysLang = lang;
            });
            // 语言国际化
            this.getLangConfig(lang).then(res => {
                this.changeLangCallback(res, isAsync);
            });
        }
        initLang(){
            chrome.storage.sync.get(['ext_lang'], items => {
                this.changeLang(items.ext_lang || this.getBrowserLang());
            });
        }
        initGetExtLang(items){
            var ext_lang = items.ext_lang ? items.ext_lang : this.getBrowserLang();
            this.changeLang(ext_lang);
            window.ext_lang = ext_lang;
        }
        changeLangCallback(result, isAsync){
            window.propI18nTextList = result;
            if (isAsync){
                let tableOptions = this.getDataTableOptions(this.sysLang);
                let locale = tableOptions[0];
                let showRowText = tableOptions[1];
                let perPageText = tableOptions[2];
                let noMatchText = tableOptions[3];
                let refreshOptions = {
                    locale: locale,
                    formatShowingRows: showRowText,
                    formatRecordsPerPage: perPageText,
                    formatNoMatches: noMatchText
                };
                wbServerObj.productTableObj.bootstrapTable('refreshOptions', refreshOptions);
                if (window.mapRecords){
                    this.assignStatData(window.mapRecords);
                }
                if (this.minerTableObj.bootstrapTable('getOptions').columns){
                    this.minerTableObj.bootstrapTable('refreshOptions', refreshOptions);
                }
                if (this.reverseTableObj.bootstrapTable('getOptions').columns){
                    this.reverseTableObj.bootstrapTable('refreshOptions', refreshOptions);
                }
            }
            // 普通文本类的
            $.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);
                }
            });
            //placeholder
            $.each($('[data-i18n-placeholder]'), (index, item) => {
                var attrName = $(item).attr('data-i18n-placeholder');
                var value = this.propI18nText(attrName);
                if (value !== ''){
                    // 有值才替换
                    $(item).attr('placeholder', value);
                }
            });
            // tips
            $.each($('[data-tips]'), (index, item) => {
                var attrName = $(item).attr('data-tips');
                var value = this.propI18nText(attrName);
                if (value !== ''){
                    // 有值才替换
                    $(item).attr('data-original-title', value);
                    $(item).attr('title', value);
                }
            });
            
            $('.product-category').each((index, item) => {
                let cnName = $(item).attr('data-cn-name');
                let enName = $(item).attr('data-en-name');
                let ruName = $(item).attr('data-ru-name');
                let cnPath = $(item).attr('data-cn-path');
                let enPath = $(item).attr('data-en-path');
                let ruPath = $(item).attr('data-ru-path');
                let newTips = '';
                let categoryLangNameMap = {'zh':cnName, 'en':enName, 'ru':ruName};
                //  $(item).text(categoryLangNameMap[this.sysLang]);
               // 判断元素类型并处理
                if ($(item).is('a')) {
                  // 如果本身就是 a 标签，直接替换文本
                      $(item).text(categoryLangNameMap[this.sysLang]);
                 } else {
                 // 如果是其他元素，查找内部的 a 标签
                     $(item).find('a').text(categoryLangNameMap[this.sysLang]);
                   }
                switch (this.sysLang){
                    case 'zh':
                        newTips = ruPath !== undefined && cnPath !== undefined ? `<div class="text-start">${ruPath}<br/>${cnPath}</div>` : '';
                        break;
                    case 'en':
                        newTips = ruPath !== undefined && enPath !== undefined ? `<div class="text-start">${ruPath}<br/>${enPath}</div>` : '';
                        break;
                    case 'ru':
                        newTips = ruPath !== undefined ? `<div class="text-start">${ruPath}</div>` : '';
                        break;
                }
            });
            this.productTableObj.bootstrapTable('resetView');
            //更改趋势图表语言
            let chartList = ['search-trend-charts', 'google-trend-charts', 'yandex-trend-charts'];
            chartList.forEach((chartId, index) => {
                if ($(`#${chartId}`).length){
                    let chart = echarts.init(document.getElementById(chartId));
                    let chartOption = chart.getOption();
                    if (chartOption){
                        let newLegend, newSeries, newYaxis;
                        switch (chartId) {
                            case 'search-trend-charts':
                                newLegend = [this.propI18nText('search_volume_new')];
                                break;
                            case 'google-trend-charts':
                                newLegend = [this.propI18nText('search_index')];
                                break;
                            case 'yandex-trend-charts':
                                newLegend = [this.propI18nText('request_number'), this.propI18nText('share_of_all_queries')];
                                break;
                        }
                        chartOption.legend[0]['data'] = newLegend;
                        newLegend.forEach((item, index) => {
                            chartOption.series[index]['name'] = item;
                            chartOption.yAxis[index]['name'] = item;
                        });
                        chart.setOption(chartOption);
                    }
                }
            });
            //更改找货源下拉选项文本语言
            let sourceSelectList = [
                {'id':'experience-score', 'placeholder':this.propI18nText('overall_experience_score')},
                {'id':'one-day-collect-rate', 'placeholder':this.propI18nText('hour_collect_rate').replace('{hour}', 24)},
                {'id':'two-days-collect-rate', 'placeholder':this.propI18nText('hour_collect_rate').replace('{hour}', 48)}
            ];
            sourceSelectList.forEach(item => {
                let selectItem = $(`#${item.id}`);
                selectItem.selectpicker({
                    'noneSelectedText':item.placeholder
                });
                selectItem.selectpicker('refresh');
            });
        }
        propI18nText(key){
            return window.propI18nTextList[key] || '';
        }
        // 获取验证码信息
        getCaptcha(){
            // 建立长链接
            let captchaPort = chrome.runtime.connect({name: 'captcha'});
            captchaPort.postMessage({'status': 1}); // 发送消息
            // 监听回复
            captchaPort.onMessage.addListener(function (message){
                if (message.data){
                    $('#captchaId').val(message.data.captchaId);
                    $('#captcha').attr('src', message.data.img);
                }
            });
            captchaPort.disconnect;
        }
        // 获取表单对象
        getFormObj(formArr){
            var obj = {};
            $.each(formArr, function (key, item){
                obj[item.name] = item.value;
            });
            return obj;
        }
        // Modal框弹出相关提示信息
        showModalTips(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');
        }
        showModalContent(headerTitle, bodyContent, footerContent){
            let commonModal = $('#common-modal');
            commonModal.find('.modal-title').removeClass('text-center').addClass('text-start').html(headerTitle);
            commonModal.find('.modal-body').removeClass('text-center').addClass('text-start').html(bodyContent);
            commonModal.find('.modal-footer').removeClass('text-center').addClass('text-end').html(footerContent);
            commonModal.modal('show');
        }
        userLogin(params){
            var port = chrome.runtime.connect({name: 'login'});
            let portParams = params.formObj;
            if (params.captchaVO){
                portParams = {...portParams, 'captchaVO':params.captchaVO};
            }
            port.postMessage(portParams); // 发送消息
            // 登录验证前新增loading加载效果
            params.signInBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-pulse"></i>');
            // 监听回复
            port.onMessage.addListener((message) => {
                // 取消禁用和loading
                params.signInBtn.prop('disabled', false).html(this.propI18nText('login'));
                if (message.userInfo){
                    console.log('登录信息',message.userInfo);
                    
                    // 记录userid/username/token/wbVip信息,同时记录上次登录的账号密码信息，便于下次登录进行回填操作
                    chrome.storage.sync.set({'userId': message.userInfo.userId, 'username': message.userInfo.userName, 'token': message.userInfo.token, 'wbVip': message.userInfo.wbVip, 'ozVip': message.userInfo.ozVip, 'loginAccount': params.formObj['account'], 'loginPass': params.formObj['password'],'isSub': message.userInfo.isSub,'messageEmail':message.userInfo.messageEmail}, () =>{
                        chrome.storage.sync.remove(['reLogin']);
                        this.isVip = message.userInfo.wbVip;
                        this.hasShopCredit = message.userInfo.hasWbShopCredit;
                        this.hasShopCreditOz = message.userInfo.hasOzShopCredit;
                        this.isSub = message.userInfo.isSub;
                        $('.sign-in-container').css('bottom', '-500px');
                        // 清空登录表单选项
                        $('#sign-in-form').trigger('reset');
                        $('.main-off').css('z-index', '1000000');
                        if (this.isDetailPage){
                            this.detailRequested = false;
                        }
                        this.mainOffStatus = false;
                    });
                }else if (message.errorCode){
                    let accountInput = $('#sign-in-username'), passInput = $('#sign-in-pass'), captchaInput = $('input[name="captcha"]');
                    switch (parseInt(message.errorCode)){
                        case 4006:
                        case 4010:
                        case 4028:
                        case 400:
                            // 账号或者密码错误
                            passInput.parent().addClass('is-invalid').after(`<div class="invalid-feedback" data-i18n-text="account_info_error">${this.propI18nText('account_info_error')}</div>`);
                            break;
                        case 4007://账号已被禁用
                            accountInput.parent().addClass('is-invalid').after(`<div class="invalid-feedback" data-i18n-text="user_not_active">${this.propI18nText('user_not_active')}</div>`);
                            break;
                        case 4008://账号需要审核
                            accountInput.parent().addClass('is-invalid').after(`<div class="invalid-feedback" data-i18n-text="user_must_review">${this.propI18nText('user_must_review')}</div>`);
                            break;
                        case 4025:// 子账号已过期
                            accountInput.parent().addClass('is-invalid').after(`<div class="invalid-feedback" data-i18n-text="sub_account_expired">${this.propI18nText('sub_account_expired')}</div>`);
                            break;
                        case 4029:
                        case 4018:
                            //没有子账号权限
                            let mainUsername = message.data;
                            accountInput.parent().addClass('is-invalid').after(`<div class="invalid-feedback" data-i18n-text="sub_user_has_deactivated">${this.propI18nText('sub_user_has_deactivated')}</div>`);
                            $('.main-username').text(mainUsername);
                            break;
                        case 4053:
                            // 系统维护
                            wbServerObj.showModalTips(this.propI18nText('warm_tips'), message.msg, '<button class="btn btn-primary" style="background-color: #9E15BF;border-color: #9E15BF;" data-dismiss="modal">'+this.propI18nText('got_it')+'</button>');
                            break;
                        case 4041://密码错误次数过多
                            passInput.parent().addClass('is-invalid').after(`<div class="invalid-feedback" data-i18n-text="incorrect_password_more_tips">${this.propI18nText('incorrect_password_more_tips')}</div>`);
                            break;
                        case 4002://验证码错误
                            captchaInput.parent().parent().next('.invalid-feedback').remove();
                            captchaInput.addClass('is-invalid').parent().parent().after(`<div class="invalid-feedback d-block" data-i18n-text="captcha_error">${this.propI18nText('captcha_error')}</div>`);
                            break;
                        case 4042:
                            //需要图片滑动二次验证
                            this.showPictureCaptcha($('#signInBtn'), $('#slide-captcha-container'), (res) => {
                                this.userLogin({
                                    'signInBtn': params.signInBtn,
                                    'formObj': portParams,
                                    'captchaVO': {
                                        'captchaVerification': res.captchaVerification
                                    }
                                });
                            });
                            break;
                        case 4065:
                            wbServerObj.showModalTips(this.propI18nText('warm_tips'), message.msg, '<button class="btn btn-primary" style="background-color: #9E15BF;border-color: #9E15BF;" data-dismiss="modal">'+this.propI18nText('got_it')+'</button>');
                            break;
                        default:
                            captchaInput.parent().parent().next('.invalid-feedback').remove();
                            captchaInput.addClass('is-invalid').parent().parent().after(`<div class="invalid-feedback d-block" data-i18n-text="system_busy_tips">${this.propI18nText('system_busy_tips')}</div>`);
                    }
                }
                // this.getCaptcha();
            });
            port.disconnect;
        }
        showPictureCaptcha(containerId, captchaObj, successCallback){
            let option = {
                baseUrl: `${wbServer.API_HOST}/user-center/browserPlugin`,
                containerId: containerId,//pop模式 必填 被点击之后出现行为验证码的元素id
                mode:'pop',//展示模式
                imgSize : {//图片的大小对象,有默认值{ width: '310px',height: '155px'},可省略
                    width: '400px',
                    height: '200px',
                },
                barSize:{//下方滑块的大小对象,有默认值{ width: '310px',height: '50px'},可省略
                    width: '400px',
                    height: '40px',
                },
                explain: this.propI18nText('swipe_right_verify'),
                title: this.propI18nText('complete_security_verify'),
                successText: this.propI18nText('valid_success'),
                failText: this.propI18nText('valid_fail'),
                success: successCallback
            };
            try{
                if (this.sysLang === 'zh'){
                    //中文环境下随机切换
                    let num = _.random(0, 1);
                    let actionMap = new Map([
                        [0, () => {
                            captchaObj.slideVerify(option);
                        }],
                        [1, () => {
                            captchaObj.pointsVerify(option);
                        }],
                        ['default', () => {
                            captchaObj.slideVerify(option);
                        }]
                    ]);
                    let action = actionMap.get(num) || actionMap.get('default');
                    action.call(this);
                }else{
                    //默认都是滑动验证
                    captchaObj.slideVerify(option);
                }
            }catch(error){
                console.log(error);
            }
        }
        // 生成插件相关页面元素
        createPage(){
            let mainPluginConfig = {'id': 'main-plugin'};
            if (this.isGlobalSite){
                mainPluginConfig['class'] = 'wb-global-sf';
            }
            const mainPlugin = $('<div>', mainPluginConfig);
            const logoBtn = $('<div>', {'class': 'logo-btn'});
            const loadingImgUrl = chrome.runtime.getURL('assets/images/loading/loading.gif');
            // 登录页面
            const signInContainer = $('<div>', {'class': 'sign-in-container'});
            signInContainer.append(
                $('<button>', {'class': 'sign-in-close'}).append($('<span>').append(
                    $('<i>', {'class': 'fa fa-close'})
                )),
                $('<div>', {'class': 'sign-in-card-box'}).append(
                    $('<img>', {'src': 'chrome-extension://' + chrome.i18n.getMessage("@@extension_id") + '/img/seefarlogo-trans.png', 'class': 'sign-in-logo'}),
                    $('<form>', {'id': 'sign-in-form', 'method': 'post', 'onsubmit': 'return false;'}).append(
                        // 账号input
                        $('<div>', {'class': 'form-ext-control d-flex'}).append(
                            $('<i>', {'class': 'fa fa-user input-icon'}),
                            $('<input>', {'type': 'text', 'class': 'form-control u-form-input', 'autofocus': 'true', 'id': 'sign-in-username', 'data-i18n-placeholder': 'login_account', 'name': 'account'})
                        ),
                        // 密码input
                        $('<div>', {'class': 'form-ext-control d-flex', 'style': 'margin-top:15px'}).append(
                            $('<i>', {'class': 'fa fa-lock input-icon'}),
                            $('<input>', {'type': 'password', 'class': 'form-control u-form-input', 'id': 'sign-in-pass', 'data-i18n-placeholder': 'password', 'name':'password'}),
                            //密码显示或隐藏
                            `<a href="javascript:void(0);" class="show-pass text-primary"><i class="fa fa-eye-slash"></i></a>`
                        ),
                        //图片滑动验证码区域
                        `<div id="slide-captcha-container" style="z-index: 3000;"></div>`,
                        // 找回密码
                        $('<div>', {'class': 'd-flex align-items-center'}).append(
                            $('<p>', {'class': 'd-flex-1 text-ext-danger show-ellipsis-nowrap'}),
                            $('<a>', {'class': 'cursor-pointer find-pass', 'style': 'margin-top: 10px;', 'data-i18n-text': 'forget_password', 'href': 'javascript:void(0)', 'id': 'forget-password'})
                        ),
                        // 登录按钮
                        $('<button>', {'class': 'btn btn-primary w-100', 'style': 'margin-top:15px;background-color:#9E15BF;border-color:#9E15BF;color:#fff;', 'data-i18n-text': 'login', 'type': 'button', 'id': 'signInBtn'}),
                        // 注册链接
                        $('<a>', {'href': 'javascript:void(0);', 'style': 'margin-top:15px;display:block;color:#9E15BF;text-decoration:underline !important;', 'data-i18n-text': 'register_now', 'id': 'reg-now'})
                    ),
                ),
                // 语言选择
                $('<div>', {'class': 'change-lang-box sign-in-lang-box'}).append(
                    $('<select>', {'class': 'form-control change-lang'}).append(
                        $('<option>', {'value':'zh', 'data-content': '<span class="dropdown-flag flag-icon flag-icon-cn"></span>中文(简体)'}).append('<span class="dropdown-flag flag-icon flag-icon-cn"></span>中文(简体)'),
                        $('<option>', {'value':'en', 'data-content': '<span class="dropdown-flag flag-icon flag-icon-us"></span>English'}).append('<span class="dropdown-flag flag-icon flag-icon-us"></span>English'),
                        $('<option>', {'value':'ru', 'data-content': '<span class="dropdown-flag flag-icon flag-icon-ru"></span>Русский'}).append('<span class="dropdown-flag flag-icon flag-icon-ru"></span>Русский'),
                    )
                )
            );
            mainPlugin.append(signInContainer);

            const page = $('<div>', {'class': 'main-off d-none'}).append(
                logoBtn
            );
            mainPlugin.append(page);

            //公共的modal框
            let commonModal = $('<div>', {'class': 'modal fade', 'id': 'common-modal', 'tabindex':'-1', 'role': 'dialog', 'aria-labelledby': 'common-modal'}).append(
                $('<div>', {'class': 'modal-dialog modal-dialog-centered'}).append(
                    $('<div>', {'class': 'modal-content', 'style':'top:180px;'}).append(
                        $('<div>', {'class': 'modal-header', 'style': 'border-bottom: none;'}).append(
                            $('<button>', {'type': 'button', 'class': 'close', 'data-dismiss': 'modal', 'aria-hidden': true, 'style': 'font-size: 35px'}).html('&times'),
                            $('<h4>', {'class': 'modal-title font-weight-bold text-center', 'style': 'line-height: 2;'})
                        ),
                        $('<div>', {'class': 'modal-body', 'style': 'line-height: 2'}),
                        $('<div>', {'class': 'modal-footer', 'style': 'border-top: none;'})
                    )
                )
            )
            chrome.storage.sync.get(['logoBtnTop'], (items) => {
                if (items.logoBtnTop !== undefined){
                    $('.main-off').css('top', `${items.logoBtnTop}px`);
                }
            });
            $('body').append(mainPlugin);
            mainPlugin.next().after(commonModal);
            this.createCustomColumnsList();
            this.initCustomColumn();
            this.initLang();
            if (!this.isGlobalSite){
                $('.fa-question-circle').tooltip();
            }
            $('.sign-in-lang-box .change-lang').selectpicker();
            $('.main-box-footer .change-lang').selectpicker();
            this.productTableObj = $('#product-table');
            this.reverseTableObj = $('#keyword-reverse-table');
            this.minerTableObj = $('#keyword-miner-table');
            // this.getCaptcha();
        }
        //开启/关闭自定义列
        createCustomColumnsList(){
            // 构造自定义列数据
            this.productColumns.forEach(column => {
                let checkboxObj = {'type': 'checkbox', 'class': 'form-check-input cursor-pointer column-check'};
                if (column == 'product_info' || column === 'sku'){
                    checkboxObj['disabled'] = true;
                    checkboxObj['checked'] = true;
                }
                $('.custom_column_content').append(
                    $('<label>', {'class': 'form-check'}).append(
                        $('<input>', checkboxObj),
                        $('<span>', {'class': 'form-check-label', 'data-i18n-text': column}).append(column),
                    ),
                );
            });
        }
        // 初始化自定义列选中状态
        initCustomColumn(){
            chrome.storage.sync.get(['customColumns'], items => {
                if (items.customColumns){
                    var customColumns = items.customColumns;
                    $('.column-check:not(:disabled)').each(function (index, item){
                        if ($.inArray($(item).next().attr('data-i18n-text'), customColumns) >= 0){
                            $(item).prop('checked', true);
                        }else{
                            $(item).prop('checked', false);
                        }
                    });
                    if ($('.column-check:checked').length === wbServerObj.productColumns.length){
                        $('#select-all').prop('checked', true);
                    }
                }else{
                    if (items.customColumns !== null){ // 默认全部字段可查看
                        $('#select-all').prop('checked', true);
                        $('.custom_column_content').find('.column-check:not(:disabled)').prop('checked', true);
                    }else{
                        $('#select-all').prop('checked', false);
                        $('.custom_column_content').find('.column-check:not(:disabled)').prop('checked', false);
                    }
                }
            });
        }
        //插件版本过低提示
        versionUpdateContent(){
            let updateBox = $('<div>', {'id': 'update-extension'});
            let extUpdateUrlMap = {
                'zh': `${ wbServer.CN_BASE_URL}/seerfar-chrome-extension-download/`,
                'en': `${ wbServer.BASE_URL}/seerfar-chrome-extension-download/`,
                'ru': `${ wbServer.RU_BASE_URL}/seerfar-chrome-extension-download/`
            };
            let extensionUpdateUrl = extUpdateUrlMap[this.sysLang] || extUpdateUrlMap['en'];
            let updateContent = $('<div>', {'class': 'box-card', 'style': 'top: 30%;width: auto;'});
            updateContent.append(
                $('<div>', {'class': 'update-extension-header'}).append(
                    $('<span>', {'class': 'update-extension-header-icon'}),
                    $('<h3>', {'style': 'margin-left:55px', 'data-i18n-text': 'extension_update'}).append(this.propI18nText('extension_update'))
                ),
                $('<div>', {'class': 'update-extension-body'}).append(
                    $('<p>', {'data-i18n-text': 'extension_update_tips'}).append(this.propI18nText('extension_update_tips'))
                ),
                $('<div>', {'class': 'update-extension-footer'}).append(
                    $('<a>', {'class': 'btn btn-primary', 'data-i18n-text': 'check_and_update', 'href': extensionUpdateUrl, 'target': '_blank'}).append(this.propI18nText('check_and_update'))
                )
            );
            updateBox.append(updateContent);
            return updateBox;
        }
        // 获取当前用户
        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;
            });
        }
        searchTableProducts(skuList){
            let postMessage = {'skuList': skuList, 'platform': 'wb'};
            return new Promise((resolve, reject) => {
                let quickViewPort = chrome.runtime.connect({name: 'getProductInfo'});
                quickViewPort.postMessage(postMessage);
                quickViewPort.onMessage.addListener(function (message){
                    resolve(message);
                });
                quickViewPort.disconnect;
            });
        }
        // logo浮标点击事件
        clickPluginLogo(){
            $('.main-off').trigger('click');
        }
        mainOffClickCallback(){
            if (!this.logoDrag && !this.mainOffStatus){
                $('.sales-trend, .review-analysis, .card-rating').popover('hide');
                $('#profit-calculator').empty();
                $('#collect-box').remove();
                $('#source-goods-box').parent().remove();
                $('html').removeClass('overflow-hidden');
                $('#search-trends-box').remove();
                $('.main-off').css('z-index', '100000');
                chrome.storage.sync.get(['userId', 'reLogin', 'loginAccount', 'loginPass', 'wbVip'], (items) => {
                    if (!items.userId || items.reLogin == 1){
                        $('.sign-in-container').css('bottom', '0px');
                        if (items.loginAccount && items.loginPass){
                            // 账号密码回显
                            $('#sign-in-username').val(items.loginAccount);
                            $('#sign-in-pass').val(items.loginPass);
                        }
                    }else{
                        $('.ext-main-container').css({'bottom': '0px', 'height': 'calc(100% - 94px)'});
                        $('.main-box-footer').show();
                        if (!items.wbVip){
                            $('.main-box-footer .export-details').addClass('disabled pointer-events-none');
                            return false;
                        }
                    }
                });
            }
        }
        removeRenderAttr(){
            $(document).find('div.data-seerfar-render').each((index, item) => {
                $(item).removeClass('data-seerfar-render')
            });
            $(document).find('article.data-seerfar-render').each((index, item) => {
                $(item).removeClass('data-seerfar-render')
            });
        }
        removeExtension(){
            $('#main-plugin').remove();
            $('.advert-tag').remove();
            $('.popover').remove();
            $('#profit-calculator').remove();
            $('#common-modal').remove();
            $('#update-extension').remove();
            $('#collect-box').remove();
            $('#source-goods-box').parent().remove();
            $('html').removeClass('overflow-hidden');
            $('#search-trends-box').remove();
            delete this.detailRequested;
            this.removeRenderAttr();
        }
        // 消息通信监听
        messageListenCallback(message, sender, sendResponse){
            let _this = this;
            if (message.active && message.active === 1){
                chrome.storage.sync.get(['userId', 'extSearchReview', 'extDetailReview', 'ext_lang'], items => {
                    _this.createPage();
                    $(document).find('.change-lang').selectpicker('val', items.ext_lang ? items.ext_lang : this.getBrowserLang());
                    // 建立长链接
                    let sysPort = chrome.runtime.connect({name: 'sysConfig'});
                    sysPort.postMessage({'status': 1}); // 发送消息
                    // 监听回复
                    sysPort.onMessage.addListener(function (message){
                        // 先验证版本号
                        if (message.data && message.data.minAvailablePluginVersion){
                            let minVersion = parseInt(message.data.minAvailablePluginVersion.replaceAll('.', ''));
                            if (wbServer.EXT_VERSION < minVersion){
                                // 低版本强制弹窗更新
                                $('#profit-calculator').after(_this.versionUpdateContent());
                            }else{
                                _this.getUserInfo().then(response => {
                                    if (response.userInfo){
                                        if (response.userInfo.hasOwnProperty('wbVip')){
                                            chrome.storage.sync.set({'wbVip': response.userInfo.wbVip,'ozVip': response.userInfo.ozVip});
                                            _this.isVip = response.userInfo.wbVip;
                                            _this.isVipOz = response.userInfo.ozVip;
                                            _this.hasShopCredit = response.userInfo.hasWbShopCredit;
                                            _this.hasShopCreditOz = response.userInfo.hasOzShopCredit;
                                            _this.isSub = response.userInfo.isSub;
                                        }
                                    }else{
                                        switch (response.errorCode){
                                            case 401:
                                                break;
                                            case 429:
                                                $('#profit-calculator').after(`<div class="alert alert-danger alert-dismissible fade in warning-tips" role="alert" style="position: fixed;z-index: 99999;top:100px;left: 40%;color:#fff;background-color: rgba(0, 0, 0, 0.8);border-color: rgba(0, 0, 0, 0.8)"><span style="font-weight: 700;">${this.propI18nText('request_frequently_tips')}</span></div>`);
                                                setTimeout(function (){
                                                    $('.warning-tips').alert('close');
                                                }, 3000);
                                                break;
                                        }
                                    }
                                });
                            }
                        }else{
                            if (items.userId){
                                // 有登录且开启了开关才查询数据
                                if ((items.extSearchReview == undefined || items.extSearchReview == 1) && contentScriptCondition){
                                    newQuickView();
                                }
                                if ((items.extDetailReview == undefined || items.extDetailReview == 1) && detailPageCondition){
                                    quickView();
                                }
                            }
                        }
                    });
                    sysPort.disconnect;
                });
            }else if (message.active === 0 || message.logout === 1){
                if (message.active === 0){
                    // 禁用插件，移除插件相关内容
                    this.removeExtension();
                }else{
                    if (message.logout === 1){
                        // 用户退出登录
                        if ($('.ext-main-container').css('bottom') == '0px'){
                            $('.close-plugin').trigger('click');
                        }
                    }
                }
            }
            // 显示下滑页面(登录或产品查询)
            if (message.showMainBox && message.showMainBox === 1){
                _this.clickPluginLogo();
            }
            // 监听页面API响应回调
            if (message.actionId) {
                switch (message.actionId){
                    case 'productList'://获取WB接口响应的商品数据
                        $('.main-off').removeClass('d-none');
                        if (message.currency){
                            if (this.pageCurrency && this.pageCurrency !== message.currency.toUpperCase()){
                                this.pageCurrency = message.currency.toUpperCase();
                                location.reload();
                            }else{
                                this.pageCurrency = message.currency.toUpperCase();
                            }
                        }
                    break;
                }
            }
            //从option页面传递的消息
            if (message.changeLang === 1 && message.lang){
                this.changeLang(message.lang, true);
                $('.change-lang-box select').selectpicker('val', message.lang);
            }
            if (message.userLogin && message.userLogin === 1){
                $('.sign-in-close').trigger('click');
            }
        }
        run(){
            chrome.storage.sync.remove(['wbTabUrl']);
            chrome.storage.sync.get(['userId', 'active', 'extSearchReview', 'extDetailReview'], items => {
                let _this = this;
                if (items.active === 1){
                    _this.createPage();
                    // 建立长链接
                    let sysPort = chrome.runtime.connect({name: 'sysConfig'});
                    sysPort.postMessage({'status': 1}); // 发送消息
                    // 监听回复
                    sysPort.onMessage.addListener((message, port) => {
                        if (message.data && message.data.minAvailablePluginVersion){
                            let minVersion = parseInt(message.data.minAvailablePluginVersion.replaceAll('.', ''));
                            if (wbServer.EXT_VERSION < minVersion){
                                $('#profit-calculator').after(_this.versionUpdateContent());
                            }else{
                                _this.getUserInfo().then(response => {
                                    if (response.userInfo){
                                        if (response.userInfo.hasOwnProperty('wbVip')){
                                            chrome.storage.sync.set({'wbVip': response.userInfo.wbVip,'ozVip': response.userInfo.ozVip});
                                            _this.isVip = response.userInfo.wbVip;
                                            _this.isVipOz = response.userInfo.ozVip;
                                            _this.hasShopCredit = response.userInfo.hasWbShopCredit;
                                            _this.hasShopCreditOz = response.userInfo.hasOzShopCredit;
                                            _this.isSub = response.userInfo.isSub;
                                        }
                                    }else if (response.errorCode){
                                        switch (response.errorCode){
                                            case 401:
                                                chrome.storage.sync.get(['is_close'], function (items){
                                                    if (!items.is_close){
                                                        _this.clickPluginLogo();
                                                    }
                                                });
                                                break;
                                        }
                                    }
                                });
                            }
                        }
                    });
                    sysPort.disconnect;
                }
            });
            // 消息通信监听
            chrome.runtime.onMessage.addListener(this.messageListenCallback.bind(this));
        }
    }
    var wbServerObj = new wbServer();
    wbServerObj.run();
    $(document).off('click', '.upgrade').on('click', '.upgrade', function (){
        let pricingUrlMap = {
            'zh': `${wbServer.CN_BASE_URL}/pricing/`,
            'en': `${wbServer.BASE_URL}/pricing/`,
            'ru': `${wbServer.RU_BASE_URL}/pricing/`,
        };
        let pricingUrl = pricingUrlMap[wbServerObj.sysLang] || pricingUrlMap['en'];
        $(this).blur();
        window.open(pricingUrl);
    });
    // 点击插件浮标触发事件
    $(document).off('click', '.main-off').on('click', '.main-off', wbServerObj.mainOffClickCallback.bind(wbServerObj)).on('mousedown', '.main-off', function (e){
        wbServerObj.logoDrag = true;
        let logoBtnObj = $(this);
        let disY = e.clientY - logoBtnObj[0].offsetTop;
        logoBtnObj.css('cursor', 'move');
        $(document).on('mousemove', function (event){
            if (e.clientY !== event.clientY){
                $(document).off('click', '.main-off');
            }
            if (wbServerObj.logoDrag){
                let newTop = event.clientY - disY;
                if (newTop > 550){
                    newTop = 550;
                }
                logoBtnObj.css('top', newTop > 0 ? newTop : 0);
                chrome.storage.sync.set({'logoBtnTop':newTop});
            }
        });
        $(document).on('mouseup',function (event){
            logoBtnObj.css('cursor', 'pointer');
            wbServerObj.logoDrag = false;
            $(document).off('mousemove');
            $(document).off('mouseup');
            setTimeout(() => {
                $(document).off('click', '.main-off').on('click', '.main-off', wbServerObj.mainOffClickCallback.bind(wbServerObj));
            }, 100);
        });
    });
    //刷新图片验证码
    $(document).on('click', '.refresh-captcha', function (){
        wbServerObj.getCaptcha();
    });
    // 携带插件语言参数给注册链接
    $(document).on('click', '#reg-now', function (){
        let regUrlMap = {
            'zh': `${wbServer.CN_BASE_URL}/sign-up/`,
            'en': `${wbServer.BASE_URL}/sign-up/`,
            'ru': `${wbServer.RU_BASE_URL}/sign-up/`
        };
        let registerUrl = regUrlMap[wbServerObj.sysLang] || regUrlMap['en'];
        window.open(registerUrl);
    });
    // 忘记密码
    $(document).on('click', '#forget-password', function (){
        let forgotPassUrlMap = {
            'zh': `${ wbServer.CN_BASE_URL}/admin/forgot-password.html?plugin_lang=zh`,
            'en': `${ wbServer.BASE_URL}/admin/forgot-password.html?plugin_lang=en`,
            'ru': `${ wbServer.RU_BASE_URL}/admin/forgot-password.html?plugin_lang=ru`
        };
        let forgotPassUrl = forgotPassUrlMap[wbServerObj.sysLang] || forgotPassUrlMap['en'];
        window.open(forgotPassUrl);
    });
    // 登录表单提交
    $(document).on('click', '#signInBtn',function (e){
        e.preventDefault();
        var _this = $(this);
        var formObj = wbServerObj.getFormObj($('#sign-in-form').serializeArray());
        // 验证登录信息的准确性
        var errorMsgKey = '';
        $.each(formObj, function (field, value){
            if (field === 'captchaId'){
                return true;
            }
            var inputObj = $('input[name="'+field+'"]');
            switch (field){
                case 'account':
                    if (value === ''){
                        errorMsgKey = 'email_empty_tips';
                    }else{
                        formObj[field] = $.trim(value);
                        errorMsgKey = '';
                    }
                    break;
                case 'password':
                    if (value === ''){
                        errorMsgKey = 'password_empty_tips';
                    }else{
                        errorMsgKey = '';
                    }
                    break;
                case 'captcha':
                    if (value === ''){
                        errorMsgKey = 'captcha_err_tips';
                    }else{
                        errorMsgKey = '';
                    }
                    break;
            }
            if (field !== 'captcha'){
                inputObj = inputObj.parent();
            }
            if (inputObj.hasClass('is-invalid')){
                if (field === 'captcha'){
                    inputObj.removeClass('is-invalid').parent().parent().next('.invalid-feedback').remove();
                }else{
                    inputObj.removeClass('is-invalid').next('.invalid-feedback').remove();
                }
            }
            if (errorMsgKey !== ''){
                if (field === 'captcha'){
                    inputObj.addClass('is-invalid').parent().parent().after(`<span class="invalid-feedback d-block" data-i18n-text="${errorMsgKey}">${wbServerObj.propI18nText(errorMsgKey)}</span>`);
                }else{
                    inputObj.addClass('is-invalid').after(`<span class="invalid-feedback" data-i18n-text="${errorMsgKey}">${wbServerObj.propI18nText(errorMsgKey)}</span>`);
                }
            }
        });
        if ($('.is-invalid').length === 0){
            // 没有了错误信息才允许提交表单
            wbServerObj.userLogin({'signInBtn':_this, formObj});
        }
    });
    // 登录支持按下Enter键登录
    $(document).on('keyup', function (event){
        if (event.keyCode === 13 && $('.sign-in-container').css('bottom') === '0px'){
            $('#signInBtn').trigger('click');
        }
    });
    $(document).find('.change-lang').selectpicker();
    chrome.storage.sync.get(['ext_lang'], function (items){
        $(document).find('.change-lang').selectpicker('val', items.ext_lang ? items.ext_lang : wbServerObj.getBrowserLang());
    });
    $(document).on('changed.bs.select', '.change-lang-box select', function (e, clickedIndex, isSelected, previousValue){
        if (clickedIndex !== null && isSelected !== null){
            var lang = $(this).val();
            wbServerObj.changeLang(lang, true);
            $('.change-lang-box select').not(this).selectpicker('val', lang);
        }
    });
    var tableLoadingTimer;
    // 显示loading层
    var showLoadingBox = function (length){
        var num = 0;
        $('#product-search-container .unavailable-tips').css('z-index', -1);
        var loadingBox = $('.loading-box');
        if ($('.bootstrap-table').length == 0){
            loadingBox.css('z-index', '10000');
            loadingBox.removeClass('d-none');
            loadingBox.find('.record-total').text(length);
            loadingBox.find('.record-unit').text(num);
            tableLoadingTimer = setInterval(function (){
                num ++;
                if (num > length){
                    num = length;
                }
                loadingBox.find('.record-unit').text(num);
                loadingBox.find('.progress .progress-bar').css('width', (num / length * 100) + '%');
                if (num == length || $('.bootstrap-table').length > 0){
                    clearInterval(tableLoadingTimer);
                    loadingBox.css('z-index', '-1');
                    loadingBox.addClass('d-none');
                }
            }, 50);
        }
    };
    chrome.storage.sync.get(['customColumns'], function (items){
        if (items.customColumns || items.customColumns === null){
            window.customColumns = items.customColumns;
        }
    });

    $(document).on('mouseover mouseout click', '.logo-link', function (event){
        var _this = $(this);
        switch (event.type){
            case 'click':
                var port = chrome.runtime.connect({name: 'options'});
                port.postMessage({redirectToOptions: 1}); // 发送
                // 监听回复
                port.onMessage.addListener(function (message){});
                port.disconnect;
                break;
            case 'mouseover':
                _this.find('.logo-img').hide();
                _this.find('.options-img').show();
                break;
            case 'mouseout':
                _this.find('.logo-img').show();
                _this.find('.options-img').hide();
                break;
        }
    });
    var resetLoadingBox = function (){
        var loadingBox = $('.loading-box');
        if (tableLoadingTimer){
            clearInterval(tableLoadingTimer);
        }
        loadingBox.find('.record-unit').text('');
        loadingBox.find('.record-total').text('');
        loadingBox.find('.progress .progress-bar').css('width', '0%');
        $('.ext-main-container').css({'bottom': '-800px', 'height': 'auto'});
        $('.main-off').css('z-index', '1000000');
        $('.main-box-footer').hide();
    };
    // 关闭弹窗
    $(document).on('click', '.close-plugin', function (){
        const isFullScreen = document.webkitIsFullScreen || false;
        resetLoadingBox();
        if (isFullScreen){
            document.exitFullscreen();
        }
        wbServerObj.productTableObj.bootstrapTable('destroy');
        wbServerObj.minerTableObj.bootstrapTable('destroy');
        wbServerObj.reverseTableObj.bootstrapTable('destroy');
        $('[data-tab="product-search-container"]').parent().addClass('active');
        $('.main-item[id="product-search-container"]').removeClass('d-none');
        $('[data-tab!="product-search-container"]').parent().removeClass('active');
        $('.main-item[id!="product-search-container"]').addClass('d-none');
        $('.unavailable-tips').css('z-index', 10);
        $('.open-custom-column').removeClass('d-none');
        $('.export-details').removeClass('disabled pointer-events-none').html(`${wbServerObj.propI18nText('export_details')}`);
        // 删除相关提示
        $('.main-box-footer .change-lang-box').find('.free-user-tips').remove();
        $('.main-box-footer .export-details').next('.export-error-tips').remove();
        // 重置相关变量
        wbServerObj.mainOffStatus = false;
    });
    // 关闭登录页面
    $(document).on('click', '.sign-in-close', function (){
        $(this).parent().css('bottom', '-500px');
        $('.main-off').css('z-index', '1000000');
        chrome.storage.sync.set({'is_close': 1});
        wbServerObj.mainOffStatus = false;
    });
    $(document).off('mouseenter mouseleave', '.fa-question-circle').on('mouseenter mouseleave', '.fa-question-circle', function (event){
        let dataTips = $(this).attr('data-tips');
        let tipsContent = wbServerObj.propI18nText(dataTips);
        if ($(this).attr('data-original-title')){
            tipsContent = $(this).attr('data-original-title');
        }
        let isTippy = $(this).hasClass('tippy-tips');
        switch (event.type){
            case 'mouseenter':
                if (isTippy || wbServerObj.isGlobalSite){
                    /*tippy($(this)[0], {
                        'interactive':true,
                        'content':tipsContent,
                        'zIndex': 1000000,
                        'maxWidth': 'none'
                    });*/
                }else{
                    $(this).tooltip({'title': tipsContent}).tooltip('show');
                }
                break;
            case 'mouseleave':
                if (!isTippy && !wbServerObj.isGlobalSite){
                    $(this).tooltip('destroy');
                }
                break;
        }
    });
    //密码显示和隐藏
    $(document).off('click', '.show-pass').on('click', '.show-pass', function (){
        let isShow = $(this).children().hasClass('fa-eye-slash');
        $('#sign-in-pass').attr('type', isShow ? 'text' : 'password');
        $(this).children().attr('class', isShow ? 'fa fa-eye' : 'fa fa-eye-slash');
    });
});