var HataDurum = false
var isStarted
var logs = ['Loglar']
var log = ''

var kontrol

var isRefreshed = false
var SekmeKapatildi = false
var PcName = ''

var AmazonUrl = ''
var AbeUrl = ''
var UrunID = ''
var MagazaAdi = ''
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.Link) {
        window.location.reload()
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.UygulamaBaslatildi) {
        SekmeBilgileriGonder()
    }
    if (message.PageReload) {
        window.location.reload()
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.SekmeBulunamadi) {
        var text = "Extension'un çalıştığı sekme açık sekmeler arasında bulunamadı!"
        HataKontrolYap(1, text)
        console.log('Hata var:' + text)
    }
})

var linkKontrolCount = 0
var urunKontrolCount = 0

chrome.storage.onChanged.addListener(function (changes, namespace) {
    var storageChange

    for (key in changes) {
        if (key == 'KontrolUrl1' || key == 'KontrolUrl2') {
            storageChange = changes[key]
            if (storageChange.newValue.length > 0) {
                linkKontrolCount++
                //alert(linkKontrolCount);
                if (linkKontrolCount == 2) {
                    setTimeout(function () {
                        SiparisTamamla()
                    }, 2000)
                }
            }
        } else if (key == 'AmzUrunList' || key == 'AbeUrunList') {
            storageChange = changes[key]
            if (storageChange.newValue != undefined && storageChange.newValue != null) {
                urunKontrolCount++
                if (urunKontrolCount == 2) {
                    setTimeout(function () {
                        console.log(' UrunListeleriniGonder(); onchanged çağrıldı')
                        UrunListeleriniGonder()
                    }, 2000)
                }
            }
        } else {
        }
    }
})

