!function () {
    $('#shopName').click(function () {
        window.open('https://fw.jd.com/main/myService/MyService/MyServicePortal/Home')
    });

    $('#venderId').click(function () {
        copyValueToClipboard($('#venderId span').text());
        showSimpleMessage('复制成功', 800);
    });

    $('#wareUrls').on('input', function () {
        var urls = $('#wareUrls').val().replace(' ', '').replace('\t', '').split('\n');
        window.wareUrls = [];
        var tem = {};

        for(var i = 0; i < urls.length; i++){
            if(!tem[urls[i]] && urls[i].indexOf('http') > -1){
                window.wareUrls.push(urls[i]);
                tem[urls[i]] = 1;
            }
        }

        if (window.wareUrls.length) {
            $('#urlsCount strong').text(window.wareUrls.length);
            $('#urlsCount').show();
        } else {
            $('#urlsCount').hide();
        }
    });

    $('#batchPurchase').click(function () {
        chrome.runtime.sendMessage({type: 'getBackgroundCacheValue', key: 'venderInfos'}, function (venderInfos) {
            if (!venderInfos) {
                showMessage('未检测到登录信息<br>【京东】 京麦商家后台登录 <a href="{0}" style="color: red" target="_blank">去登录</a>'.format(window.globalConfig.jdShopUrls.indexPageUrl));
                return;
            }

            $('#urlsCount').hide();
            if (!window.wareUrls.length) {
                showSimpleMessage('请输入商品链接', 1000);
                return;
            }

            $(".responsive-table tr:not(:first)").empty();

            for (let i = 0; i < window.wareUrls.length; i++) {
                var trElem = $('<tr><td title="{0}">{0}</td><td><i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop fa-3/2x"></i><span ></span></td><td></td><td></td><td></td></tr>'.format(window.wareUrls[i], window.wareUrls[i]));
                $(".responsive-table tbody").append(trElem);
            }

            window.crawlTaobaoItemCnt = 0;
            $('#progress').html('成功采购<strong>0</strong>个商品（0/{0}）'.format(window.wareUrls.length));
            crawlItem(window.wareUrls[0], false, crawlItemTaskChech);
        });
    });

    $('#copyFailedUrls').click(function () {
        var failedUrls = [];
        $('table tr').each(function (index, elem) {
            console.log(elem);
            console.log($(elem).find('td:eq(1) i'));
            if ($(elem).find('td:eq(1) i').hasClass('fa-times-circle') || $(elem).find('td:eq(1) i').hasClass('layui-icon-loading-1')) {
                failedUrls.push($(elem).find('td:eq(0)').attr('title'));
            }
        });



        if (failedUrls.length) {
            $('#wareUrls').val(failedUrls.join('\n'));
            window.wareUrls = failedUrls;
            setTimeout(function () {
                $('#batchPurchase').click();
            }, 1000);

            // copyValueToClipboard(failedUrls.join('\n'));
            showSimpleMessage('重新采购成功', 800);
        } else {
            showSimpleMessage('无失败链接', 800);
        }
    });

    $('.responsive-table').click(function (event) {
        var url = $(event.target).closest('tr').find('td:eq(0)').attr('title');
        window.open(url);
    });

    async function crawlItemInterval(curItemUrl, nextItemUrl) {
        var taobaoUrl = 'https://www.taobao.com';
        if (curItemUrl.indexOf('taobao.') > -1 || curItemUrl.indexOf('tmall.') > -1) {
            window.crawlTaobaoItemCnt++;
        }

        if (nextItemUrl.indexOf('taobao.') > -1 || nextItemUrl.indexOf('tmall.') > -1) {
            if (window.crawlTaobaoItemCnt%3 == 2) {
                var cookies = await getCookies(taobaoUrl);
                chrome.runtime.sendMessage({type: 'reloadTabPage', url: taobaoUrl});
                for (let i = 0; i < 10; i++) {
                    await sleep(2000);
                    var cookiesNew = await getCookies(taobaoUrl);
                    if (cookies != cookiesNew) {
                        console.log('cookiesNew');
                        break;
                    }
                }
            }
        }
        await sleep(35000);
    }

    async function crawlItemTaskChech(response) {
        if (response['code'] == 1) {
            var tdElems = $('td[title="{0}"]'.format(response['data']['goodsUrl'])).nextAll();
            var statusElem = $(tdElems[0]).find('i');

            statusElem.removeClass().addClass('fas fa-check-circle text-green-400');
            $(tdElems[1]).text(response['data']['title']);
            $(tdElems[1]).attr('title', response['data']['title']);
            $(tdElems[2]).text(response['data']['price']);
            $(tdElems[3]).text(response['data']['shopName']);
            var curProgress = parseInt($('#progress strong').text()) + 1;
            $('#progress').html('成功采购<strong>{0}</strong>个商品（{1}/{2}）'.format(curProgress, curProgress, window.wareUrls.length));
        } else {
            var tdElems = $('td[title="{0}"]'.format(response['goodsUrl'])).nextAll();
            var statusElem = $(tdElems[0]).find('i');

            statusElem.removeClass().addClass('fas fa-times-circle text-red-400');
            // $(tdElems[1]).text('error({0})'.format(response['code']));
            $(tdElems[1]).text('请点击此处手动去通过验证码，然后重新采购');
        }

        var nextItemUrl = $('td[title="{0}"]'.format(response['data']['goodsUrl'])).parent().next().find('td[title]').text();
        if (nextItemUrl) {
            await crawlItemInterval(response['data']['goodsUrl'], nextItemUrl);
            crawlItem(nextItemUrl, false, crawlItemTaskChech);
        }
    }

    chrome.storage.local.get('BackgroundCache').then(function(result) {

        var BackgroundCache = result['BackgroundCache'] || {};
        if (BackgroundCache.hasOwnProperty('venderInfos')) {
            $('#shopName span').removeAttr('color');
            $('#shopName span').text(BackgroundCache['venderInfos']['shopName']);
            $('#venderId span').text(BackgroundCache['venderInfos']['venderId']);
        } else {
            $('#shopName span').css('color', 'darkred');
        }
    });
    // chrome.runtime.sendMessage({type: 'reloadTabPage', url: 'https://www.baidu.com'});

}();

