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++
                console.log(key)
                //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://www.amazon.com/') {
                        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')
                            let type = QueryStringOku('orderFilter')
                            if (type == 'cancelled') {
                                CancelledLinkKontrol()
                            } else {
                                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) {
    chrome.storage.sync.get(['MagazaAdi', 'UrunID', 'tracking', 'kargoFirma', 'ApiUrl'], function (item) {
        //MTip: Mağaza Tip (Amazon (0), Abe (1))
        let refundList = JSON.parse(localStorage.getItem('refund'))
        let cancelList = JSON.parse(localStorage.getItem('cancel'))
        let dataArray = $.merge(refundList, cancelList)
        console.log(dataArray)
        var datam = {
            magazaDeger: item.MagazaAdi,
            ReturnRequestArray: dataArray,
            tip: 'newBuyOrderReturnRequest',
        }
        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)
                SiparisTamamla()
            },
        })
    })
}

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: 'newShipmentLogStart',
            }
            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,
                timeout: 5000,
                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(
                                {
                                    ShipID: cevap.result[0].ShipmentId,
                                    ShipDate: cevap.result[0].ShipDate,
                                    UrunGetirildi: true,
                                    Durum: 'TypeKontrol',
                                    KontrolUrl1: '',
                                    KontrolUrl2: '',
                                },
                                function () {
                                    linkKontrolCount = 0
                                    urunKontrolCount = 0
                                    var link1 = cevap.result.Url
                                    SekmeAc(
                                        'https://www.amazon.com/gp/legacy/order-history?orderFilter=months-3&ref_=ppx_yo2ov_dt_b_filter_all_y2023'
                                    )
                                    SekmeAc(
                                        'https://www.amazon.com/gp/legacy/order-history?orderFilter=cancelled&ref_=ppx_yo2ov_dt_b_filter_all_y2023'
                                    )
                                    // 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 == 'www.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 getInfoTab = async (shipID) => {
    return await axios
        .get(
            'https://sellercentral.amazon.com/fba/inbound-shipment/summary/shipment-info/' + shipID,
            {},
            {
                headers: {
                    cookie: document.cookie,
                },
            }
        )
        .then((response) => {
            if (response.data && response.data.carrierShipmentInfo.totalCostEstimate) {
                return response.data.carrierShipmentInfo.totalCostEstimate.amount ?? undefined
            }
        })
        .catch((e) => {})
}
const getItems = async (shipID) => {
    return axios
        .get(
            'https://sellercentral.amazon.com/fba/wmsr/eligibilities/' +
                shipID +
                '?withInquiry=true&withDiscrepancies=true',
            {},
            {
                headers: {
                    cookie: document.cookie,
                },
            }
        )
        .then((response) => {
            return response.data.discrepancies
        })
        .catch((e) => {})
}
const getOrderDetail = async (orderId) => {
    let array = []
    await axios
        .get(
            `https://www.amazon.com/gp/your-account/order-details?ie=UTF8&orderID=${orderId}&ref=ppx_yo2ov_dt_b_order_details`,
            {},
            {
                headers: {
                    cookie: document.cookie,
                },
            }
        )
        .then((response) => {
            let responseData = response.data
            html = $.parseHTML(responseData)

            $('div.a-box-group.od-shipments div.a-row.shipment-top-row.js-shipment-info-container', html).each(
                function () {
                    let data = {}
                    let price = $(this)
                        .find('div.actions div.a-column.a-span3.a-text-right.a-span-last span')
                        .text()
                        .split('$')[1]
                        .trim()
                    let refundText = $(this).find('span.a-color-secondary').text().trim()
                    data.price = price
                    data.refundText = refundText
                    array.push(data)
                }
            )
            $('div.shipment-is-delivered', html).each(function () {
                let data = {}
                let price = ''
                // if ($(this).find('div.actions div.a-column.a-span3.a-text-right.a-span-last span')) {
                //     price = $(this)
                //         .find('div.actions div.a-column.a-span3.a-text-right.a-span-last span')
                //         .text()
                //         .split('$')[1]
                //         .trim()
                // }
                if ($(this).find('div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(4)')) {
                    price = $(this)
                        .find('div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(4)')
                        .text()
                        .split('$')[1]
                        .trim()
                }

                let refundText = $(this)
                    .find('div.a-row.shipment-top-row.js-shipment-info-container span.a-color-secondary')
                    .text()
                    .trim()

                data.price = price
                data.refundText = refundText
                array.push(data)
            })
            $('div.shipment div.a-row.shipment-top-row.js-shipment-info-container', html).each(function () {
                let data = {}
                let price = $(this)
                    .find('div.actions div.a-column.a-span3.a-text-right.a-span-last span')
                    .text()
                    .split('$')[1]
                    .trim()
                let refundText = $(this).find('span.a-color-secondary').text().trim()
                data.price = price
                data.refundText = refundText
                array.push(data)
            })
        })
        .catch((e) => {})
    return array
}

let shipingData = []
var count = 0
async function BirinciLinkKontrol() {
    chrome.storage.sync.get(['ShipID'], async function (item) {
        var host = window.location.host
        let shipIDs = []
        let loader = dialogModal(`Loading...`)
        let counter = 1
        let paginationCount = 1
        if (document.querySelector('.a-pagination')) {
            paginationCount =
                parseInt(
                    document.querySelector('.a-pagination').children[
                        document.querySelector('.a-pagination').children.length - 2
                    ].textContent
                ) ?? 1
        }
        let urlbase = `https://www.amazon.com/gp/your-account/order-history?ie=UTF8&orderFilter=months-3&ref_=ppx_yo2ov_dt_b_filter_all_y2023#tab/yoOrdersTabination/pagination/`
        if (window.location.href.indexOf('/gp/legacy') != -1) {
            urlbase = `https://www.amazon.com/gp/legacy/order-history?ie=UTF8&orderFilter=months-3&search=&startIndex=`
        }
        let urls = []
        for (let index = 0; index < paginationCount; index++) {
            let url = ''
            if (window.location.href.indexOf('/gp/legacy') != -1) {
                url = urlbase + index * 10
            } else {
                url = urlbase + 1
            }

            console.log(url)
            urls.push(url)
        }

        let promises = []
        await urls.map((url) => {
            const request = new Promise((resolve, reject) => {
                axios
                    .get(
                        url,
                        {},
                        {
                            headers: {
                                cookie: document.cookie,
                            },
                        }
                    )
                    .then(async (response) => {
                        let responseData = response.data
                        html = $.parseHTML(responseData)
                        let orderStatusList = []
                        let dataPromises = []
                        await $('div.js-order-card', html).each(function () {
                            let orderNumber = $(this, html).find('.yohtmlc-order-id').find('bdi').text()

                            let deliveries = $(this, html).find('div.a-box.shipment')

                            deliveries.map(async function () {
                                const req = new Promise(async (resolve, reject) => {
                                    let status = $(this, html).find('span.a-size-medium').text().trim()
                                    let refundArray = []
                                    if (status == 'Refunded') {
                                        refundArray = await getOrderDetail(orderNumber)
                                        console.log('log3', refundArray)
                                    }

                                    let _asin = $(this, html)
                                        .find('div > div.a-fixed-left-grid-col > div:nth-child(1) > a')
                                        .attr('href')
                                        .split('/')[3]
                                    //console.log(asin)
                                    let itemData = {
                                        orderNumber,
                                        asin: _asin,
                                        status,
                                        refundText:
                                            refundArray != undefined
                                                ? refundArray.length > 0
                                                    ? refundArray[0].refundText
                                                    : ''
                                                : '',
                                        refundPrice:
                                            refundArray != undefined
                                                ? refundArray.length > 0
                                                    ? refundArray[0].price
                                                    : ''
                                                : '',
                                    }
                                    console.log(itemData)
                                    resolve(itemData)
                                })
                                dataPromises.push(req)
                            })
                            //console.log(orderStatusList, '-------')
                        })
                        await $('#orderCard', html).each(function () {
                            console.log($(this, html).find('#orderCardHeader').text())
                            let orderNumber = $(this, html)
                                .find('#orderCardHeader')
                                .find('.a-box-inner')
                                .find('#orderIdField')
                                .text()
                                .trim()
                                .split('\n')[2]

                            console.log(orderNumber)

                            let deliveries = $(this, html).find('#orderCardDeliveryBox')

                            deliveries.map(async function () {
                                const req = new Promise(async (resolve, reject) => {
                                    let status = $(this, html)
                                        .find('div > div:nth-child(1) > div > div.a-row.a-size-medium > span')
                                        .text()
                                        .trim()
                                    let refundArray = []
                                    if (status == 'Refunded') {
                                        refundArray = await getOrderDetail(orderNumber)
                                    }

                                    let _asin = $(this, html)
                                        .find('#itemDetail > div.a-column.a-span2.imageContainer > a')
                                        .attr('href')
                                        .split('/')[3]

                                    let itemData = {
                                        orderNumber,
                                        asin: _asin,
                                        status,
                                        refundText:
                                            refundArray != undefined
                                                ? refundArray.length > 0
                                                    ? refundArray[0].refundText
                                                    : ''
                                                : '',
                                        refundPrice:
                                            refundArray != undefined
                                                ? refundArray.length > 0
                                                    ? refundArray[0].price
                                                    : ''
                                                : '',
                                    }
                                    console.log(itemData)
                                    resolve(itemData)
                                })
                                dataPromises.push(req)
                            })

                            //console.log(orderStatusList, '-------')
                        })
                        Promise.all(dataPromises).then((values) => {
                            resolve(values)
                        })
                    })
            })
            promises.push(request)
        })

        Promise.all(promises).then((values) => {
            console.log(values)
            let finalArray = []
            for (let index = 0; index < values.length; index++) {
                finalArray = $.merge(values[index], finalArray)
            }
            // console.log(finalArray)
            // finalArray = finalArray.filter((item) => {
            //     if (item.status.indexOf('Delivered') == -1) return item
            // })
            console.table(finalArray)
            localStorage.setItem('refund', JSON.stringify(finalArray))
            chrome.storage.sync.set(
                {
                    KontrolUrl1: 'deneme',
                },
                function () {
                    SekmeKapat(1)
                }
            )
        })
        // console.log('tracking:' + tracks[1] + ' kargoFirma:' + firm[1])
    })
}

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

        let paginationCount = 1
        if (document.querySelector('.a-pagination')) {
            paginationCount =
                parseInt(
                    document.querySelector('.a-pagination').children[
                        document.querySelector('.a-pagination').children.length - 2
                    ].textContent
                ) ?? 1
        }

        let urlbase = `https://www.amazon.com/gp/your-account/order-history?ie=UTF8&orderFilter=cancelled&search=&startIndex=`
        if (window.location.href.indexOf('/gp/legacy') != -1) {
            urlbase = `https://www.amazon.com/gp/legacy/order-history?ie=UTF8&orderFilter=cancelled&search=&startIndex=`
        }
        let urls = []
        for (let index = 0; index < paginationCount; index++) {
            let url = urlbase + index * 10
            urls.push(url)
        }

        let promises = []
        await urls.map(async (url) => {
            const request = new Promise((resolve, reject) => {
                axios
                    .get(
                        url,
                        {},
                        {
                            headers: {
                                cookie: document.cookie,
                            },
                        }
                    )
                    .then(async (response) => {
                        let responseData = response.data
                        html = $.parseHTML(responseData)
                        let dataPromises = []
                        await $('div.js-order-card', html).each(function () {
                            let orderNumber = $(this, html).find('.yohtmlc-order-id').find('bdi').text()

                            let deliveries = $(this, html).find('div.yohtmlc-item')

                            deliveries.map(async function () {
                                const req = new Promise(async (resolve, reject) => {
                                    let status = 'Cancelled'

                                    let _asin = $(this, html).find('.a-link-normal').attr('href').split('/')[3]
                                    //console.log(asin)
                                    let itemData = {
                                        orderNumber,
                                        asin: _asin,
                                        status,
                                    }
                                    console.log(itemData)
                                    resolve(itemData)
                                })
                                dataPromises.push(req)
                            })

                            //console.log(orderStatusList, '-------')
                        })
                        await $('#orderCard', html).each(function () {
                            console.log($(this, html).find('#orderIdField > span > div').text())

                            let orderNumber = $(this, html)
                                .find('#orderIdField > span > div')
                                .text()
                                .trim()
                                .split('\n')[2]

                            console.log(orderNumber)

                            let deliveries = $(this, html).find('#orderCardDeliveryBox')

                            deliveries.map(async function () {
                                const req = new Promise(async (resolve, reject) => {
                                    let status = $(this, html)
                                        .find('div > div:nth-child(1) > div > div.a-row.a-size-medium > span')
                                        .text()
                                        .trim()
                                    let refundArray = []
                                    if (status == 'Refunded') {
                                        refundArray = await getOrderDetail(orderNumber)
                                    }

                                    let _asin = $(this, html)
                                        .find('#itemDetail > div.a-column.a-span2.imageContainer > a')
                                        .attr('href')
                                        .split('/')[3]
                                    //console.log(asin)
                                    let itemData = {
                                        orderNumber,
                                        asin: _asin,
                                        status,
                                        refundText:
                                            refundArray != undefined
                                                ? refundArray.length > 0
                                                    ? refundArray[0].refundText
                                                    : ''
                                                : '',
                                        refundPrice:
                                            refundArray != undefined
                                                ? refundArray.length > 0
                                                    ? refundArray[0].price
                                                    : ''
                                                : '',
                                    }
                                    console.log(itemData)
                                    resolve(itemData)
                                })
                                dataPromises.push(req)
                            })

                            //console.log(orderStatusList, '-------')
                        })
                        Promise.all(dataPromises).then((values) => {
                            resolve(values)
                        })
                    })
            })
            promises.push(request)
        })

        Promise.all(promises).then((values) => {
            console.log(values)
            let finalArray = []
            for (let index = 0; index < values.length; index++) {
                finalArray = $.merge(values[index], finalArray)
            }
            console.table(finalArray)
            localStorage.setItem('cancel', JSON.stringify(finalArray))
            chrome.storage.sync.set(
                {
                    KontrolUrl2: 'deneme',
                },
                function () {
                    SekmeKapat(1)
                }
            )
        })

        // 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);
// // }
// //}
// });