$(document).ready(function () {
    var host = window.location.host
    var href = window.location.href
    chrome.storage.sync.get(
        [
            'isStarted',
            'UrunGetirildi',
            'Durum',
            'KontrolUrl1',
            'KontrolUrl1Hata',
            'KontrolUrl2Hata',
            'KontrolUrl2',
            'UrunFiyat',
            'AmzPageCount',
            'AbePageCount',
            'AmazonUrl',
            'AbeUrl',
            'UrunFiyat',
            'MagazaAdi',
            'RequestTime',
        ],
        function (item) {
            setTimeout(async function () {
                if (item.isStarted == true) {
                    MagazaAdi = item.MagazaAdi
                    AmazonUrl = item.AmazonUrl
                    console.log(item.Durum)
                    AbeUrl = item.AbeUrl
                    var urll = window.location.href
                    if (urll == 'https://www.amazon.com/gp/errors/404.html') {
                        UrunZararYaz()
                    }
                    if (href == 'https://sellercentral.amazon.com/home') {
                        if (item.UrunGetirildi == false) {
                            //KartBilgisiGetir(item.MagazaAdi);
                            UrunGetir()
                            SekmeBilgileriGonder()
                        } else {
                            console.log('düşün')
                            //UrunGetir();
                        }
                    } else {
                        console.log(item.Durum + 'TypeKontrol')
                        //HataKontrolYap(250);
                        if (item.Durum == 'TypeKontrol') {
                            console.log('TypeKontrol')

                            BirinciLinkKontrol()
                            // setTimeout(function () {
                            // var TipKontrolYap = LinkKontrolSayfasi == 1 ? BirinciLinkKontrol(KontrolUrl2, KontrolUrl1Hata) : IkinciLinkKontrol(KontrolUrl1, KontrolUrl2Hata);
                            // }, 500);
                        } else if (item.Durum == 'FiyatKontrol') {
                            var Fiyat = item.UrunFiyat
                            var AmzPageCount = 0
                            var AbePageCount = 0
                            AmazonUrl = item.AmazonUrl
                            AbeUrl = item.AbeUrl
                            var FiyatKontrolSayfasi = QueryStringOku('PgNm')
                            if (FiyatKontrolSayfasi != null && FiyatKontrolSayfasi.length > 0) {
                                setTimeout(function () {
                                    var FiyatKontrolYap =
                                        FiyatKontrolSayfasi == 'Abe'
                                            ? AbeFiyatKontrol(Fiyat, AbePageCount, AbeUrl)
                                            : AmazonFiyatKontrol(Fiyat, AmzPageCount, AmazonUrl)
                                    console.log('FiyatKontrolYap')
                                }, 500)
                            }
                        } else if (item.Durum == 'UrunAl') {
                            AmazonUrl = item.AmazonUrl
                            AbeUrl = item.AbeUrl
                            var UrunSatinAlmaSayfasi = QueryStringOku('PgNm')
                            var UrunSepetSayfasi = QueryStringOku('Basket')
                            var AddAdres = QueryStringOku('AddAdres')
                            var AmzSepetBosalt = QueryStringOku('Sil')
                            var AbeBilling = QueryStringOku('Billing')
                            var isAbePlaceOrder = QueryStringOku('Complete')
                            if (UrunSatinAlmaSayfasi != null && UrunSatinAlmaSayfasi.length > 0) {
                                if (UrunSepetSayfasi != null && UrunSepetSayfasi.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe' ? AbeBasketPage() : AmzBasketPage()
                                    }, 500)
                                } else if (AddAdres != null && AddAdres.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe' ? AbeAdresSilme() : 'AmzAdresEkle()'
                                    }, 500)
                                } else if (AmzSepetBosalt != null && AmzSepetBosalt.length > 0) {
                                    setTimeout(function () {
                                        AmzBasketBosalt()
                                    }, 500)
                                } else if (AbeBilling != null && AbeBilling != 'false' && AbeBilling.length > 0) {
                                    setTimeout(function () {
                                        AbeEditBilling()
                                    }, 500)
                                } else if (isAbePlaceOrder != null && isAbePlaceOrder.length > 0) {
                                    setTimeout(function () {
                                        AbeOrderComplete()
                                        //incele
                                    }, 500)
                                } else {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe'
                                                ? AbeUrunAl(item.UrunFiyat)
                                                : AmzUrunAl(item.UrunFiyat)
                                    }, 500)
                                }
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/ShoppingBasket') {
                                AbeBasketBosalt()
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/PaymentDetail?ac=f') {
                                AbeSaveBilling()
                            } else if (
                                window.location.href == 'https://www.abebooks.com/servlet/OrderSummary' &&
                                document.referrer == 'https://www.abebooks.com/servlet/PaymentDetail?ac=f'
                            ) {
                                AbeOrderComplete()
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/ShippingAddress') {
                                var textMessage = $('.errorMessage').text()
                                if (textMessage.length > 0) {
                                    HataKontrolYap(1, textMessage.trim())
                                    console.log('Hata var:' + textMessage.trim())
                                    UrunZararYaz()
                                } else {
                                    //AbeAdresEkle();

                                    chrome.storage.sync.get(['AdresEklendi'], function (item) {
                                        console.log(item.AdresEklendi)
                                        if (!item.AdresEklendi) {
                                            var url =
                                                'https://www.abebooks.com/servlet/ShippingAddress?AddAdres=true&PgNm=Abe'
                                            SayfaGit(url, 1)
                                        } else {
                                            var link =
                                                'https://www.abebooks.com/servlet/OrderSummary?Billing=false&PgNm=Abe&Complete=true'
                                            SayfaGit(link, 1)
                                            console.log('Adres Eklendi && Sayfa Yenilendi')
                                        }
                                    })
                                }
                            } else if (window.location.pathname == '/gp/huc/view.html') {
                                var SepetCount = $('#nav-cart-count').text()
                                if (SepetCount != undefined && SepetCount.length > 0) {
                                    if (parseInt(SepetCount) > 1) {
                                        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
                                        var params = 'PgNm=Amz&Sil=True'
                                        var link = amzlink + params
                                        SayfaGit(link, 1)
                                    } else if (parseInt(SepetCount) == 1) {
                                        console.log('Sepetteki ürün 0')
                                        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
                                        var params = 'PgNm=Amz&Basket=True'
                                        var link = amzlink + params
                                        SayfaGit(link, 1)
                                    } else {
                                    }
                                }
                            } else if (window.location.pathname == '/gp/buy/addressselect/handlers/display.html') {
                                if ($('.address-book-title').length > 0) {
                                    location.reload()
                                }
                                AmzAdresEkle()
                            } else if (window.location.pathname == '/gp/yourstore') {
                                var SepetKargoAdres =
                                    'https://www.amazon.com/gp/buy/addressselect/handlers/display.html'
                                // SekmeAc(SepetKargoAdres);
                                console.log('yourstore')
                            } else {
                                var path = window.location.pathname.toString()
                                var NotAdded = 'item-dispatch'
                                var NotAddedDurum = path.indexOf(NotAdded) !== -1
                                if (NotAddedDurum) {
                                    AmzItemNotAdded()
                                } else {
                                    var pass =
                                        $('.auth-text-truncate:first-child').text().trim().toLowerCase() + '478965'
                                    $('#ap_password').val(pass)
                                    if ($('#signInSubmit').length > 0) {
                                        $('#signInSubmit').click()
                                        $('#signInSubmit').trigger('click')
                                    } else UrunAl(1)
                                    console.log('hiç biri')
                                }
                            }
                        } else if (item.Durum == 'SiparisTamamla') {
                            var Sayfa = QueryStringOku('PgNm')
                            var SiparisTamamla = QueryStringOku('SiparisTamamla')
                            if (Sayfa != null && Sayfa.length > 0) {
                                if (SiparisTamamla != null && SiparisTamamla.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa = Sayfa == 'Abe' ? AbeSiparisTamamla() : 'AmzSiparisTamamla()'
                                    }, 500)
                                }
                            } else if (window.location.pathname == '/servlet/ThankYou') {
                                // var params = "?PgNm=Abe&SiparisTamamla=True";
                                // var url = "https://www.abebooks.com/servlet/BuyerOrderTrackPL"
                                // var link = url + params;
                                // SayfaGit(link, 1);
                                // } else if (window.location.pathname == "/gp/buy/thankyou/handlers/display.html") {

                                if ($('.mfa-failure').length > 0) {
                                    chrome.storage.sync.set(
                                        {
                                            Durum: 'UrunAl',
                                            AdresEklendi: true,
                                        },
                                        function () {
                                            console.log('Siparişler alınacak. ')
                                            UrunAl(0)
                                        }
                                    )
                                    //UrunAl();//UrunZararYaz();
                                } else {
                                    AbeSiparisTamamla()
                                }
                            } else if (window.location.pathname == '/gp/buy/thankyou/handlers/display.html')
                                AmzSiparisTamamla()
                        }
                    }
                }
            }, parseInt(item.RequestTime) * 1000)
        }
    )
})

