let pre_host = 'https://www.5ufclub.com';
//流量超过以后，或者状态不可用使用此代理服务器
let disbaled_server = 'black.5uf99.com:8443';

//site同步间隔，单位为:s
let site_sync_limit = 30;

//账号检测时间间隔，单位为:s
let auth_limit = 30;

//启动后多久检查新版本，单位为:s
let update_limit = 120;

//当前的版本号
let current_version = '4.2';
//用于获取网站域名的url地址
let find_host = pre_host+'/data/crx/crx_host.txt';
let find_host_2 = pre_host+'/data/crx/crx_host_2.txt';
//ajax超时时间
let ajax_timeout = 5;

//切换服务器后，用于测试的url
let test_url = 'https://www.5ufclub.com';
//特殊域名后缀
let special_domain_suffix = ['com.cn', 'com.co.jp', 'co.jp', 'net.cn', 'org.cn', 'gov.cn','edu.cn', "tw.cn", "hn.cn", "hl.cn", "sh.cn", "hi.cn", "cp.cn", "hk.cn", "gx.cn", "sx.cn", "mo.cn", "ln.cn", "nm.cn", "ah.cn", "qh.cn", "hb.cn", "xj.cn", "gz.cn", "jl.cn", "nx.cn", "gd.cn", "sn.cn", "sc.cn", "he.cn", "zj.cn", "ha.cn", "tj.cn", "bj.cn", "sd.cn", "fj.cn", "yn.cn", "gs.cn", "xz.cn", "jx.cn", "ac.cn", "com.cn", "net.cn", "org.cn", "js.cn", "cn.com", "co.com", "nom.es", "com.es", "org.es", "com.hk", "com.im", "co.im", "net.im", "org.im", "plc.co.im", "net.in", "co.in", "co.jp", "or.kr", "co.kr", "org.lc", "co.lc", "com.lc", "net.lc", "in.net", "co.nz", "org.so", "net.so", "com.so", "com.tw", "org.tw", "co.uk", "gov.cn", "com.ph"];
//统计代码
let trace_code = '';
let complete = [];
chrome.storage.local.get(['5uf_login_username', '5uf_login_password', '', '', ''], (result) => {
    //初始化下标和title
    if (typeof(result['5uf_login_username']) == 'string' && typeof(result['5uf_login_password']) == 'string') {
        chrome.storage.local.set({'5uf_error_list': JSON.stringify({})});
        //chrome.action.setBadgeText({text:''});
        chrome.action.setTitle({title:'无忧府VPN '});
    } else {
        chrome.storage.local.set({'5uf_error_list': JSON.stringify({})});
    }
    complete = [];
    chrome.storage.local.set({'disable': 0});
});


  
// chrome.proxy.onRequest.addListener(
//     (details) => {
//         // 如果请求需要身份验证
//         if (details.url.includes('xinhuanet.com')) {
//             return {
//                 authCredentials: {
//                     username: "111",
//                     password: "222"
//                 }
//             };
//         }
//     },
//     { urls: ['<all_urls>'] },
//     ["blocking"]
// );

// chrome.webRequest.onAuthRequired.addListener(function(details){
// 		console.log(details);
//         if (localStorage.getItem('5uf_login_username') != null) {
//             console.log('认证成功');
//             return {
//                 authCredentials: {username:localStorage.getItem('5uf_login_username'), password:localStorage.getItem('5uf_login_password')}
//             };
//         } else {
//             console.log('无法认证');
//             return {};
//         }
//     }, {
//         urls: ['<all_urls>']
//     }, ['blocking']
// );

