# -*- coding: utf-8 -*-
"""退款事实表加载器"""

from ..base_loader import BaseLoader


class RefundLoader(BaseLoader):
    """写入 fact_refund"""

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

        sql = """
        INSERT INTO billiards.fact_refund (
            store_id,
            refund_id,
            site_id,
            tenant_id,
            pay_amount,
            pay_status,
            pay_time,
            create_time,
            relate_type,
            relate_id,
            payment_method,
            refund_amount,
            action_type,
            pay_terminal,
            operator_id,
            channel_pay_no,
            channel_fee,
            is_delete,
            member_id,
            member_card_id,
            raw_data
        )
        VALUES (
            %(store_id)s,
            %(refund_id)s,
            %(site_id)s,
            %(tenant_id)s,
            %(pay_amount)s,
            %(pay_status)s,
            %(pay_time)s,
            %(create_time)s,
            %(relate_type)s,
            %(relate_id)s,
            %(payment_method)s,
            %(refund_amount)s,
            %(action_type)s,
            %(pay_terminal)s,
            %(operator_id)s,
            %(channel_pay_no)s,
            %(channel_fee)s,
            %(is_delete)s,
            %(member_id)s,
            %(member_card_id)s,
            %(raw_data)s
        )
        ON CONFLICT (store_id, refund_id) DO UPDATE SET
            site_id         = EXCLUDED.site_id,
            tenant_id       = EXCLUDED.tenant_id,
            pay_amount      = EXCLUDED.pay_amount,
            pay_status      = EXCLUDED.pay_status,
            pay_time        = EXCLUDED.pay_time,
            create_time     = EXCLUDED.create_time,
            relate_type     = EXCLUDED.relate_type,
            relate_id       = EXCLUDED.relate_id,
            payment_method  = EXCLUDED.payment_method,
            refund_amount   = EXCLUDED.refund_amount,
            action_type     = EXCLUDED.action_type,
            pay_terminal    = EXCLUDED.pay_terminal,
            operator_id     = EXCLUDED.operator_id,
            channel_pay_no  = EXCLUDED.channel_pay_no,
            channel_fee     = EXCLUDED.channel_fee,
            is_delete       = EXCLUDED.is_delete,
            member_id       = EXCLUDED.member_id,
            member_card_id  = EXCLUDED.member_card_id,
            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)
