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

var AmazonUrl = ''
var UrunID = ''
var MagazaAdi = ''
var kayitEdilsinDurumu = true // Varsayılan olarak aktif

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)
    }
    if (message.action === 'setKayitDurumu') {
        kayitEdilsinDurumu = message.kayitEdilsin
        console.log('Kayıt durumu güncellendi: ' + kayitEdilsinDurumu)
        sendResponse({status: "Kayıt durumu başarıyla güncellendi"})
    }
    return true
})

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++
                if (linkKontrolCount == 2) {
                    setTimeout(function () {
                        SiparisTamamla()
                    }, 2000)
                }
            }
        } else if (key == 'AmzUrunList') {
            storageChange = changes[key]
            if (storageChange.newValue != undefined && storageChange.newValue != null) {
                urunKontrolCount++
                if (urunKontrolCount == 1) {
                    setTimeout(function () {
                        console.log(' UrunListeleriniGonder(); onchanged çağrıldı')
                        UrunListeleriniGonder()
                    }, 2000)
                }
            }
        }
    }
})

$(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',
            'AmazonUrl',
            'UrunFiyat',
            'MagazaAdi',
            'RequestTime',
        ],
        function (item) {
            setTimeout(async function () {
                if (item.isStarted == true) {
                    MagazaAdi = item.MagazaAdi
                    AmazonUrl = item.AmazonUrl
                    console.log(item.Durum)
                    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) {
                            UrunGetir()
                            SekmeBilgileriGonder()
                        } else {
                            console.log('düşün')
                        }
                    } else {
                        console.log(item.Durum + 'TypeKontrol')
                        if (item.Durum == 'TypeKontrol') {
                            console.log('TypeKontrol')

                            BirinciLinkKontrol()
                        }
                    }
                }
            }, parseInt(item.RequestTime) * 1000)
        }
    )
})

// At the beginning of the file, after variable declarations
chrome.storage.sync.get(['kayitEdilsin'], function (result) {
    if (result.kayitEdilsin !== undefined) {
        kayitEdilsinDurumu = result.kayitEdilsin;
        console.log('Kayıt durumu yüklendi: ' + kayitEdilsinDurumu);
    }
});

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) {
    if (!kayitEdilsinDurumu) {
        console.log('Siparişler kaydedilmiyor - ayarlarda devre dışı bırakıldı')
        $('.extDialog').remove()
        dialogModal('Sipariş kaydedilmedi (Ayarlarda devre dışı). Yeni siparişe geçiliyor.')
        return // Fonksiyondan çık
    }
    chrome.storage.sync.get(['MagazaAdi', 'UrunID', 'tracking', 'kargoFirma', 'ApiUrl'], function (item) {
        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')
                    }
                }
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
            },
        })
    })
}

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)
            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) {
                        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'
                                    )

                                    console.log('Sekmeler Açılacak!')
                                    if (host == 'sellercentral.amazon.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
        })
}

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

        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)

                                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)

                                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++) {
                        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)
            })
    })
}

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 () {
        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)
}