function buildChromeProxyWarnings(proxyDetails) {
    const level = proxyDetails.levelOfControl;
    const value = proxyDetails.value || {};
    const mode = value.mode || 'direct';
    const warnings = [];
    if (level === 'controlled_by_other_extensions') {
        warnings.push('Chrome 报告代理正由其他扩展程序控制，无忧府 VPN 可能无法生效。请先禁用其它代理类扩展。');
    }
    // 扩展无 API 读取系统「网络 → 代理」里的 HTTP/HTTPS（如 127.0.0.1:7890），仅能作人工排查提示
    if (level === 'controlled_by_this_extension') {
        warnings.push('提示：无法自动检测系统在「网络 → 代理」中开启的 HTTP/HTTPS（常见如 127.0.0.1:7890）。若与本插件同时启用，可能叠代理；异常时请关闭系统代理或本地代理软件，只保留一种方式。');
    }
    if (level === 'not_controllable' && mode !== 'direct') {
        warnings.push('浏览器代理受企业策略或系统限制，本插件可能无法修改代理设置。');
    }
    if (mode === 'system' && level !== 'controlled_by_this_extension') {
        warnings.push('当前为「使用系统代理」。若操作系统或其它软件已开启代理/VPN，可能与无忧府叠加或冲突，建议在系统网络设置中检查。');
    }
    if (mode === 'auto_detect' && level !== 'controlled_by_this_extension') {
        warnings.push('当前为「自动检测代理」(WPAD)，可能与无忧府冲突，建议在系统或网络设置中关闭自动代理检测。');
    }
    if ((mode === 'fixed_servers' || mode === 'pac_script') && level === 'controllable_by_this_extension') {
        warnings.push('检测到 Chrome 已配置手动代理或 PAC（尚不由本插件接管），可能与无忧府冲突。');
    }
    return warnings;
}

function checkEnvironmentConflicts(sendResponse) {
    chrome.proxy.settings.get({ incognito: false }, (proxyDetails) => {
        if (chrome.runtime.lastError) {
            sendResponse({
                error: chrome.runtime.lastError.message,
                warnings: [],
                otherProxyExtensions: [],
                blockMainUI: false,
            });
            return;
        }
        const proxyWarnings = buildChromeProxyWarnings(proxyDetails);
        chrome.management.getAll((exts) => {
            const myId = chrome.runtime.id;
            const otherProxy = [];
            for (let i = 0; i < exts.length; i++) {
                const ext = exts[i];
                if (ext.id === myId || !ext.enabled) {
                    continue;
                }
                const perms = ext.permissions || [];
                for (let j = 0; j < perms.length; j++) {
                    if (perms[j] === 'proxy') {
                        otherProxy.push({ id: ext.id, name: ext.name, icons: ext.icons });
                        break;
                    }
                }
            }
            const blockMainUI =
                otherProxy.length > 0 ||
                proxyDetails.levelOfControl === 'controlled_by_other_extensions';
            sendResponse({
                warnings: proxyWarnings,
                otherProxyExtensions: otherProxy,
                proxyLevel: proxyDetails.levelOfControl,
                proxyMode: (proxyDetails.value && proxyDetails.value.mode) || 'direct',
                blockMainUI,
            });
        });
    });
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'get_storage') {
        let keys = message.data != null ? message.data : message.key;
        if (Array.isArray(keys)) {
            keys = keys.filter((k) => k);
        }
        chrome.storage.local.get(keys, (result) => {
            sendResponse(result);  // 将数据返回给 popup
        });
        return true;  // 表示这是一个异步的响应
    } else if (message.action === 'set_storage') {
        chrome.storage.local.set(message.data, () => {
            if (chrome.runtime.lastError) {
                sendResponse({ success: false, error: chrome.runtime.lastError.message });
            } else {
                sendResponse({ success: true });
            }
        });
        return true;
    } else if (message.action === 'clear_storage') {
        return chrome.storage.local.clear()
    } else if (message.action === 'remove_storage') {
        chrome.storage.local.remove(message.data, () => {
            if (chrome.runtime.lastError) {
                sendResponse({ success: false, error: chrome.runtime.lastError.message });
            } else {
                sendResponse({ success: true });
            }
        });
        return true;
    } else if (message.action === 'set_proxy') {
        set_proxy();
    } else if (message.action === 'test_url') {
        console.log("测试："+test_url);
        fetch(test_url, {method: 'GET', mode: 'cors'})
            .then(response => {
                console.log(response);
                if (response.ok) {
                    return response.text();  // 处理响应
                } else {
                    sendResponse({ success: false, error: '23322' });
                }
            })
            .then(data => {
                // 返回请求结果给 popup
                sendResponse({ success: true, data: data });
            })
            .catch(error => {
                // 如果请求失败，返回错误信息
                sendResponse({ success: false, error: '5555' });
            });
        return true;
    } else if (message.action === 'refresh_tab') {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          if (tabs[0]) {
            chrome.tabs.reload(tabs[0].id);  // 刷新当前激活的 tab
          }
        });
      } else if (message.action === 'check_proxy_conflict') {
        checkEnvironmentConflicts(sendResponse);
        return true;
      } else if (message.action === 'recheck_desktop_vpn') {
        runDesktopVpnPortCheck({ ensureProxyOnClean: true }, () => {
          sendResponse({ ok: true });
        });
        return true;
      } else if (message.action === 'run_check_online_now') {
        check_online();
        sendResponse({ ok: true });
        return true;
      }
});
chrome.alarms.create('sync', {periodInMinutes: 0.2});
chrome.alarms.create('check_online', {periodInMinutes: 0.2});

