#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TEMU EPR授权代理费详情表模型
frozenType: epr_authorization_agent_fee
"""

from sqlalchemy import create_engine, Column, String, Text, DateTime, Integer, DECIMAL, Date, Index
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime, date
import json
import re

Base = declarative_base()


class TemuRestrictEprAuthorizationAgentFee(Base):
    """
    TEMU EPR授权代理费详情表
    """
    __tablename__ = 'temu_restrict_epr_authorization_agent_fee'

    # 主键ID (自增)
    id = Column(Integer, primary_key=True, autoincrement=True, comment='主键ID')

    # 商城和日期
    mall_id = Column(String(50), nullable=False, comment='商城ID')
    record_date = Column(Date, nullable=False, comment='记录日期')

    # 详情字段
    billing_cycle = Column(String(20), nullable=True, comment='费用周期')
    cert_name = Column(String(100), nullable=True, comment='环保品类')
    region_name = Column(String(100), nullable=True, comment='销售站点')
    payment_cycle = Column(String(50), nullable=True, comment='缴费周期')
    amount = Column(String(50), nullable=True, comment='限制金额文本')
    amount_value = Column(DECIMAL(12, 2), nullable=True, comment='限制金额数值')
    currency = Column(String(10), nullable=True, comment='货币类型')
    state = Column(String(50), nullable=True, comment='状态')
    freeze_start_time = Column(DateTime, nullable=True, comment='限制开始时间')
    source_dr = Column(String(50), nullable=True, comment='地区')

    # 时间戳
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    # 定义索引
    __table_args__ = (
        Index('ix_epr_agent_mall_id', 'mall_id'),
        Index('ix_epr_agent_record_date', 'record_date'),
        Index('ix_epr_agent_billing_cycle', 'billing_cycle'),
        Index('ix_epr_agent_mall_date', 'mall_id', 'record_date'),
        Index('ix_epr_agent_unique', 'mall_id', 'record_date', 'billing_cycle', 'cert_name', 'region_name', unique=True),
    )

    def __repr__(self):
        return f"<TemuRestrictEprAuthorizationAgentFee(id={self.id}, billing_cycle='{self.billing_cycle}', cert_name='{self.cert_name}')>"


class TemuRestrictEprAuthorizationAgentFeeManager:
    """
    TEMU EPR授权代理费数据管理器
    """

    def __init__(self, database_url):
        self.engine = create_engine(database_url, echo=False)
        self.Session = sessionmaker(bind=self.engine)

    def create_tables(self):
        Base.metadata.create_all(self.engine)
        print("TEMU EPR授权代理费表创建成功！")

    def drop_tables(self):
        Base.metadata.drop_all(self.engine)
        print("TEMU EPR授权代理费表删除成功！")

    def _parse_amount_value(self, amount_str):
        if not amount_str:
            return None
        try:
            cleaned = re.sub(r'[￥¥$€£+,\s]', '', str(amount_str))
            return float(cleaned) if cleaned else None
        except:
            return None

    def _parse_timestamp(self, timestamp_ms):
        if not timestamp_ms:
            return None
        try:
            return datetime.fromtimestamp(timestamp_ms / 1000)
        except:
            return None

    def upsert_data(self, mall_id, record_date, data):
        """
        插入或更新数据
        """
        session = self.Session()
        try:
            details_rows = data.get('detailsRows', [])
            insert_count = 0
            update_count = 0

            for row in details_rows:
                billing_cycle = row.get('billingCycle')
                cert_name = row.get('certName')
                region_name = row.get('regionName')

                existing = session.query(TemuRestrictEprAuthorizationAgentFee).filter_by(
                    mall_id=mall_id,
                    record_date=record_date,
                    billing_cycle=billing_cycle,
                    cert_name=cert_name,
                    region_name=region_name
                ).first()

                if existing:
                    existing.payment_cycle = row.get('paymentCycle')
                    existing.amount = row.get('amount')
                    existing.amount_value = self._parse_amount_value(row.get('amount'))
                    existing.currency = row.get('currency')
                    existing.state = row.get('state')
                    existing.freeze_start_time = self._parse_timestamp(row.get('freezeStartTime'))
                    existing.source_dr = row.get('sourceDR')
                    existing.updated_at = datetime.now()
                    update_count += 1
                else:
                    new_record = TemuRestrictEprAuthorizationAgentFee(
                        mall_id=mall_id,
                        record_date=record_date,
                        billing_cycle=billing_cycle,
                        cert_name=cert_name,
                        region_name=region_name,
                        payment_cycle=row.get('paymentCycle'),
                        amount=row.get('amount'),
                        amount_value=self._parse_amount_value(row.get('amount')),
                        currency=row.get('currency'),
                        state=row.get('state'),
                        freeze_start_time=self._parse_timestamp(row.get('freezeStartTime')),
                        source_dr=row.get('sourceDR')
                    )
                    session.add(new_record)
                    insert_count += 1

            session.commit()
            print(f"TEMU EPR授权代理费: 新增 {insert_count} 条，更新 {update_count} 条")

        except Exception as e:
            session.rollback()
            print(f"处理数据失败: {e}")
            raise
        finally:
            session.close()

    def import_from_json_file(self, json_file_path, mall_id, record_date):
        with open(json_file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
            self.upsert_data(mall_id, record_date, data)
