#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SHEIN发布记录数据模型
存储已驳回和已撤回的商品发布记录
"""

from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, JSON, Boolean, Index
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import json

# 创建基类
Base = declarative_base()

class SheinPublishRecord(Base):
    """
    SHEIN商品发布记录表
    存储已驳回和已撤回的发布记录
    """
    __tablename__ = 'shein_publish_record'

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

    # 记录唯一标识
    record_id = Column(String(50), nullable=False, unique=True, comment='发布记录ID')

    # 店铺信息
    store_username = Column(String(50), nullable=True, comment='店铺账号')
    store_name = Column(String(100), nullable=True, comment='店铺名称')
    store_manager = Column(String(50), nullable=True, comment='店长')

    # 文档信息
    doc_type = Column(String(10), nullable=True, comment='文档类型')
    version = Column(String(50), nullable=True, comment='版本号')

    # 商品信息
    spu_name = Column(String(50), nullable=True, comment='SPU名称')
    skc_name = Column(String(100), nullable=True, comment='SKC名称')
    product_name = Column(Text, nullable=True, comment='商品名称')
    product_en_name = Column(Text, nullable=True, comment='商品英文名称')
    product_name_multi = Column(Text, nullable=True, comment='商品多语言名称')
    supplier_code = Column(String(200), nullable=True, comment='供应商编码')
    sale_name = Column(String(100), nullable=True, comment='销售名称')

    # 品牌信息
    brand_code = Column(String(50), nullable=True, comment='品牌编码')
    brand_name = Column(String(100), nullable=True, comment='品牌名称')

    # 状态信息
    audit_state = Column(Integer, nullable=True, comment='审核状态: 3-已驳回, 4-已撤回')
    state = Column(Integer, nullable=True, comment='详细状态: 10-已驳回, 11-核价被驳回, 13-已撤回, 14-已归档, 17-审款被驳回, 18-审版被驳回, 19-核样被驳回, 20-终审被驳回, 30-跟卖被驳回, 33-初审驳回')
    edit_type = Column(Integer, nullable=True, comment='编辑类型')

    # 操作人信息
    operator = Column(String(50), nullable=True, comment='操作人')
    auditor = Column(String(50), nullable=True, comment='审核人')

    # 时间信息
    create_time = Column(DateTime, nullable=True, comment='创建时间')
    audit_date = Column(DateTime, nullable=True, comment='审核时间')

    # 图片信息
    main_image_thumbnail_url = Column(Text, nullable=True, comment='主图缩略图URL')

    # 标签和标记
    change_tag_list = Column(JSON, nullable=True, comment='变更标签列表')
    appeal_record = Column(Boolean, nullable=True, comment='是否有申诉记录')
    has_judge_result = Column(Boolean, nullable=True, comment='是否有判定结果')
    is_embryo = Column(Boolean, nullable=True, comment='是否为胚胎商品')
    time_out = Column(Boolean, nullable=True, comment='是否超时')
    has_category_authority = Column(Boolean, nullable=True, comment='是否有类目权限')

    # 其他信息
    discuss_type = Column(String(50), nullable=True, comment='讨论类型')
    submit_entry = Column(String(50), nullable=True, comment='提交入口')
    
    # 驳回原因和草稿历史（JSON格式存储）
    reject_reason_list = Column(JSON, nullable=True, comment='驳回原因列表')
    audit_result = Column(JSON, nullable=True, comment='完整审核结果')
    draft_history = Column(JSON, nullable=True, comment='草稿历史详情')

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

    # 用户备注字段（供后续web界面使用）
    user_notes = Column(Text, nullable=True, comment='用户备注')

    # 定义索引
    __table_args__ = (
        Index('ix_record_id', 'record_id'),
        Index('ix_spu_name', 'spu_name'),
        Index('ix_skc_name', 'skc_name'),
        Index('ix_store_username', 'store_username'),
        Index('ix_audit_state', 'audit_state'),
        Index('ix_state', 'state'),
        Index('ix_create_time', 'create_time'),
        Index('ix_operator', 'operator'),
    )

    def __repr__(self):
        return f"<SheinPublishRecord(id={self.id}, record_id='{self.record_id}', spu_name='{self.spu_name}', state={self.state})>"


class SheinPublishRecordManager:
    """
    SHEIN发布记录管理器
    负责数据库操作和数据导入
    """

    def __init__(self, database_url):
        """
        初始化管理器

        Args:
            database_url: 数据库连接URL
        """
        self.engine = create_engine(database_url, echo=False, pool_pre_ping=True)
        self.Session = sessionmaker(bind=self.engine)

    def create_tables(self):
        """创建所有表"""
        Base.metadata.create_all(self.engine)
        print("发布记录表创建成功")

    def upsert_publish_record(self, record_data):
        """
        插入或更新单条发布记录

        Args:
            record_data: 发布记录数据字典
        """
        session = self.Session()
        try:
            record_id = record_data.get('record_id')
            if not record_id:
                print(f"警告: 记录缺少 record_id，跳过")
                return

            # 查询是否存在
            existing_record = session.query(SheinPublishRecord).filter_by(record_id=record_id).first()

            # 处理时间字段
            create_time = None
            if record_data.get('create_time'):
                try:
                    create_time = datetime.strptime(record_data['create_time'], '%Y-%m-%d %H:%M:%S')
                except:
                    pass

            audit_date = None
            if record_data.get('audit_date'):
                try:
                    audit_date = datetime.strptime(record_data['audit_date'], '%Y-%m-%d %H:%M:%S')
                except:
                    pass

            if existing_record:
                # 更新现有记录
                existing_record.store_username = record_data.get('store_username')
                existing_record.store_name = record_data.get('store_name')
                existing_record.store_manager = record_data.get('store_manager')
                existing_record.doc_type = record_data.get('doc_type')
                existing_record.version = record_data.get('version')
                existing_record.spu_name = record_data.get('spu_name')
                existing_record.skc_name = record_data.get('skc_name')
                existing_record.product_name = record_data.get('product_name')
                existing_record.product_en_name = record_data.get('product_en_name')
                existing_record.product_name_multi = record_data.get('product_name_multi')
                existing_record.supplier_code = record_data.get('supplier_code')
                existing_record.sale_name = record_data.get('sale_name')
                existing_record.brand_code = record_data.get('brand_code')
                existing_record.brand_name = record_data.get('brand_name')
                existing_record.audit_state = record_data.get('audit_state')
                existing_record.state = record_data.get('state')
                existing_record.edit_type = record_data.get('edit_type')
                existing_record.operator = record_data.get('operator')
                existing_record.auditor = record_data.get('auditor')
                existing_record.create_time = create_time
                existing_record.audit_date = audit_date
                existing_record.main_image_thumbnail_url = record_data.get('main_image_thumbnail_url')
                existing_record.change_tag_list = record_data.get('change_tag_list')
                existing_record.appeal_record = record_data.get('appeal_record')
                existing_record.has_judge_result = record_data.get('has_judge_result')
                existing_record.is_embryo = record_data.get('is_embryo')
                existing_record.time_out = record_data.get('time_out')
                existing_record.has_category_authority = record_data.get('has_category_authority')
                existing_record.discuss_type = record_data.get('discuss_type')
                existing_record.submit_entry = record_data.get('submit_entry')
                existing_record.reject_reason_list = record_data.get('reject_reason_list')
                existing_record.audit_result = record_data.get('audit_result')
                existing_record.draft_history = record_data.get('draft_history')
                existing_record.updated_at = datetime.now()
            else:
                # 插入新记录
                new_record = SheinPublishRecord(
                    record_id=record_id,
                    store_username=record_data.get('store_username'),
                    store_name=record_data.get('store_name'),
                    store_manager=record_data.get('store_manager'),
                    doc_type=record_data.get('doc_type'),
                    version=record_data.get('version'),
                    spu_name=record_data.get('spu_name'),
                    skc_name=record_data.get('skc_name'),
                    product_name=record_data.get('product_name'),
                    product_en_name=record_data.get('product_en_name'),
                    product_name_multi=record_data.get('product_name_multi'),
                    supplier_code=record_data.get('supplier_code'),
                    sale_name=record_data.get('sale_name'),
                    brand_code=record_data.get('brand_code'),
                    brand_name=record_data.get('brand_name'),
                    audit_state=record_data.get('audit_state'),
                    state=record_data.get('state'),
                    edit_type=record_data.get('edit_type'),
                    operator=record_data.get('operator'),
                    auditor=record_data.get('auditor'),
                    create_time=create_time,
                    audit_date=audit_date,
                    main_image_thumbnail_url=record_data.get('main_image_thumbnail_url'),
                    change_tag_list=record_data.get('change_tag_list'),
                    appeal_record=record_data.get('appeal_record'),
                    has_judge_result=record_data.get('has_judge_result'),
                    is_embryo=record_data.get('is_embryo'),
                    time_out=record_data.get('time_out'),
                    has_category_authority=record_data.get('has_category_authority'),
                    discuss_type=record_data.get('discuss_type'),
                    submit_entry=record_data.get('submit_entry'),
                    reject_reason_list=record_data.get('reject_reason_list'),
                    audit_result=record_data.get('audit_result'),
                    draft_history=record_data.get('draft_history')
                )
                session.add(new_record)

            session.commit()
        except Exception as e:
            session.rollback()
            print(f"处理发布记录失败: {e}")
            raise
        finally:
            session.close()

    def import_from_json_file(self, json_file):
        """
        从JSON文件导入发布记录数据

        Args:
            json_file: JSON文件路径，格式为 {store_username: [record_list]}
        """
        print(f"开始从文件导入发布记录: {json_file}")

        with open(json_file, 'r', encoding='utf-8') as f:
            data_dict = json.load(f)

        total_count = 0
        for store_username, record_list in data_dict.items():
            print(f"处理店铺 {store_username} 的发布记录，共 {len(record_list)} 条")
            for record_data in record_list:
                self.upsert_publish_record(record_data)
                total_count += 1

        print(f"发布记录导入完成，共处理 {total_count} 条记录")
        return total_count

    def get_records_by_store(self, store_username, audit_state=None, state=None):
        """
        查询指定店铺的发布记录

        Args:
            store_username: 店铺账号
            audit_state: 审核状态筛选（可选）
            state: 详细状态筛选（可选）

        Returns:
            发布记录列表
        """
        session = self.Session()
        try:
            query = session.query(SheinPublishRecord).filter_by(store_username=store_username)

            if audit_state is not None:
                query = query.filter_by(audit_state=audit_state)

            if state is not None:
                query = query.filter_by(state=state)

            records = query.order_by(SheinPublishRecord.create_time.desc()).all()
            return records
        finally:
            session.close()

    def get_rejected_records(self, store_username=None):
        """
        获取已驳回的记录（audit_state=3 且 state!=14）

        Args:
            store_username: 店铺账号（可选）

        Returns:
            已驳回记录列表
        """
        session = self.Session()
        try:
            query = session.query(SheinPublishRecord).filter(
                SheinPublishRecord.audit_state == 3,
                SheinPublishRecord.state != 14  # 排除已归档
            )

            if store_username:
                query = query.filter_by(store_username=store_username)

            records = query.order_by(SheinPublishRecord.create_time.desc()).all()
            return records
        finally:
            session.close()

    def get_withdrawn_records(self, store_username=None):
        """
        获取已撤回的记录（audit_state=4 且 state=13）

        Args:
            store_username: 店铺账号（可选）

        Returns:
            已撤回记录列表
        """
        session = self.Session()
        try:
            query = session.query(SheinPublishRecord).filter(
                SheinPublishRecord.audit_state == 4,
                SheinPublishRecord.state == 13
            )

            if store_username:
                query = query.filter_by(store_username=store_username)

            records = query.order_by(SheinPublishRecord.create_time.desc()).all()
            return records
        finally:
            session.close()