chrome.alarms.onAlarm.addListener((alarm) => {
    if (alarm.name === 'sync') {
        runDesktopVpnPortCheck();
        chrome.storage.local.get(['5uf_login_username', '5uf_login_password', '5uf_host', '5uf_webproxy_version'], (items) => {
            const form_data = {username: items['5uf_login_username'], password: items['5uf_login_password'], version: items['5uf_webproxy_version']};
            const params = new URLSearchParams();
            for (const [key, value] of Object.entries(form_data)) {
                params.append(key, value);
            }
            if (typeof(items['5uf_login_username']) == 'undefined' || typeof(items['5uf_login_password']) == 'undefined') {
                console.log('无需开始同步任务');
                return true;
            }
            fetch(items['5uf_host'] + '/api_sync_webproxy_site/index/nocrypt/1/nocbase64/1', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params.toString()
            }).then(response => {
                if (!response.ok) {
                    return;
                }
                return response.json();
            }).then(data => {
                if (data['code']==1) {
                    var s_data = {
                        '5uf_block_list': JSON.stringify(data['data']['site']),
                        '5uf_block_list_system': JSON.stringify(data['data']['system_site']),
                        '5uf_white_list': JSON.stringify(data['data']['white']),
                        '5uf_white_list_system': JSON.stringify(data['data']['system_white']),
                        '5uf_webproxy_version': data['data']['version'],
                    };
                    chrome.runtime.sendMessage({ action: 'set_storage', data: s_data });
                    set_proxy();
                } else {

                }
            })
        });
    } else if (alarm.name === 'check_online') {
        check_online();
    }
});


chrome.runtime.onInstalled.addListener(() => {
    //chrome.storage.local.clear()
    var currentTime = new Date().toLocaleString();
    console.log(currentTime + ' 初始化install');
    chrome.storage.local.set({
        "5uf_host" : 'https://www.5ufclub.com',
        "5uf_web_host" : 'https://www.5ufclub.com',
        "crx_version" : current_version
        // "5uf_login_username" : '111',
        // "5uf_login_password" : '222',
    });
    fetch(find_host, {
        method: 'GET'
    }).then(response => {
        if (!response.ok) {
            chrome.storage.local.set({
                "5uf_host": pre_host,
                "5uf_web_host": pre_host,
            });
            return;
        }
        return response.text();
    }).then(data => {
        console.log(data.length);
        if (data == null || data.length == 0 || data.substring(0, 4) != 'http') {
            data.split(/[\s\n]/);
            chrome.storage.local.set({
                "5uf_host": pre_host,
                "5uf_web_host": pre_host,
            });
            return;
        }
        chrome.storage.local.set({
            "5uf_host": data
        });
    })
    .catch(error => {
        console.log(error);
    });


    fetch(find_host_2, {
        method: 'GET'
    }).then(response => {
        if (!response.ok) {
            chrome.storage.local.set({
                "5uf_host": pre_host,
                "5uf_web_host": pre_host,
            });
            return;
        }
        return response.text();
    }).then(data => {
        console.log(data.length);
        if (data == null || data.length == 0 || data.substring(0, 4) != 'http') {
            data.split(/[\s\n]/);
            chrome.storage.local.set({
                "5uf_host_2": pre_host,
                "5uf_web_host": pre_host,
            });
            return;
        }
        chrome.storage.local.set({
            "5uf_host_2": data
        });
    })
    .catch(error => {
        console.log(error);
    });
    runDesktopVpnPortCheck({ ensureProxyOnClean: true });
});