function dialogModal(message, background = 'limegreen') {
    let loader = document.createElement('div')
    $(loader).addClass('extDialog')
    $(loader).css('position', 'fixed')
    $(loader).css('min-height', '200px')
    $(loader).css('height', 'auto')
    $(loader).css('width', '200px')
    $(loader).css('background', background)
    $(loader).css('color', '#fff')
    $(loader).css('overflow-wrap', 'anywhere')
    $(loader).css('border-radius', '50%')
    $(loader).css('font-weight', 'bold')
    $(loader).css('bottom', '10px')
    $(loader).css('right', '0')
    $(loader).css('z-index', '9999')
    $(loader).css('display', 'flex')
    $(loader).css('justify-content', 'center')
    $(loader).css('align-items', 'center')

    $(loader).html(message)
    document.body.append(loader)
    return loader
}

function SiparisTamamla(dataArray, refundedArray) {
    chrome.storage.sync.get(['MagazaAdi', 'UrunID', 'tracking', 'kargoFirma', 'ApiUrl'], function (item) {
        //MTip: Mağaza Tip (Amazon (0), Abe (1))

        var datam = {
            magazaDeger: item.MagazaAdi,
            SaleOrderArray: dataArray,
            refundedArray,
            tip: 'newSaleOrderEnd',
        }
        console.log(datam)
        $.ajax({
            type: 'post',
            url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            data: datam,
            success: function (cevap) {
                console.log(cevap)
                if (cevap.hata == '0') {
                    console.log('Hata: ShipmentLog Bilgileri Gönderilemedi!')

                    //Hata alındı bilgilendirilme yapılacak
                } else {
                    if (cevap.result) {
                        console.log(cevap.result)
                        console.log('ShipmentLog bilgileri gönderildi')
                        setTimeout(function () {
                            SekmeKapat(1)
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {})
                            })
                        }, 2000)
                    } else {
                        console.log('else girdi')
                        //SekmeKapat()
                    }
                }
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
            },
        })
    })
}

