# -*- coding: utf-8 -*-
"""台费打折事实表"""

from ..base_loader import BaseLoader


class TableDiscountLoader(BaseLoader):
    """写入 fact_table_discount"""

    def upsert_discounts(self, records: list) -> tuple:
        if not records:
            return (0, 0, 0)

        sql = """
        INSERT INTO billiards.fact_table_discount (
            store_id,
            discount_id,
            adjust_type,
            applicant_id,
            applicant_name,
            operator_id,
            operator_name,
            ledger_amount,
            ledger_count,
            ledger_name,
            ledger_status,
            order_settle_id,
            order_trade_no,
            site_table_id,
            table_area_id,
            table_area_name,
            create_time,
            is_delete,
            raw_data
        )
        VALUES (
            %(store_id)s,
            %(discount_id)s,
            %(adjust_type)s,
            %(applicant_id)s,
            %(applicant_name)s,
            %(operator_id)s,
            %(operator_name)s,
            %(ledger_amount)s,
            %(ledger_count)s,
            %(ledger_name)s,
            %(ledger_status)s,
            %(order_settle_id)s,
            %(order_trade_no)s,
            %(site_table_id)s,
            %(table_area_id)s,
            %(table_area_name)s,
            %(create_time)s,
            %(is_delete)s,
            %(raw_data)s
        )
        ON CONFLICT (store_id, discount_id) DO UPDATE SET
            adjust_type     = EXCLUDED.adjust_type,
            applicant_id    = EXCLUDED.applicant_id,
            applicant_name  = EXCLUDED.applicant_name,
            operator_id     = EXCLUDED.operator_id,
            operator_name   = EXCLUDED.operator_name,
            ledger_amount   = EXCLUDED.ledger_amount,
            ledger_count    = EXCLUDED.ledger_count,
            ledger_name     = EXCLUDED.ledger_name,
            ledger_status   = EXCLUDED.ledger_status,
            order_settle_id = EXCLUDED.order_settle_id,
            order_trade_no  = EXCLUDED.order_trade_no,
            site_table_id   = EXCLUDED.site_table_id,
            table_area_id   = EXCLUDED.table_area_id,
            table_area_name = EXCLUDED.table_area_name,
            create_time     = EXCLUDED.create_time,
            is_delete       = EXCLUDED.is_delete,
            raw_data        = EXCLUDED.raw_data,
            updated_at      = now()
        RETURNING (xmax = 0) AS inserted
        """

        inserted, updated = self.db.batch_upsert_with_returning(
            sql, records, page_size=self._batch_size()
        )
        return (inserted, updated, 0)
