# -*- coding: utf-8 -*-
"""库存变动事实表"""

from ..base_loader import BaseLoader


class InventoryChangeLoader(BaseLoader):
    """写入 fact_inventory_change"""

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

        sql = """
        INSERT INTO billiards.fact_inventory_change (
            store_id,
            change_id,
            site_goods_id,
            stock_type,
            goods_name,
            change_time,
            start_qty,
            end_qty,
            change_qty,
            unit,
            price,
            operator_name,
            remark,
            goods_category_id,
            goods_second_category_id,
            raw_data
        )
        VALUES (
            %(store_id)s,
            %(change_id)s,
            %(site_goods_id)s,
            %(stock_type)s,
            %(goods_name)s,
            %(change_time)s,
            %(start_qty)s,
            %(end_qty)s,
            %(change_qty)s,
            %(unit)s,
            %(price)s,
            %(operator_name)s,
            %(remark)s,
            %(goods_category_id)s,
            %(goods_second_category_id)s,
            %(raw_data)s
        )
        ON CONFLICT (store_id, change_id) DO UPDATE SET
            site_goods_id            = EXCLUDED.site_goods_id,
            stock_type               = EXCLUDED.stock_type,
            goods_name               = EXCLUDED.goods_name,
            change_time              = EXCLUDED.change_time,
            start_qty                = EXCLUDED.start_qty,
            end_qty                  = EXCLUDED.end_qty,
            change_qty               = EXCLUDED.change_qty,
            unit                     = EXCLUDED.unit,
            price                    = EXCLUDED.price,
            operator_name            = EXCLUDED.operator_name,
            remark                   = EXCLUDED.remark,
            goods_category_id        = EXCLUDED.goods_category_id,
            goods_second_category_id = EXCLUDED.goods_second_category_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)
