"""
 * @author Xiaobo Sun, Daliang Chen
 * created  on 29.11.2025
 * @copyright (C) 2025 Sogood International GmbH - all rights reserved
 * @licence
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
"""
import logging
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from .setting import CONFIG, CompanyEntry

# Get an instance of a logger
logger = logging.getLogger('django')

@dataclass
class TaxItem:
    """
    用于映射 SQL 查询结果的订单数据模型。
    """

    order_id: str
    payment_date: datetime
    order_date: datetime
    payment_full_amount: str
    payment_already_paid: str
    payment_id: Optional[str]
    invoice_url: Optional[str]
    country: str
    selling_country: str
    lager_country: str
    systemId: str
    systemInvoiceId: str
    customerTaxId: str
    taxItemId: str
    konto: str
    tax: int

    def toDatev(self, company: CompanyEntry):
        logger.info("toDatev lager_country " + self.lager_country)
        logger.info("toDatev country " + self.country)
        logger.info("toDatev systemId " + self.systemId)
        logger.info("toDatev systemInvoiceId " + self.systemInvoiceId)
        logger.info("toDatev customerTaxId " + str(self.customerTaxId))
        logger.info("toDatev konto " + str(self.konto))
        logger.info("toDatev invoice_url " + str(self.invoice_url))
        logger.info("toDatev taxItemId " + str(self.taxItemId))
        logger.info("toDatev tax " + str(self.tax))

        # The formatted version (reconstructed column by column)
        ret = (
            "Umsatz;" + # column 1
            "SollHaben;" + # column 2
            ";" + # column 3
            ";" + # column 4
            ";" + # column 5
            ";" + # column 6
            "Konto;" + # column 7
            "Gegenkonto;" + # column 8
            "BU-Schluessel;" + # column 9
            "Belegdatum;" + # column 10
            "Belegfeld1;" + # column 11
            ";" + # column 12
            ";" + # column 13
            "Buchungstext;" + # column 14
            ";" + # column 15
            "\"\";" + # column 16
            ";" + # column 17
            ";" + # column 18
            ";" + # column 19
            "\"\";" + # column 20
            "\"\";" + # column 21
            "\"\";" + # column 22
            "\"\";" + # column 23
            "\"\";" + # column 24
            "\"\";" + # column 25
            "\"\";" + # column 26
            "\"\";" + # column 27
            "\"\";" + # column 28
            "\"\";" + # column 29
            "\"\";" + # column 30
            "\"\";" + # column 31
            "\"\";" + # column 32
            "\"\";" + # column 33
            "\"\";" + # column 34
            "\"\";" + # column 35
            "\"\";" + # column 36
            "\"\";" + # column 37
            "\"\";" + # column 38
            "\"\";" + # column 39
            "EU_UStID-Bestimmung;" + # column 40
            "Steuersatz-Bestimmung;" + # column 41
            "\"\";" + # column 42
            "\"\";" + # column 43
            "\"\";" + # column 44
            "\"\";" + # column 45
            "\"\";" + # column 46
            "\"\";" + # column 47
            "ZusatzinformationArt1;" + # column 48
            "ZusatzinformationInhalt1;" + # column 49
            "ZusatzinformationArt2;" + # column 50
            "ZusatzinformationInhalt2;" + # column 51
            "\"\";" + # column 52
            "\"\";" + # column 53
            "\"\";" + # column 54
            "\"\";" + # column 55
            "\"\";" + # column 56
            "\"\";" + # column 57
            "\"\";" + # column 58
            "\"\";" + # column 59
            "\"geliefert aus\";" + # column 60
            "\"selling_country\";" + # column 61
            "\"geliefert nach\";" + # column 62
            "\"country\";" + # column 63
            "\"\";" + # column 64
            "\"\";" + # column 65
            "\"\";" + # column 66
            "\"\";" + # column 67
            "\"\";" + # column 68
            "\"\";" + # column 69
            "\"\";" + # column 70
            "\"\";" + # column 71
            "\"\";" + # column 72
            "\"\";" + # column 73
            "\"\";" + # column 74
            "\"\";" + # column 75
            "\"\";" + # column 76
            "\"\";" + # column 77
            "\"\";" + # column 78
            "\"\";" + # column 79
            "\"\";" + # column 80
            "\"\";" + # column 81
            "\"\";" + # column 82
            "\"\";" + # column 83
            "\"\";" + # column 84
            "\"\";" + # column 85
            "\"\";" + # column 86
            "\"\";" + # column 87
            ";" + # column 88
            ";" + # column 89
            ";" + # column 90
            "\"\";" + # column 91
            "Veranlagungsjahr;" + # column 92
            ";" + # column 93
            ";" + # column 94
            "\"\";" + # column 95
            "\"\";" + # column 96
            ";" + # column 97
            "\"\";" + # column 98
            ";" + # column 99
            ";" + # column 100
            ";" + # column 101
            "\"\";" + # column 102
            ";" + # column 103
            ";" + # column 104
            "\"\";" + # column 105
            ";" + # column 106
            "\"\";" + # column 107
            ";" + # column 108
            "\"\";" + # column 109
            "\"\";" + # column 110
            ";" + # column 111
            "\"\";" + # column 112
            ";" + # column 113
            "0;" + # column 114
            ";" + # column 115
            ";" + # column 116
            ";" + # column 117
            "\"\";" + # column 118
            ";" + # column 119
            "\"\";" + # column 120
            ";" + # column 121
            ";" + # column 122
            "EU_UStID-Ursprung;" + # column 123
            "Steuersatz-Ursprung" # column 124 (Empty tail because original ends in ;)
        )

        Umsatz = float(self.payment_full_amount.replace(",", "."))
        if Umsatz is None:
            Umsatz = 0
        if Umsatz == 0:
            logger.info("toDatev: Umsatz is 0!")
            return None

        ret = ret.replace("Umsatz", abs(Umsatz).__round__(2).__str__().replace(".", ","))
        ret = ret.replace("SollHaben", "S" if Umsatz > 0 else "H")
        ret = ret.replace("Konto", self.konto)

        UStID = ""
        gKonto = ""
        is8400 = False
        # isMerchant = False
        # if self.customerTaxId is not None and self.customerTaxId != "":
        #    isMerchant = True
        #    UStID = self.customerTaxId
        isMerchant = self.tax == 0
        if (self.lager_country == "DE" 
            and self.tax == 19 
            and self.customerTaxId is not None 
            and self.customerTaxId.strip() != ""):
            logger.info("dupa: set8400")
            isMerchant = True
            is8400 = True
        if isMerchant:
            UStID = self.customerTaxId
        logger.info("toDatev isMerchant " + str(isMerchant))
        gegenKonto = [
            gegenkonto
            for gegenkonto in CONFIG.gegenkonto
            if gegenkonto.from_country == self.lager_country
            and gegenkonto.to_country == self.country
            and gegenkonto.isMerchant == isMerchant
        ]
        if not gegenKonto:
            gegenKonto = [
                gegenkonto
                for gegenkonto in CONFIG.gegenkonto
                if gegenkonto.from_country == "DE"
                and gegenkonto.to_country == "DE"
                and gegenkonto.isMerchant == isMerchant
            ]
        if gegenKonto:
            if company.id == 1759750295592:
                gKonto = "84000" if is8400 else gegenKonto[0].konto
            else:
                gKonto = "840000" if is8400 else gegenKonto[0].mkonto
        else:
            return None
        logger.info("toDatev gegenkonto " + gKonto)

        buS = gegenKonto[0].buKey
        ret = ret.replace("BU-Schluessel", "" if is8400 else buS)
        ret = ret.replace("Gegenkonto", gKonto)
        ret = ret.replace("Belegdatum", self.payment_date.strftime("%d%m"))
        ret = ret.replace("Belegfeld1", self.systemInvoiceId)
        ret = ret.replace("Buchungstext", self.systemId + " " + gegenKonto[0].to_country + " " + str(self.tax) + "%")
        ret = ret.replace("ZusatzinformationArt1", "")
        ret = ret.replace("ZusatzinformationInhalt1", "")
        ret = ret.replace("ZusatzinformationArt2", "")
        ret = ret.replace("ZusatzinformationInhalt2", "")
        ret = ret.replace("selling_country", gegenKonto[0].from_country)
        ret = ret.replace("country", gegenKonto[0].to_country)
        ret = ret.replace("Veranlagungsjahr", self.payment_date.strftime("%Y"))
        ret = ret.replace("EU_UStID-Bestimmung", UStID or gegenKonto[0].to_country)
        if gKonto.startswith("8125"):
            ret = ret.replace("Steuersatz-Bestimmung", "")
            ret = ret.replace("EU_UStID-Ursprung", gegenKonto[0].from_country)
            ret = ret.replace("Steuersatz-Ursprung", "0")
        elif buS == "TwoFourZero":
            ret = ret.replace("Steuersatz-Bestimmung", gegenKonto[0].tax)
            ret = ret.replace("EU_UStID-Ursprung", gegenKonto[0].from_country)
            ret = ret.replace("Steuersatz-Ursprung", "")
            ret = ret.replace("TwoFourZero", "")
        elif buS == "TwoFourTwo":
            ret = ret.replace("Steuersatz-Bestimmung", gegenKonto[0].tax)
            ret = ret.replace("EU_UStID-Ursprung", "")
            ret = ret.replace("Steuersatz-Ursprung", gegenKonto[0].tax)
            ret = ret.replace("TwoFourTwo", "")
        else:
            ret = ret.replace("Steuersatz-Bestimmung", "19" if is8400 else gegenKonto[0].tax)
            ret = ret.replace("EU_UStID-Ursprung", "")
            ret = ret.replace("Steuersatz-Ursprung", "")
        # logger.info(ret)
        return ret

