# -*- coding: utf-8 -*-
"""台桌维度加载器"""

from ..base_loader import BaseLoader


class TableLoader(BaseLoader):
    """将台桌档案写入 dim_table"""

    def upsert_tables(self, records: list) -> tuple:
        """批量写入台桌档案"""
        if not records:
            return (0, 0, 0)

        sql = """
        INSERT INTO billiards.dim_table (
            store_id,
            table_id,
            site_id,
            area_id,
            area_name,
            table_name,
            table_price,
            table_status,
            table_status_name,
            light_status,
            is_rest_area,
            show_status,
            virtual_table,
            charge_free,
            only_allow_groupon,
            is_online_reservation,
            created_time,
            raw_data
        )
        VALUES (
            %(store_id)s,
            %(table_id)s,
            %(site_id)s,
            %(area_id)s,
            %(area_name)s,
            %(table_name)s,
            %(table_price)s,
            %(table_status)s,
            %(table_status_name)s,
            %(light_status)s,
            %(is_rest_area)s,
            %(show_status)s,
            %(virtual_table)s,
            %(charge_free)s,
            %(only_allow_groupon)s,
            %(is_online_reservation)s,
            %(created_time)s,
            %(raw_data)s
        )
        ON CONFLICT (store_id, table_id) DO UPDATE SET
            site_id                = EXCLUDED.site_id,
            area_id                = EXCLUDED.area_id,
            area_name              = EXCLUDED.area_name,
            table_name             = EXCLUDED.table_name,
            table_price            = EXCLUDED.table_price,
            table_status           = EXCLUDED.table_status,
            table_status_name      = EXCLUDED.table_status_name,
            light_status           = EXCLUDED.light_status,
            is_rest_area           = EXCLUDED.is_rest_area,
            show_status            = EXCLUDED.show_status,
            virtual_table          = EXCLUDED.virtual_table,
            charge_free            = EXCLUDED.charge_free,
            only_allow_groupon     = EXCLUDED.only_allow_groupon,
            is_online_reservation  = EXCLUDED.is_online_reservation,
            created_time           = COALESCE(EXCLUDED.created_time, dim_table.created_time),
            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)