chrome.webRequest.onCompleted.addListener(function (a) {
    chrome.storage.local.get(['5uf_login_username', '5uf_login_password'], (items) => {
        if (typeof(items['5uf_login_username']) == 'undefined' && typeof(items['5uf_login_password']) == 'undefined'){
            return;
        }
        //获得域名
        var domain_name = getDomainFromUrl(a.url);
        if (domain_name=="" || domain_name==undefined || domain_name.length<3) {
            return ;
        }
        if (a.url.indexOf("chrome-extension") != -1) {
            return ;
        }
        if (a.url.indexOf("192.") != -1) {
            return ;
        }
        if (a.url.indexOf("127.") != -1) {
            return ;
        }
        if (a.url.indexOf("10.") != -1) {
            return ;
        }
        if (a.url.indexOf("100.") != -1) {
            return ;
        }
        if (a.url.indexOf("localhost") != -1) {
            return ;
        }
        for (var i in complete) {
            if (complete[i] == domain_name) {
                return;
            }
        }
        complete.push(domain_name);
    });
    
}, {
    urls: ["<all_urls>"]
});


chrome.webRequest.onErrorOccurred.addListener(function (a) {
    //获得域名
    var domain_name = getDomainFromUrl(a.url);
    chrome.storage.local.get(['5uf_login_username', '5uf_login_password', '5uf_error_list', '5uf_block_list', '5uf_block_list_system'], (items) => {
        if (typeof(items['5uf_login_username']) == 'undefined' && typeof(items['5uf_login_password']) == 'undefined'){
            return;
        }
        if (domain_name=="" || domain_name==undefined || domain_name.length<3) {
            return ;
        }
    
        //错误列表
        var error_list = items['5uf_error_list'];
        if (typeof(error_list) == 'undefined' || error_list == null) {
            var error_list = {};
            chrome.storage.local.set({'5uf_error_list': JSON.stringify(error_list)});
        }
        var error_list = items['5uf_error_list'];
        error_list = JSON.parse(error_list);
    
        //加速列表
        var block_list = items['5uf_block_list'];
        if (typeof(block_list) == 'undefined' || block_list == null) {
            var block_list = [];
            chrome.storage.local.set({'5uf_block_list': JSON.stringify(block_list)});
        }
        var block_list = items['5uf_block_list'];
        block_list = JSON.parse(block_list);
    
        //通用加速列表
        var block_list_system = items['5uf_block_list_system'];
        if (typeof(block_list_system) == 'undefined' || block_list_system == null) {
            var block_list_system = [];
            chrome.storage.local.set({'5uf_block_list_system': JSON.stringify(block_list_system)});
        }
        var block_list_system = items['5uf_block_list_system'];
        block_list_system = JSON.parse(block_list_system);
        if (a.url.indexOf("chrome-extension") != -1) {
            return ;
        }
        if (a.url.indexOf("192.") != -1) {
            return ;
        }
        if (a.url.indexOf("127.") != -1) {
            return ;
        }
        if (a.url.indexOf("10.") != -1) {
            return ;
        }
        if (a.url.indexOf("100.") != -1) {
            return ;
        }
        if (a.url.indexOf("localhost") != -1) {
            return ;
        }
        var tabId = a.tabId, tab_key = 'tab_'+tabId;
    
        if (a.error.indexOf("ABORT") == -1) {
            if (typeof(error_list[tabId]) == 'undefined' || error_list[tabId] == null) {
                error_list[tabId] = [];
            }
            //重复的
            for (var i in  error_list[tabId]) {
                if ( error_list[tabId][i] == domain_name) {
                    return;
                }
            }
            //存在的
            for (var i in block_list) {
                if (block_list[i] == domain_name) {
                    return;
                }
            }
            //通用存在的
            for (var i in block_list_system) {
                if (block_list_system[i] == domain_name) {
                    return;
                }
            }
    
            for (var i in  complete) {
                if ( complete[i] == domain_name) {
                    return;
                }
            }
            if (typeof(error_list[tabId]) == 'undefined') {
                error_list[tabId] = [];
            }
            error_list[tabId].push(domain_name);
            chrome.storage.local.set({'5uf_error_list': JSON.stringify(error_list)});
            chrome.tabs.query({ currentWindow: true, active: true }, function (tab) {
                if (tabId == tab[0].id) {
                    chrome.action.setBadgeText({text:error_list[tabId].length+''});
                    chrome.action.setTitle({title:'无忧府VPN '+'当前已探测到'+error_list[tabId].length+'个加载失败的资源'});
                }
            });
            return ;
        }
    });
}, {
    urls: ["<all_urls>"]
});

