#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TEMU限制规则汇总表模型
存储限制规则的汇总信息，每个商城每天记录一次
"""

from sqlalchemy import create_engine, Column, String, Text, DateTime, Integer, DECIMAL, Date, Boolean, 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 TemuRestrictRule(Base):
    """
    TEMU限制规则汇总表
    """
    __tablename__ = 'temu_restrict_rule'

    # 主键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='记录日期')

    # 规则信息
    frozen_type = Column(String(100), nullable=False, comment='冻结类型')
    reason = Column(String(200), 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='货币类型')
    description = Column(Text, nullable=True, comment='描述说明')
    operation = Column(String(50), nullable=True, comment='操作提示')
    unfreeze_condition = Column(String(500), nullable=True, comment='解冻条件')
    show_detail = Column(Boolean, 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_temu_rule_mall_id', 'mall_id'),
        Index('ix_temu_rule_record_date', 'record_date'),
        Index('ix_temu_rule_frozen_type', 'frozen_type'),
        Index('ix_temu_rule_mall_date', 'mall_id', 'record_date'),
        Index('ix_temu_rule_unique', 'mall_id', 'record_date', 'frozen_type', unique=True),
    )

    def __repr__(self):
        return f"<TemuRestrictRule(id={self.id}, mall_id='{self.mall_id}', frozen_type='{self.frozen_type}')>"


class TemuRestrictRuleManager:
    """
    TEMU限制规则数据管理器
    """

    def __init__(self, database_url):
        """
        初始化数据库连接
        
        Args:
            database_url (str): 数据库连接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限制规则表创建成功！")

    def drop_tables(self):
        """删除数据表"""
        Base.metadata.drop_all(self.engine)
        print("TEMU限制规则表删除成功！")

    def _parse_amount_value(self, amount_str):
        """
        解析金额字符串，提取数值
        例如: "￥21.86" -> 21.86, "+673.92" -> 673.92
        """
        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 upsert_data(self, mall_id, record_date, data_list):
        """
        插入或更新数据
        
        Args:
            mall_id (str): 商城ID
            record_date (date): 记录日期
            data_list (list): 规则数据列表
        """
        session = self.Session()
        try:
            insert_count = 0
            update_count = 0

            for data in data_list:
                frozen_type = data.get('frozenType')
                if not frozen_type:
                    continue

                existing = session.query(TemuRestrictRule).filter_by(
                    mall_id=mall_id,
                    record_date=record_date,
                    frozen_type=frozen_type
                ).first()

                if existing:
                    # 更新现有记录
                    existing.reason = data.get('reason')
                    existing.amount = data.get('amount')
                    existing.amount_value = self._parse_amount_value(data.get('amount'))
                    existing.currency = data.get('currency')
                    existing.description = data.get('description')
                    existing.operation = data.get('operation')
                    existing.unfreeze_condition = data.get('unfreezeCondition')
                    existing.show_detail = data.get('showDetail')
                    existing.updated_at = datetime.now()
                    update_count += 1
                else:
                    # 插入新记录
                    new_record = TemuRestrictRule(
                        mall_id=mall_id,
                        record_date=record_date,
                        frozen_type=frozen_type,
                        reason=data.get('reason'),
                        amount=data.get('amount'),
                        amount_value=self._parse_amount_value(data.get('amount')),
                        currency=data.get('currency'),
                        description=data.get('description'),
                        operation=data.get('operation'),
                        unfreeze_condition=data.get('unfreezeCondition'),
                        show_detail=data.get('showDetail')
                    )
                    session.add(new_record)
                    insert_count += 1

            session.commit()
            print(f"TEMU限制规则: 新增 {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):
        """
        从JSON文件导入数据
        
        Args:
            json_file_path (str): JSON文件路径
            mall_id (str): 商城ID
            record_date (date): 记录日期
        """
        with open(json_file_path, 'r', encoding='utf-8') as f:
            data_list = json.load(f)
            self.upsert_data(mall_id, record_date, data_list)

    def get_rules_by_mall_date(self, mall_id, record_date):
        """
        获取指定商城和日期的规则列表
        """
        session = self.Session()
        try:
            return session.query(TemuRestrictRule).filter_by(
                mall_id=mall_id,
                record_date=record_date
            ).all()
        finally:
            session.close()
