# -*- coding: utf-8 -*-
"""券核销事实表"""

from ..base_loader import BaseLoader


class CouponUsageLoader(BaseLoader):
    """写入 fact_coupon_usage"""

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

        sql = """
        INSERT INTO billiards.fact_coupon_usage (
            store_id,
            usage_id,
            coupon_code,
            coupon_channel,
            coupon_name,
            sale_price,
            coupon_money,
            coupon_free_time,
            use_status,
            create_time,
            consume_time,
            operator_id,
            operator_name,
            table_id,
            site_order_id,
            group_package_id,
            coupon_remark,
            deal_id,
            certificate_id,
            verify_id,
            is_delete,
            raw_data
        )
        VALUES (
            %(store_id)s,
            %(usage_id)s,
            %(coupon_code)s,
            %(coupon_channel)s,
            %(coupon_name)s,
            %(sale_price)s,
            %(coupon_money)s,
            %(coupon_free_time)s,
            %(use_status)s,
            %(create_time)s,
            %(consume_time)s,
            %(operator_id)s,
            %(operator_name)s,
            %(table_id)s,
            %(site_order_id)s,
            %(group_package_id)s,
            %(coupon_remark)s,
            %(deal_id)s,
            %(certificate_id)s,
            %(verify_id)s,
            %(is_delete)s,
            %(raw_data)s
        )
        ON CONFLICT (store_id, usage_id) DO UPDATE SET
            coupon_code      = EXCLUDED.coupon_code,
            coupon_channel   = EXCLUDED.coupon_channel,
            coupon_name      = EXCLUDED.coupon_name,
            sale_price       = EXCLUDED.sale_price,
            coupon_money     = EXCLUDED.coupon_money,
            coupon_free_time = EXCLUDED.coupon_free_time,
            use_status       = EXCLUDED.use_status,
            create_time      = EXCLUDED.create_time,
            consume_time     = EXCLUDED.consume_time,
            operator_id      = EXCLUDED.operator_id,
            operator_name    = EXCLUDED.operator_name,
            table_id         = EXCLUDED.table_id,
            site_order_id    = EXCLUDED.site_order_id,
            group_package_id = EXCLUDED.group_package_id,
            coupon_remark    = EXCLUDED.coupon_remark,
            deal_id          = EXCLUDED.deal_id,
            certificate_id   = EXCLUDED.certificate_id,
            verify_id        = EXCLUDED.verify_id,
            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)