var RunCount = 0
function UrunGetir() {
    chrome.storage.sync.set({
        KontrolUrl1: '',
        KontrolUrl2: '',
        Titles: '',
        tracking: '',
        kargoFirma: '',
    })
    var host = window.location.host
    setTimeout(function () {
        chrome.storage.sync.get(['MagazaAdi', 'PcName', 'ApiUrl'], function (item) {
            clearTimeout(HataKontrol)
            //HataKontrolYap(75);
            console.log('Ürün Getirilecek!')
            localStorage.clear()
            localStorage.removeItem('LSAmazonUrunList')
            var datam = {
                magazaDeger: item.MagazaAdi,
                pcAd: item.PcName,
                tip: 'newSaleOrderStart',
            }
            console.log(datam)
            console.log('Ürün getirilecek!')
            $.ajax({
                type: 'post',
                url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                },
                cache: false,
                dataType: 'json',
                data: datam,
                success: function (cevap) {
                    console.log(cevap)
                    // if (cevap.hata == 0 || cevap.data==null) {
                    // chrome.storage.sync.set({
                    // "UrunGetirildi": false,
                    // "Durum": "AppStarted"
                    // }, function () {
                    // console.log("Hata: Ürün getirilemedi!");
                    // var d1 = new Date(),
                    // d2 = new Date(d1);
                    // d2.setMinutes(d1.getMinutes() + 30);
                    // var sure = d2.toLocaleString().substring(11, 19);
                    // var text = " Kontrol edilecek sipariş kalmadı! Uygulama 30 dk bekletiliyor." + sure + " itibariyle tekrar başlatılacak.";
                    // HataKontrolYap(1, text);

                    // chrome.runtime.sendMessage({
                    // YenidenBaslat: true,
                    // });
                    // if (host == "www.amazon.com" || host == "www.abebooks.com") {
                    // SekmeKapat(2);
                    // }
                    // });
                    // } else {
                    if (cevap) {
                        if (cevap.hata) {
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {})
                            })
                        }

                        if (Array.isArray(cevap.result)) {
                            chrome.storage.sync.set(
                                {
                                    orderNumber: cevap.result[0].orderNumber,
                                    UrunGetirildi: true,
                                    Durum: 'TypeKontrol',
                                    KontrolUrl1: '',
                                    KontrolUrl2: '',
                                },
                                function () {
                                    linkKontrolCount = 0
                                    urunKontrolCount = 0
                                    var link1 = cevap.result.Url
                                    SekmeAc(
                                        'https://sellercentral.amazon.com/orders-v3/ref=xx_myo_dnav_xx?page=1&date-range=last-365'
                                    )

                                    // if(data.KontrolUrl1 == data.KontrolUrl2)
                                    // {
                                    // chrome.storage.sync.set({
                                    // "Durum": "FiyatKontrol"
                                    // },function () {
                                    // SiparisLinkleriGetir(data.ID, data.AmazonUrl, data.AbeUrl);
                                    // });

                                    // }else{

                                    //SekmeAc(link1);

                                    //AmazonUrl = link1;
                                    //AbeUrl = data.AbeUrl;
                                    console.log('Sekmeler Açılacak!')
                                    if (host == 'sellercentral.amazon.com' || host == 'www.abebooks.com') {
                                        SekmeKapat(2)
                                    }
                                    //}
                                }
                            )
                        } else {
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {})
                            })
                        }
                    }
                    //}
                },
                error: function (req, textStatus, errorThrown) {
                    console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                    UrunGetir()
                },
            })
        })
    }, 2000)
}