//关闭标签事件
chrome.tabs.onRemoved.addListener(function (tabId, changeInfo, tab) {

    chrome.storage.local.get(['5uf_login_username', '5uf_login_password', '5uf_error_list'], (items) => {
        if (typeof(items['5uf_login_username']) == 'undefined' && typeof(items['5uf_login_password']) == 'undefined'){
            return;
        }
        //错误列表
        var error_list = items['5uf_error_list'];
        if (typeof(error_list) == 'undefined' || error_list == null) {
            var error_list = '[]';
            chrome.storage.local.set({'5uf_error_list': error_list});
        }
        error_list = JSON.parse(error_list);


        if (typeof(error_list[tabId]) == 'undefined') {
        } else {
            error_list[tabId] = [];
        }
        chrome.storage.local.set({'5uf_error_list': JSON.stringify(error_list)});
    });
    
});

//切换标签事件
chrome.tabs.onActivated.addListener(function (activeInfo){
    chrome.storage.local.get(['5uf_login_username', '5uf_login_password', '5uf_error_list', '5uf_block_list', '5uf_block_list_system'], (items) => {
        if (typeof(items['5uf_login_username']) == 'undefined' && typeof(items['5uf_login_password']) == 'undefined'){
            return;
        }
        var tabId = activeInfo.tabId;
        //错误列表
        var error_list = items['5uf_error_list'];
        if (typeof(error_list) == 'undefined' || error_list == null) {
            var error_list = [];
            localStorage.setItem('5uf_error_list', JSON.stringify(error_list));
        }
        var error_list = items['5uf_error_list'];
        error_list = JSON.parse(error_list);
        if (typeof(error_list[tabId]) == 'undefined' || error_list[tabId] == null) {
            chrome.action.setBadgeText({text:''});
            chrome.action.setTitle({title:'无忧府VPN '});
        } else {
            if (error_list[tabId].length == 0) {
                chrome.action.setBadgeText({text:''});
                chrome.action.setTitle({title:'无忧府VPN '});
                return;
            }
            var num = error_list[tabId].length;
            chrome.action.setBadgeText({text:num+''});
            chrome.action.setTitle({title:'无忧府VPN '+'当前已探测到'+num+'个加载失败的资源'});
        }
    });
});

/** 与 5UF 桌面版等本地 HTTP 代理常见端口冲突探测（本机 127.0.0.1:7890 有 HTTP 应答即视为占用） */
const LOCAL_DESKTOP_VPN_PROBE_URL = 'http://127.0.0.1:7890/';
const LOCAL_DESKTOP_VPN_PROBE_MS = 2500;

function probeLocalDesktopVpnHttpPort() {
    const ac = new AbortController();
    const tid = setTimeout(() => ac.abort(), LOCAL_DESKTOP_VPN_PROBE_MS);
    return fetch(LOCAL_DESKTOP_VPN_PROBE_URL, {
        method: 'GET',
        signal: ac.signal,
        cache: 'no-store',
    })
        .then(() => {
            clearTimeout(tid);
            return true;
        })
        .catch(() => {
            clearTimeout(tid);
            return false;
        });
}

/**
 * @param {object} [options]
 * @param {boolean} [options.ensureProxyOnClean] 为 true 时：未占用且无冲突标记也会执行一次 set_proxy()（用于 install 首次）
 * @param {function} [done]
 */
