// pdfFillDataDukeEnergy.js

const pdfFillData = require('./pdfFillData'); // Родительский класс

class pdfFillDataDukeEnergy extends pdfFillData {
    constructor() {
        super('DukeEnergy');

        // Коэффициент для коррекции Y для базовой линии.
        // Настройте это значение (0.8 - 1.0) после первых тестов для лучшего выравнивания.
        this.baselineCorrectionFactor = 0.85;

        // Инициализируем свойства пустыми значениями.
        // Они будут заполнены в setFields из POST-запроса.
        this.bill_date = '';
        this.service_period_from = '';
        this.service_period_to = '';
        this.account_number = '';
        this.customer_name = '';
        this.service_address_line1 = '';
        this.service_address_line2 = '';
        this.previous_amount_due = '';
        this.payment_received_date = '';
        this.payment_received_amount = '';
        this.current_electric_charges = '';
        this.current_lighting_charges = '';
        this.taxes = ''; // Будет рассчитано
        this.total_amount_due_date = '';
        this.total_amount_due_value = ''; // Будет рассчитано
        this.electric_usage_current_month_kwh = '';
        this.electric_usage_jul_2021_kwh = '';
        this.electric_usage_12_month_avg_kwh = '';
        this.remit_account_number = '';
        this.remit_amount_due_value = '';
        this.remit_due_date = '';
        this.remit_customer_name = '';
        this.remit_address_line1 = '';
        this.remit_address_line2 = '';
        this.barcode_number = '';
        this.meter_number = '';
        this.energy_used_kwh = '';
        this.basic_customer_charge = '';
        this.energy_charge_details = '';
        this.energy_charge_amount = '';
        this.total_taxes_detail = '';
        this.total_taxes_amount = '';

        this.dataMap = [];
    }

    // Вспомогательная функция для очистки сумм от знака '$'
    _cleanAmount(amount) {
        if (typeof amount !== 'string') return 0;
        return parseFloat(amount.replace('$', '').trim()) || 0;
    }

    async setFields(fields) {
        // 1. Заполняем свойства класса из объекта fields (данные из POST-запроса)
        this.bill_date = fields.bill_date;
        this.service_period_from = fields.service_period_from;
        this.service_period_to = fields.service_period_to;
        this.account_number = fields.account_number;
        this.customer_name = fields.customer_name;
        this.service_address_line1 = fields.service_address_line1;
        this.service_address_line2 = fields.service_address_line2;
        this.payment_received_date = fields.payment_received_date;
        this.total_amount_due_date = fields.total_amount_due_date;
        this.electric_usage_current_month_kwh = fields.electric_usage_current_month_kwh;
        this.electric_usage_jul_2021_kwh = fields.electric_usage_jul_2021_kwh;
        this.electric_usage_12_month_avg_kwh = fields.electric_usage_12_month_avg_kwh;
        this.remit_address_line2 = fields.remit_address_line2;
        this.barcode_number = fields.barcode_number;
        this.meter_number = fields.meter_number;
        this.energy_used_kwh = fields.energy_used_kwh;
        this.basic_customer_charge = fields.basic_customer_charge;
        this.energy_charge_details = fields.energy_charge_details;
        this.energy_charge_amount = fields.energy_charge_amount;
        this.total_taxes_detail = fields.total_taxes_detail;
        
        // Преобразуем числовые строки в числа для расчетов
        const prevAmountNum = this._cleanAmount(fields.previous_amount_due);
        const paymentReceivedNum = this._cleanAmount(fields.payment_received_amount); // Ожидается отрицательное число
        const electricChargesNum = this._cleanAmount(fields.current_electric_charges);
        const lightingChargesNum = this._cleanAmount(fields.current_lighting_charges);

        // Присваиваем очищенные строки для отображения
        this.previous_amount_due = `$${prevAmountNum.toFixed(2)}`;
        this.payment_received_amount = `${paymentReceivedNum.toFixed(2)}`;
        this.current_electric_charges = `${electricChargesNum.toFixed(2)}`;
        this.current_lighting_charges = `${lightingChargesNum.toFixed(2)}`;


        // 2. Рассчитываем налогооблагаемую базу
        const taxableAmount = electricChargesNum + lightingChargesNum;

        // 3. Формируем полный адрес и получаем налоговые ставки от TaxJar
        const fullAddress = `${this.service_address_line1}, ${this.service_address_line2}`;
        let taxValue = 0;
        try {
            const taxInfo = await this.getTaxRateByAddress(fullAddress);
            if (taxInfo && taxInfo.combinedRate) {
                taxValue = taxableAmount * taxInfo.combinedRate;
            } else {
                console.warn("Could not retrieve valid tax rate from TaxJar. Tax will be 0.");
            }
        } catch (error) {
            console.error("Failed to calculate taxes via TaxJar. Tax will be 0. Error:", error.message);
            // Оставляем taxValue = 0
        }
        this.taxes = `${taxValue.toFixed(2)}`;
        this.total_taxes_amount = `$${taxValue.toFixed(2)}`;


        // 4. Рассчитываем итоговую сумму
        const totalDueNum = prevAmountNum + paymentReceivedNum + electricChargesNum + lightingChargesNum + taxValue;
        this.total_amount_due_value = `$${totalDueNum.toFixed(2)}`;


        // 5. Заполняем поля для отрывного купона
        this.remit_account_number = this.account_number;
        this.remit_amount_due_value = this.total_amount_due_value;
        this.remit_due_date = `by ${this.total_amount_due_date}`;
        this.remit_customer_name = this.customer_name;
        this.remit_address_line1 = this.service_address_line1;
    }