const getBuyerInfoTab = async (blob, orderId) => {
    let blobs = { blobs: [blob] }
    return await axios
        .post('https://sellercentral.amazon.com/orders-st/resolve', blobs, {})
        .then((response) => {
            if (response.data[orderId] && response.data[orderId].buyerName) {
                return response.data[orderId].buyerName ?? undefined
            }
        })
        .catch((e) => {})
}
const getOrderRefundInfoTab = async (orderIds) => {
    return await axios
        .get(`https://sellercentral.amazon.com/orders-api/refund-status?orderId=${orderIds.toString()}`, {})
        .then((response) => {
            return response.data.refundSummaryList
        })
        .catch((e) => {
            return false
        })
}
const getItemTracking = async (shipID) => {
    return await axios
        .get(
            'https://sellercentral.amazon.com/fba/inbound/arest/addressbook/tracking/' +
                shipID +
                '/summary?pageSize=20&lastEntry=0',
            {},
            {
                headers: {
                    cookie: document.cookie,
                },
            }
        )
        .then((response) => {
            return response.data.trackingItemsPage.trackingItems[0].trackingId
        })
        .catch((e) => {})
}

let shipingData = []
var count = 0
async function BirinciLinkKontrol() {
    chrome.storage.sync.get(['orderNumber'], async function (item) {
        var host = window.location.host
        let shipIDs = []
        let loader = dialogModal(`Loading...`)
        let counter = 1

        // document.querySelector("#header-row > kat-table-cell:nth-child(2) a").click();
        // setTimeout(() => {
        //     document.querySelector("#pagination-dropdown > kat-dropdown").shadowRoot.querySelector("div.kat-select-container > div.select-options > div > div > slot > kat-option:nth-child(4) > div > div.standard-option-name").click();
        // }, 200);

        // $("#shipment_id_text").each(function(index){
        //     let shipId = $(this).text().split(',')[0];

        //     if(item.ShipID === shipId) {
        //         return;
        //     } else {
        //         shipIDs.push(shipId);
        //     }
        // });

        let promises = ''
        let promises2 = ''
        let pagenation = 250
        let cpagenation = 10
        let items = []
        let items2 = []

        for (let index = 0; index < pagenation; index++) {
            let url = `https://sellercentral.amazon.com/orders-api/search?limit=250&offset=${
                250 * index
            }&sort=order_date_desc&date-range=last-180&fulfillmentType=fba&orderStatus=all&forceOrdersTableRefreshTrigger=false`
            await axios
                .get(
                    url,
                    {},
                    {
                        headers: {
                            cookie: document.cookie,
                        },
                    }
                )
                .then((response) => {
                    console.log(response)
                    let responseData = response.data.orders

                    pagenation = response.data.total / 250 + 1

                    if (response.data.orders.length === 0) {
                        return items
                    }

                    if (response.data.total / 250 + 1 >= index) {
                        promises = Promise.all(
                            responseData.map(async (element) => {
                                console.log('1', 'aşama')
                                let buyerName = ''
                                if (element.blob != null)
                                    buyerName = await getBuyerInfoTab(element.blob, element.sellerOrderId)

                                //let cancelledOrders = await getCancelledOrders()
                                //let _trackingId = await getItemTracking(shipId)

                                if (element && element !== undefined && element.orderItems) {
                                    await element.orderItems.forEach((item) => {
                                        let data = {}
                                        data.asin = item.asin
                                        data.orderNumber = element.sellerOrderId
                                        data.price = item.unitPrice ? item.unitPrice.Amount : 0
                                        data.status = element.orderFulfillmentStatus
                                        data.customerType =
                                            element.badgeList.length > 0 ? 'Business Customer' : 'Customer'
                                        data.sku = item.sellerSku
                                        data.quantity = item.quantityOrdered
                                        data.fulfillmentmethod = element.fulfillmentMethod
                                        data.saleschannel = element.salesChannel
                                        data.sellerorderid = element.sellerOrderId
                                        data.saletime = element.orderDate
                                        data.customeroption = element.shippingService
                                        data.buyerName = buyerName
                                        data.refunded = false
                                        if (data.asin) {
                                            items.push(data)
                                        }
                                    })
                                }
                                return items
                            })
                        )
                    } else {
                        return items
                    }
                })
        }
        for (let index2 = 0; index2 < cpagenation; index2++) {
            let url = `https://sellercentral.amazon.com/orders-api/search?limit=250&offset=${
                250 * index2
            }&sort=order_date_desc&date-range=last-180&fulfillmentType=fba&orderStatus=canceled&forceOrdersTableRefreshTrigger=false`

            await axios
                .get(
                    url,
                    {},
                    {
                        headers: {
                            cookie: document.cookie,
                        },
                    }
                )
                .then((response) => {
                    console.log(response)
                    let responseData = response.data.orders

                    cpagenation = 1

                    if (response.data.orders.length === 0) {
                        return items2
                    }

                    if (response.data.total / 250 + 1 >= index2) {
                        promises2 = Promise.all(
                            responseData.map(async (element) => {
                                console.log('2', 'aşama')
                                let buyerName = ''
                                if (element.blob != null)
                                    buyerName = await getBuyerInfoTab(element.blob, element.sellerOrderId)
                                //let cancelledOrders = await getCancelledOrders()
                                //let _trackingId = await getItemTracking(shipId)

                                if (element && element !== undefined && element.orderItems) {
                                    await element.orderItems.forEach((item) => {
                                        let data = {}
                                        data.asin = item.asin
                                        data.orderNumber = element.sellerOrderId
                                        data.price = item.unitPrice ? item.unitPrice.Amount : 0
                                        data.status = element.orderFulfillmentStatus
                                        data.customerType =
                                            element.badgeList.length > 0 ? 'Business Customer' : 'Customer'
                                        data.sku = item.sellerSku
                                        data.quantity = item.quantityOrdered
                                        data.fulfillmentmethod = element.fulfillmentMethod
                                        data.saleschannel = element.salesChannel
                                        data.sellerorderid = element.sellerOrderId
                                        data.saletime = element.orderDate
                                        data.customeroption = element.shippingService
                                        data.buyerName = buyerName
                                        data.refunded = false
                                        if (data.asin) {
                                            items2.push(data)
                                        }
                                    })
                                }
                                return items2
                            })
                        )
                    } else {
                        return items2
                    }
                })
        }
        promises
            .then((values) => {
                promises2.then(async (values2) => {
                    let dataArray = $.merge(values[0], values2[0])
                    console.log('Result:', values[0])
                    console.log('Result2:', values2[0])
                    console.log('Result3:', dataArray)
                    var orderIds = $.map(dataArray, function (item) {
                        return item.orderNumber
                    })
                    let refunded = []
                    for (let index = 0; index <= parseInt(orderIds.length / 50); index++) {
                        //console.log(orderIds.slice(index * 50, index * 50 + 50))
                        let refunds = await getOrderRefundInfoTab(orderIds.slice(index * 50, index * 50 + 50))
                        refunded = $.merge(refunded, refunds)
                    }

                    console.log(refunded)
                    var refundedArray = $.map(refunded, function (item) {
                        return item.OrderId
                    })

                    console.log(refundedArray)

                    var refundedArray = $.map(refundedArray, function (item) {
                        return { orderNumber: item }
                    })

                    console.log(refundedArray)
                    SiparisTamamla(dataArray, refundedArray)
                })
            })
            .catch((e) => {
                console.log(e)
            })
        // console.log('tracking:' + tracks[1] + ' kargoFirma:' + firm[1])
    })
}