function runDesktopVpnPortCheck(options, done) {
    if (typeof options === 'function') {
        done = options;
        options = {};
    }
    options = options || {};
    const ensureProxyOnClean = !!options.ensureProxyOnClean;
    probeLocalDesktopVpnHttpPort().then((open) => {
        chrome.storage.local.get(['5uf_desktop_vpn_conflict'], (data) => {
            const was = data['5uf_desktop_vpn_conflict'];
            if (open) {
                if (!was) {
                    chrome.storage.local.set(
                        { '5uf_desktop_vpn_conflict': 1, proxy_mode: 'close' },
                        () => {
                            setProxyFollowOperatingSystem();
                            chrome.action.setBadgeBackgroundColor({ color: '#C62828' });
                            chrome.action.setBadgeText({ text: '!' });
                            chrome.action.setTitle({
                                title: '无忧府VPN：检测到本机 7890 端口（可能与桌面版同时运行），浏览器扩展已停用',
                            });
                            if (done) {
                                done();
                            }
                        },
                    );
                } else {
                    setProxyFollowOperatingSystem();
                    chrome.action.setBadgeBackgroundColor({ color: '#C62828' });
                    chrome.action.setBadgeText({ text: '!' });
                    chrome.action.setTitle({
                        title: '无忧府VPN：检测到本机 7890 端口（可能与桌面版同时运行），浏览器扩展已停用',
                    });
                    if (done) {
                        done();
                    }
                }
            } else if (was) {
                chrome.storage.local.remove('5uf_desktop_vpn_conflict', () => {
                    chrome.action.setBadgeText({ text: '' });
                    chrome.action.setTitle({ title: '无忧府VPN ' });
                    set_proxy();
                    if (done) {
                        done();
                    }
                });
            } else if (ensureProxyOnClean) {
                set_proxy();
                if (done) {
                    done();
                }
            } else if (done) {
                done();
            }
        });
    });
}

/** 「关闭」本插件加速时：不显式接管为直连 PAC，而改为使用操作系统代理（与 Chrome 选「使用系统代理设置」一致；系统未开代理时一般为直连） */
function setProxyFollowOperatingSystem() {
    chrome.proxy.settings.set({ value: { mode: 'system' }, scope: 'regular' }, () => {
        if (chrome.runtime.lastError) {
            console.warn('setProxyFollowOperatingSystem:', chrome.runtime.lastError.message);
            chrome.proxy.settings.clear({ scope: 'regular' });
        }
    });
}