    async draw() {
        // ВАЖНО: Замените значения x_ill, y_ill, size, ifont на точные,
        // измеренные в Adobe Illustrator (опорная точка - верхний левый угол блока).

        this.dataMap = [
            // --- PAGE 1 ---
            { ipage: 0, field: `Page 1 of 3`, x_ill: 525.5, y_ill: 28.7, size: 9, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.customer_name, x_ill: 345.2, y_ill: 78.9, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.service_address_line1, x_ill: 345.2, y_ill: 91.5, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.service_address_line2, x_ill: 345.2, y_ill: 104.1, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.bill_date, x_ill: 470.0, y_ill: 78.9, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: `${this.service_period_from} - ${this.service_period_to}`, x_ill: 470.0, y_ill: 91.5, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.account_number, x_ill: 443.52, y_ill: 110.84, size: 10, ifont: 1, cR: 0, cG: 0, cB: 0 }, // Пример с ifont: 1 (жирный)
            { ipage: 0, field: this.previous_amount_due, x_ill: 165.0, y_ill: 172.5, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: `Payment Received ${this.payment_received_date}`, x_ill: 58.0, y_ill: 187.5, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.payment_received_amount, x_ill: 165.0, y_ill: 187.5, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.current_electric_charges, x_ill: 165.0, y_ill: 202.5, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.current_lighting_charges, x_ill: 165.0, y_ill: 217.5, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.taxes, x_ill: 165.0, y_ill: 232.5, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: `Total Amount Due ${this.total_amount_due_date}`, x_ill: 58.0, y_ill: 248.0, size: 10, ifont: 1, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.total_amount_due_value, x_ill: 165.0, y_ill: 247.0, size: 12, ifont: 1, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.remit_account_number, x_ill: 440, y_ill: 648, size: 10, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 0, field: this.remit_amount_due_value, x_ill: 440, y_ill: 658, size: 12, ifont: 1, cR: 0, cG: 0, cB: 0 },

            // --- PAGE 3 --- (Примеры, нуждаются в измерении)
            { ipage: 2, field: `Page 3 of 3`, x_ill: 525.5, y_ill: 28.7, size: 9, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 2, field: this.basic_customer_charge, x_ill: 500, y_ill: 240, size: 9, ifont: 0, cR: 0, cG: 0, cB: 0 },
            { ipage: 2, field: this.total_taxes_amount, x_ill: 500, y_ill: 590, size: 9, ifont: 0, cR: 0, cG: 0, cB: 0 },
        ];

        // Цикл отрисовки, который автоматически пересчитывает координаты
        for (const item of this.dataMap) {
            const page = this.getPageByIndex(item.ipage);
            if (!page || !this.getCustomerFontByIndex(item.ifont)) {
                console.warn(`Skipping draw for item due to missing page or font:`, item);
                continue;
            }

            const pageHeight = this.getPageHeight(item.ipage);
            if (pageHeight === undefined) {
                console.warn(`Could not get page height for page ${item.ipage}. Skipping item:`, item);
                continue;
            }

            const x_pdf = item.x_ill;
            const y_pdf = pageHeight - item.y_ill - (item.size * this.baselineCorrectionFactor);

            await super.draw(
                item.ipage,
                item.field,
                x_pdf,
                y_pdf,
                item.size,
                item.ifont,
                item.cR,
                item.cG,
                item.cB
            );
        }
    }

    async saveData(host, outputDir) {
        return await super.saveData(host, outputDir, this.getPdfDocumentName());
    }
}

module.exports = pdfFillDataDukeEnergy;