function getSayfa(adres) {
    var strText = null
    $.ajax({
        url: adres,
        async: false,
        dataType: 'text',
        success: function (text) {
            strText = text
        },
        error: function (http, message, exc) {
            strText = null
        },
    })

    return strText
}

function QueryStringOku(name, url) {
    if (!url) url = window.location.href
    name = name.replace(/[\[\]]/g, '\\$&')
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url)
    if (!results) return null
    if (!results[2]) return ''
    return decodeURIComponent(results[2].replace(/\+/g, ' '))
}

function SekmeKapat(sure) {
    setTimeout(function () {
        chrome.runtime.sendMessage({
            SekmeKapat: true,
        })
    }, sure * 1000)
}

function SekmeBilgileriGonder() {
    chrome.runtime.sendMessage({
        AktifSekmeBilgileri: true,
    })
}

function waitForElement(elementPath, callBack) {
    window.setTimeout(function () {
        if ($(elementPath).text().length > 0) {
            callBack(elementPath, $(elementPath))
        } else {
            waitForElement(elementPath, callBack)
        }
    }, 100)
}

function ClearData() {
    AppLog(log)
    AppLogGonder()
    sessionStorage.clear()
    chrome.runtime.sendMessage({
        LinkHata: 'LinkteError',
        YeniSekme: true,
    })
    clearTimeout(HataKontrol)
}

