chrome.runtime.onInstalled.addListener(function () {
    // 类似于什么时候激活浏览器插件图标这种感觉
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
        chrome.declarativeContent.onPageChanged.addRules([{
            conditions: [new chrome.declarativeContent.PageStateMatcher({
                pageUrl: {hostSuffix: '.com'},
            })
            ],
            actions: [new chrome.declarativeContent.ShowPageAction()]
        }]);
    });
});

function upload(upload_data, path) {
    let views = chrome.extension.getViews({type: 'popup'});
    views[0].document.getElementById('info').innerHTML += '<p class="text-primary">上传中...</p>'
    let urls = upload_data.split(/\s+/)
    urls.forEach(function (item) {
        let t = item.replace(/^yunpan:\/\//).split('|');
        let [name, content_length, file_md5, file_sliced_md5] = item.replace(/^yunpan:\/\//, '').split('|');
        rapid_upload(path, name, content_length, file_md5, file_sliced_md5)
    })
}


function rapid_upload(path, name, content_length, file_md5, file_sliced_md5) {
    chrome.storage.sync.get({yunData: null}, function (items) {
        let views = chrome.extension.getViews({type: 'popup'});
        if (items.yunData) {
            let bdstoken = items.yunData.MYBDSTOKEN
            if (path) {
                quote_path = '%2F' + encodeURIComponent(path) + '%2F'
            } else (
                quote_path = '%2F'
            )
            let data = 'path=' + quote_path + name + '&content-length=' + content_length + '&content-md5='
                + file_md5 + '&slice-md5=' + file_sliced_md5 + '&target_path=%2F&local_mtime='
                + parseInt(+new Date() / 1000)
            $.ajax({
                url: 'https://pan.baidu.com/api/rapidupload?rtype=1&channel=chunlei&web=1&app_id=250528&bdstoken=' + bdstoken + '&clienttype=0',
                type: 'POST',
                data: data,
                dataType: 'text',
            }).then(function (resp) {
                let result = JSON.parse(resp)
                if (result.errno === 0) {
                    if (views.length > 0) {
                        views[0].document.getElementById('info').innerHTML += '<p class="text-success">' + name + ' 上传成功！</p>'
                    }
                } else {
                    if (views.length > 0) {
                        views[0].document.getElementById('info').innerHTML += '<p class="text-danger">' + name + ' 上传失败！</p>'
                    }
                }
            }, function () {
                alert('fail!')

            });
        } else {
            alert('请先登录百度云盘，然后上传！')
        }
    });
}