function set_proxy () {
    chrome.storage.local.get(['5uf_block_list', '5uf_block_list_system', '5uf_white_list', '5uf_white_list_system', 'proxy_mode', '5uf_user_status', '5uf_server_selected_host', '5uf_server_selected_port', '5uf_desktop_vpn_conflict', '5uf_no_webproxy_pwd'], (result) => {
        if (result['5uf_desktop_vpn_conflict'] || result['5uf_no_webproxy_pwd']) {
            setProxyFollowOperatingSystem();
            return;
        }
        // var block_list = result['5uf_block_list'];
        // block_list = JSON.parse(block_list);

        // var block_list_system = result['5uf_block_list_system'];
        // block_list_system = JSON.parse(block_list_system);

        // var white_list = result['5uf_white_list'];
        // white_list = JSON.parse(white_list);

        // var white_list_system = result['5uf_white_list_system'];
        // white_list_system = JSON.parse(white_list_system);

        var proxy_mode = result['proxy_mode'];

        var user_status = result['5uf_user_status'];
        if (proxy_mode != 'close' && user_status != 'Password') {
            var pac =
                'dnsDomainIs=function(h,d){return h.indexOf(d,h.length-d.length)!==-1&&(d.length===h.length||h.indexOf("."+d,h.length-("."+d).length)!==-1)};'+
                "var FindProxyForURL = function(url, host){"+
                "host=host.toLowerCase();"+
                "var white_list_system = "+result['5uf_white_list_system']+';'+
                "for(i=0;i<white_list_system.length;i++){"+
                "if (dnsDomainIs(host,white_list_system[i])){"+
                "return 'DIRECT';"+
                "}"+
                "}"+
                "return '"+disbaled_server+"';"+
                "}";
            //alert(pac);
            var config = {
                mode: "pac_script",
                pacScript: {
                    data: pac
                }
            }
            chrome.proxy.settings.set({value: config, scope: 'regular'}, function(){});
            return;

        } else if (result['5uf_server_selected_host'] == null || result['5uf_server_selected_host'] == null) {
            var pac =
                "var FindProxyForURL = function(url, host){"+
                +"return 'DIRECT';"+
                "}";
            var config = {
                mode: "pac_script",
                pacScript: {
                    data: pac
                }
            };
            chrome.proxy.settings.set({value: config, scope: 'regular'}, function(){});
            return ;
        } else if (proxy_mode == 'all') {
            console.log('切换模式：all');
            var pac =
                'dnsDomainIs=function(h,d){return h.indexOf(d,h.length-d.length)!==-1&&(d.length===h.length||h.indexOf("."+d,h.length-("."+d).length)!==-1)};'+
                "var FindProxyForURL = function(url, host){"+
                "host=host.toLowerCase();"+
                "var white_list = "+result['5uf_white_list']+';'+
                "var white_list_system = "+result['5uf_white_list_system']+';'+
                "for(i=0;i<white_list.length;i++){"+
                "if (dnsDomainIs(host,white_list[i])){"+
                "return 'DIRECT';"+
                "}"+
                "}"+
                "for(i=0;i<white_list_system.length;i++){"+
                "if (dnsDomainIs(host,white_list_system[i])){"+
                "return 'DIRECT';"+
                "}"+
                "}"+
                "return 'HTTPS "+result['5uf_server_selected_host']+":"+(result['5uf_server_selected_port'] != 0 ? result['5uf_server_selected_port'] : '443')+"';"+
                "}";
            //alert(pac);
            var config = {
                mode: "pac_script",
                pacScript: {
                    data: pac
                }
            };
            chrome.proxy.settings.set({value: config, scope: 'regular'}, function(){});
            return ;
        } else if (proxy_mode == 'close') {
            console.log('切换模式：close（Chrome 使用系统代理设置）');
            setProxyFollowOperatingSystem();
            return;
        } else if (proxy_mode == 'require') {
            console.log('切换模式：require');
            var pac =
                'dnsDomainIs=function(h,d){return h.indexOf(d,h.length-d.length)!==-1&&(d.length===h.length||h.indexOf("."+d,h.length-("."+d).length)!==-1)};'+
                "var FindProxyForURL = function(url, host){"+
                "host=host.toLowerCase();"+
                "var block_list = "+result['5uf_block_list']+';'+
                "var block_list_system = "+result['5uf_block_list_system']+';'+


                "var white_list = "+result['5uf_white_list']+';'+
                "var white_list_system = "+result['5uf_white_list_system']+';'+
                "for(i=0;i<white_list.length;i++){"+
                "if (dnsDomainIs(host,white_list[i])){"+
                "return 'DIRECT';"+
                "}"+
                "}"+
                "for(i=0;i<white_list_system.length;i++){"+
                "if (dnsDomainIs(host,white_list_system[i])){"+
                "return 'DIRECT';"+
                "}"+
                "}"+
                "for(i=0;i<block_list_system.length;i++){"+
                "if (dnsDomainIs(host,block_list_system[i])){"+
                "return 'HTTPS "+result['5uf_server_selected_host']+":"+(result['5uf_server_selected_port'] != 0 ? result['5uf_server_selected_port'] : '443')+"';"+
                "}"+
                "}"+
                "for(i=0;i<block_list.length;i++){"+
                "if (dnsDomainIs(host,block_list[i])){"+
                "return 'HTTPS "+result['5uf_server_selected_host']+":"+(result['5uf_server_selected_port'] != 0 ? result['5uf_server_selected_port'] : '443')+"';"+
                "}"+
                "}"+
                "return 'DIRECT';"+

                "}";
            var config = {
                mode: "pac_script",
                pacScript: {
                    data: pac
                }
            }
            chrome.proxy.settings.set({value: config, scope: 'regular'}, function(){});
        }
    });
}