function AppLogGonder() {
    chrome.runtime.sendMessage({
        HataDurum: HataDurum,
        isStarted: isStarted,
        AppLog: logs,
    })
}

function AppLog(log) {
    var time = new Date().toLocaleString()
    var test = log + ' - ' + time
    var loglar = logs
    if (loglar.length < 6) {
        loglar.push(test)
    } else {
        loglar.splice(0, 1)
        loglar.push(test)
    }
    logs = loglar
    localStorage.setItem('LocalStorageAppLog', JSON.stringify(logs))
    chrome.storage.sync.set(
        {
            AppLog: test,
        },
        function () {}
    )
}

function SayfaGit(adres, time) {
    setTimeout(function () {
        window.location.href = adres
    }, parseInt(time) * 1000)
}

function BellekSil() {
    chrome.storage.sync.remove(['isStarted', 'Durum'], function () {})
}

var HataKontrol

function HataKontrolYap(time, msj2) {
    HataKontrol = setTimeout(function () {
        //location.reload();
        chrome.storage.sync.get(
            ['isStarted', 'PcName', 'UygulamaAdi', 'Durum', 'UrunID', 'MagazaAdi'],
            function (item) {
                var aciklama = ''
                if (msj2 == undefined) {
                    aciklama = ''
                } else {
                    aciklama = msj2
                }
                var msj = `Bilgisayar: ${item.PcName} Mağaza Adı: ${item.MagazaAdi}  Durum: ${item.Durum} iken extension çalışmayı durdurdu! ${aciklama}`
                var datam = {
                    ID: item.UrunID,
                    tip: 'newOrderBreak',
                    mesaj: msj,
                }
                console.log(msj)

                $.ajax({
                    type: 'post',
                    url: 'https://www.andromedaworkspace.com/Extension/ajaxCall',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                    },
                    cache: false,
                    dataType: 'json',
                    data: datam,
                    success: function (cevap) {
                        if (cevap.hata == 0) {
                            console.log('Hata: Hata Bilgisi Gönderilemedi!')
                        } else {
                            if (cevap.result) {
                                console.log(cevap.result)
                                setTimeout(function () {}, 3000)
                            }
                        }
                        console.log('Hata Bilgisi  Gönder Response!')
                    },
                    error: function (req, textStatus, errorThrown) {
                        console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                    },
                })
            }
        )
    }, parseInt(time) * 1000)
}

