# -*- coding: utf-8 -*-
"""团购/套餐定义加载器"""

from ..base_loader import BaseLoader


class PackageDefinitionLoader(BaseLoader):
    """写入 dim_package_coupon"""

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

        sql = """
        INSERT INTO billiards.dim_package_coupon (
            store_id,
            package_id,
            package_code,
            package_name,
            table_area_id,
            table_area_name,
            selling_price,
            duration_seconds,
            start_time,
            end_time,
            type,
            is_enabled,
            is_delete,
            usable_count,
            creator_name,
            date_type,
            group_type,
            coupon_money,
            area_tag_type,
            system_group_type,
            card_type_ids,
            raw_data
        )
        VALUES (
            %(store_id)s,
            %(package_id)s,
            %(package_code)s,
            %(package_name)s,
            %(table_area_id)s,
            %(table_area_name)s,
            %(selling_price)s,
            %(duration_seconds)s,
            %(start_time)s,
            %(end_time)s,
            %(type)s,
            %(is_enabled)s,
            %(is_delete)s,
            %(usable_count)s,
            %(creator_name)s,
            %(date_type)s,
            %(group_type)s,
            %(coupon_money)s,
            %(area_tag_type)s,
            %(system_group_type)s,
            %(card_type_ids)s,
            %(raw_data)s
        )
        ON CONFLICT (store_id, package_id) DO UPDATE SET
            package_code      = EXCLUDED.package_code,
            package_name      = EXCLUDED.package_name,
            table_area_id     = EXCLUDED.table_area_id,
            table_area_name   = EXCLUDED.table_area_name,
            selling_price     = EXCLUDED.selling_price,
            duration_seconds  = EXCLUDED.duration_seconds,
            start_time        = EXCLUDED.start_time,
            end_time          = EXCLUDED.end_time,
            type              = EXCLUDED.type,
            is_enabled        = EXCLUDED.is_enabled,
            is_delete         = EXCLUDED.is_delete,
            usable_count      = EXCLUDED.usable_count,
            creator_name      = EXCLUDED.creator_name,
            date_type         = EXCLUDED.date_type,
            group_type        = EXCLUDED.group_type,
            coupon_money      = EXCLUDED.coupon_money,
            area_tag_type     = EXCLUDED.area_tag_type,
            system_group_type = EXCLUDED.system_group_type,
            card_type_ids     = EXCLUDED.card_type_ids,
            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)