//在线连接数检查
function check_online () {
    chrome.storage.local.get(['5uf_login_username', '5uf_login_password', '5uf_host'], (items) => {
        if (typeof(items['5uf_login_username']) == 'undefined' && typeof(items['5uf_login_password']) == 'undefined'){
            return;
        }
        console.log('check_online');
        const form_data = {username: items['5uf_login_username'], password: items['5uf_login_password']};
        const params = new URLSearchParams();
        for (const [key, value] of Object.entries(form_data)) {
            params.append(key, value);
        }
        fetch(items['5uf_host'] + '/api_refresh/index/nocrypt/1/nocbase64/1', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: params.toString()
        }).then(response => {
            if (!response.ok) {
                return;
            }
            return response.json();
        }).then(data => {
            if (data['code']==1) {
                const ui = data['data']['userinfo'];
                const wpr = ui['webproxy_pwd_ready'];
                chrome.storage.local.set({
                    '5uf_user_expired': ui['expired'],
                    '5uf_user_email': ui['email'],
                    '5uf_user_group': ui['group'],
                    '5uf_user_online_total': ui['online_total'],
                    '5uf_conn_total': ui['auth_total'],
                    '5uf_user_status': ui['attribute'],
                }, () => {
                    if (wpr === 0) {
                        chrome.storage.local.set({ '5uf_no_webproxy_pwd': 1, proxy_mode: 'close' }, () => {
                            set_proxy();
                            chrome.storage.local.get(['5uf_desktop_vpn_conflict'], (d) => {
                                if (!d['5uf_desktop_vpn_conflict']) {
                                    chrome.action.setBadgeBackgroundColor({ color: '#C62828' });
                                    chrome.action.setBadgeText({ text: '!' });
                                    chrome.action.setTitle({
                                        title: '无忧府VPN：未设置超级VPN兼容密钥，扩展已暂停，请到官网设置',
                                    });
                                }
                            });
                        });
                        return;
                    }
                    chrome.storage.local.remove('5uf_no_webproxy_pwd', () => {
                        chrome.storage.local.get(['proxy_mode'], (pm) => {
                            if ((parseInt(ui['online_total'], 10) > parseInt(ui['auth_total'], 10) || ui['attribute'] != 'Password') && pm['proxy_mode'] != 'close') {
                                chrome.storage.local.set({ disable: 1 });
                                return;
                            }
                            set_proxy();
                            chrome.storage.local.get(['5uf_desktop_vpn_conflict', '5uf_no_webproxy_pwd'], (d2) => {
                                if (!d2['5uf_desktop_vpn_conflict'] && !d2['5uf_no_webproxy_pwd']) {
                                    chrome.action.setBadgeText({ text: '' });
                                    chrome.action.setTitle({ title: '无忧府VPN ' });
                                }
                            });
                        });
                    });
                });
            } else {
                setProxyFollowOperatingSystem();
                // NOTE: Do not clear saved credentials on transient refresh/auth errors.
                // Switching upstream hosts/servers can briefly fail; clearing credentials forces
                // users to re-enter username/password unnecessarily.
                chrome.storage.local.remove([
                    'first_run',
                    '5uf_server_list',
                    '5uf_server_selected',
                    '5uf_server_selected_port',
                    '5uf_server_selected_host',
                    'proxy_mode',
                    '5uf_error_list',
                    '5uf_block_list',
                    '5uf_block_list_system',
                    '5uf_white_list',
                    '5uf_white_list_system',
                    // keep: '5uf_login_username', '5uf_login_password'
                    '5uf_user_expired',
                    '5uf_user_email',
                    '5uf_user_group',
                    '5uf_user_online_total',
                    '5uf_conn_total',
                    '5uf_webproxy_version',
                    '5uf_no_webproxy_pwd',
                ]);
                chrome.action.setBadgeText({text:0+''});
            }
        })
    });
    
}

function getDomainFromUrl(url){
    if (url.indexOf("chrome-extension://") != -1) {
        return;
    }
    var durl = /(.*?):\/\/([^\/]+)\//i;
    var tmp = url.match(durl);
    var protocol = tmp[1];
    var tmp2 = tmp[2].split(".");
    var domain = "";
    if (tmp2.length >= 2) {
        var a = tmp2[tmp2.length - 2];
        var b = tmp2[tmp2.length - 1];
        var c = tmp2[tmp2.length - 3];
        domain = a + "." + b;
        for (i in special_domain_suffix) {
            var stmp = special_domain_suffix[i].split(".");
            var stmp_len = stmp.length;
            if (tmp2.length > stmp_len && tmp[2].indexOf(special_domain_suffix[i]) != -1) {
                domain = '';
                for (var ii = tmp2.length - stmp_len - 1; ii < tmp2.length; ii++) {
                    domain += (tmp2[ii] + '.');
                }
                domain = domain.substr(0, domain.length - 1);
                break;
            }
        }
    }
    else {
        domain = tmp2[tmp2.length - 1];
        protocol = "local";
    }
    if (tmp2.length == 4 && !isNaN(parseInt(tmp2[0])) && !isNaN(parseInt(tmp2[1])) && !isNaN(parseInt(tmp2[2])) && !isNaN(parseInt(tmp2[3]))) {
        var is_ok = 0;
        var regex = /[0-9]{1,3}/;
        for (var i in tmp2) {
            if (regex.test(tmp2[i])) {
                is_ok++;
            }
        }
        domain = tmp2[0] + "." + tmp2[1] + "." + tmp2[2] + "." + tmp2[3];
    }
    return domain;
}