function curDataTime() {
    // 创建一个Date对象来表示当前时间
    var currentDate = new Date();

    // 获取年、月、日
    var year = currentDate.getFullYear();
    var month = currentDate.getMonth() + 1; // 月份是从0开始计数的，所以需要加1
    var day = currentDate.getDate();

    // 获取时、分、秒
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var seconds = currentDate.getSeconds();

    // 将单个数字的月、日、时、分、秒转换为双位数格式
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }

    // 构建表示时间的字符串
    var formattedTime = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;

    return formattedTime;
}

async function crawlItemTaskResult(response) {
    console.log(response)

    var platformId = parsePlatformId(response.goodsUrl);
    if (response.code == 1) {   //采购成功
        crawlTaskStatus[platformId]['success']++;
        crawlTaskStatus[platformId]['lastSuccessTime'] = curDataTime();
        crawlTaskStatus[platformId]['fail'] = 0;

        if (platformId == '0' || platformId == '1') {
            if (crawlTaskStatus[platformId]['success'] % 3 == 0) {
                chrome.runtime.sendMessage({type: 'reloadTabPage', url: 'https://www.taobao.com/'});
            }
        }
    } else {
        crawlTaskStatus[platformId]['fail']++;
        crawlTaskStatus[platformId]['lastFailTime'] = curDataTime();
    }
}

function initCrawlTaskStatus() {
    window.crawlTaskStatus = {};
    var platformIds = ['0', '1', '2', '3', '4', '43'];
    platformIds.forEach(platformId => {
        window.crawlTaskStatus[platformId] = {
            'platformId': platformId,
            'fail': 0,
            'success': 0,
            'lastFailTime': '',
            'lastSuccessTime': ''
        }
    });
}

function getCrawlTaskStatus(goodsUrl) {
    var platformId = parsePlatformId(goodsUrl);
    return window.crawlTaskStatus[platformId];
}

initCrawlTaskStatus();
// crawlItem('https://item.taobao.com/item.htm?spm=a21n57.1.0.0.434e523cbuW7UX&id=616047858487&ns=1&abbucket=11#detail', false, crawlItemTaskResult, {'venderId': '7506477777777', 'pType': 'jdYm'})
