
export const useSum = () => {
    const unwrapCreatedDocuments = (createddocuments = []) => {
        if (Array.isArray(createddocuments)) return createddocuments
        if (Array.isArray(createddocuments?.value)) return createddocuments.value
        return []
    }

    const getCreatedDocumentLinkId = (value) => {
        if (value && typeof value === "object") return value.id
        return value
    }

    const getIncomingInvoiceSum = (invoice) => {
        let sum = 0
        invoice.accounts.forEach(account => {


            sum += account.amountTax
            sum += account.amountNet



        })
        return sum.toFixed(2)
    }

    const getCreatedDocumentSum = (createddocument,createddocuments = []) => {
        const availableCreatedDocuments = unwrapCreatedDocuments(createddocuments)
        let totalNet = 0
        let total19 = 0
        let total7 = 0




        createddocument.rows.forEach(row => {
            if(!['pagebreak','title','text'].includes(row.mode)){
                let rowPrice = Number(Number(row.quantity) * Number(row.price) * (1 - Number(row.discountPercent) /100) ).toFixed(3)
                totalNet = totalNet + Number(rowPrice)

                if(row.taxPercent === 19) {
                    total19 = total19 + Number(rowPrice * 0.19)
                } else if(row.taxPercent === 7) {
                    total7 = total7 + Number(rowPrice * 0.07)
                }
            }
        })




        let totalGross = Number(totalNet.toFixed(2)) + Number(total19.toFixed(2)) + Number(total7.toFixed(2))

        let totalGrossAlreadyPaid = 0


        createddocument.usedAdvanceInvoices.forEach(advanceInvoiceId => {
            let advanceInvoice = availableCreatedDocuments.find(i => i.id === advanceInvoiceId)

            if (!advanceInvoice) return

            let priceNet = advanceInvoice.rows.find(i => i.advanceInvoiceData).price

            let partSum = priceNet * ((100 + advanceInvoice.rows.find(i => i.advanceInvoiceData).taxPercent) / 100)

            totalGrossAlreadyPaid += partSum
        })


        let sumToPay = totalGross - totalGrossAlreadyPaid

        return Number(sumToPay.toFixed(2))
    }

    const hasCancellationInvoice = (createddocument, createddocuments = []) => {
        const availableCreatedDocuments = unwrapCreatedDocuments(createddocuments)

        return availableCreatedDocuments.some((document) => {
            return document.type === "cancellationInvoices"
                && document.state !== "Entwurf"
                && !document.archived
                && getCreatedDocumentLinkId(document.createddocument) === createddocument.id
        })
    }

    const getCreatedDocumentOpenAmount = (createddocument, createddocuments = []) => {
        let amountPaid = 0
        createddocument.statementallocations.forEach(allocation => amountPaid += allocation.amount)

        return Number((getCreatedDocumentSum(createddocument, createddocuments) - amountPaid).toFixed(2))
    }

    const getCreatedDocumentSumDetailed = (createddocument) => {
        let totalNet = 0
        let total19 = 0
        let total7 = 0

        createddocument.rows.forEach(row => {
            if(!['pagebreak','title','text'].includes(row.mode)){
                let rowPrice = Number(Number(row.quantity) * Number(row.price) * (1 - Number(row.discountPercent) /100) ).toFixed(3)
                totalNet = totalNet + Number(rowPrice)

                if(row.taxPercent === 19) {
                    total19 = total19 + Number(rowPrice * 0.19)
                } else if(row.taxPercent === 7) {
                    total7 = total7 + Number(rowPrice * 0.07)
                }
            }
        })

        //Title Sum

        let titleSums = {}
        let lastTitle = ""

        createddocument.rows.forEach(row => {
            if(row.mode === 'title'){
                titleSums[`${row.pos} - ${row.text}`] = 0
                lastTitle = `${row.pos} - ${row.text}`
            } else if(!['pagebreak','text'].includes(row.mode) && lastTitle !== ""){
                titleSums[lastTitle] = Number(titleSums[lastTitle]) + Number(Number(row.quantity) * Number(row.price) * (1 - Number(row.discountPercent) /100) )
            }
        })




        let totalGross = Number(totalNet.toFixed(2)) + Number(total19.toFixed(2)) + Number(total7.toFixed(2))

        let totalGrossAlreadyPaid = 0

        createddocument.usedAdvanceInvoices.forEach(advanceInvoiceId => {
            let advanceInvoice = createddocuments.value.find(i => i.id === advanceInvoiceId)

            let priceNet = advanceInvoice.rows.find(i => i.advanceInvoiceData).price

            let partSum = priceNet * ((100 + advanceInvoice.rows.find(i => i.advanceInvoiceData).taxPercent) / 100)

            totalGrossAlreadyPaid += partSum
        })

        console.log(totalGrossAlreadyPaid)

        let sumToPay = totalGross - totalGrossAlreadyPaid

        return {
            titleSums: titleSums,
            totalNet: totalNet,
            total19: total19,
            total7: total7,
            totalGross: totalGross,
            totalGrossAlreadyPaid: totalGrossAlreadyPaid,
            totalSumToPay: sumToPay
        }
    }

    const getIsPaid = (createddocument,createddocuments) => {
        return getCreatedDocumentOpenAmount(createddocument, createddocuments) === 0
    }

    const isOpenCreatedDocument = (createddocument, createddocuments = []) => {
        return ['invoices', 'advanceInvoices'].includes(createddocument.type)
            && createddocument.state === "Gebucht"
            && !hasCancellationInvoice(createddocument, createddocuments)
            && !getIsPaid(createddocument, createddocuments)
    }

    return {
        getIncomingInvoiceSum,
        getCreatedDocumentSum,
        getCreatedDocumentSumDetailed,
        getCreatedDocumentOpenAmount,
        getIsPaid,
        hasCancellationInvoice,
        isOpenCreatedDocument
    }

}