function getRandomInt(max) {
    return Math.floor(Math.random() * (max - 0 + 1)) + 0
}

function SekmeAc(link) {
    setTimeout(function () {
        console.log('Sekme Açılıyor: ' + link)
        chrome.runtime.sendMessage({
            YeniSekme: true,
            Url: link,
        })
    }, 1000)
}

//localStorage.removeItem("KontrolUrl1");
//localStorage.removeItem("KontrolUrl2");
// chrome.storage.local.set({
// 'SekmeCount': 0
// }, function () {
// });
// HataKontrolYap(75);
// chrome.storage.local.get(["RunCount"], function (item) {
// RunCount=item.RunCount
// });
// console.log(RunCount+1);

// chrome.storage.sync.set({
// "UrunID": "",
// "UrunGetirildi": true,
// "Durum": "TypeKontrol",
// "UrunFiyat": "",
// "AbeUrl": "",
// "AmazonUrl": "",
// "KontrolUrl1Hata": 0,
// "KontrolUrl2Hata": 0,
// "KontrolUrl1": "",
// "KontrolUrl2": "",
// "AdresEklendi":false,
// "RunCount": RunCount+1
// }, function () {
// linkKontrolCount = 0;
// urunKontrolCount = 0;
// var link1 = `https://www.amazon.com/Bedtime-Originals-Twinkle-Elephant-Plush/dp/B0771V1JZX`;
// //var link2 = `https://www.ebay.com/itm/Fluffy-Rugs-Anti-Skid-Shaggy-Area-Rug-Carpet-Dining-Room-Home-Bedroom-Floor-Mat/383128436979`;
// var link3 = `https://www.walmart.com/ip/Safavieh-California-Solid-Plush-Shag-Area-Rug-or-Runner/17691964`;
// var link4 = `https://www.wayfair.com/rugs/pdp/calvin-klein-la-hand-woven-shag-cobalt-blue-area-rug-drqh1001.html`;
// var link5 = `https://www.overstock.com/Home-Garden/Safavieh-Madison-Bohemian-Vintage-Cream-Multi-Distressed-Rug-8-x-10/12659869/product.html`;
// var link6 = `https://www.homedepot.com/p/Foss-Unbound-Smoke-Gray-Ribbed-6-ft-x-8-ft-Indoor-Outdoor-Area-Rug-CP45N41PJ1VH/202800194`;
// var link7 = `https://markandday.com/collections/deals-of-month/products/cambrai-modern-white-rug`;
// var link8 = `https://boutiquerugs.com/venezia-vnz-2309-area-rug/?button=shop_now`;
// // if(data.KontrolUrl1 == data.KontrolUrl2)
// // {
// // chrome.storage.sync.set({
// // "Durum": "FiyatKontrol"
// // },function () {
// // SiparisLinkleriGetir(data.ID, data.AmazonUrl, data.AbeUrl);
// // });

// // }else{
// SekmeAc(link1);
// //SekmeAc(link2);
// SekmeAc(link3);
// SekmeAc(link4);
// SekmeAc(link5);
// SekmeAc(link6);
// SekmeAc(link7);
// SekmeAc(link8);

// // AmazonUrl = data.AmazonUrl;
// // AbeUrl = data.AbeUrl;
// // console.log("Sekmeler Açılacak!");
// // if (host == "www.amazon.com" || host == "www.abebooks.com") {
// // SekmeKapat(2);
// // }
// //}
// });
