from __future__ import annotations

import json
from decimal import Decimal
from typing import Any, List

from pydantic import BaseModel, Field, computed_field


class Product(BaseModel):
    """产品模型"""

    uid: str
    rowid: str
    name: str
    pieces: int | None
    segment_size: Decimal | None
    unit: str | None
    color: str | None
    width: str | None = None
    detail_str: str | None = Field(exclude=True)  # 在序列化时排除此字段
    created_at: str

    @computed_field
    @property
    def detail(self) -> dict[str, Any]:
        """将 detail_str 转换为字典"""

        try:
            return json.loads(self.detail_str) if self.detail_str else {}
        except (json.JSONDecodeError, TypeError):
            return {}


class ProductListResponse(BaseModel):
    """产品列表响应"""

    products: List[Product]
    total: int


class Customer(BaseModel):
    """客户模型"""

    uid: str
    rowid: str
    name: str
    area: str | None
    created_at: str


class Fabric(BaseModel):
    """面料模型"""

    name: str


# ------------------------------------------------------------------------------
# 明道云：通用值类型（Relation / Attachment / Collaborator 等）
# ------------------------------------------------------------------------------
class MDYRelationItem(BaseModel):
    """Relation 字段的单项（跨表关联）"""

    rowid: str
    name: str
    link: str | None = None


class MDYAttachmentItem(BaseModel):
    """Attachment 字段的单项（附件）"""

    original_file_name: str
    file_id: str
    download_url: str
    preview_url: str | None = None


class MDYCollaboratorItem(BaseModel):
    """Collaborator 字段的单项（成员/人员）

    说明：明道云在不同场景下可能返回对象或列表；这里先按“对象字段”建模，
    后续解析时可以按实际返回结构再做兼容适配。
    """

    accountId: str | None = None
    fullname: str | None = None
    avatar: str | None = None


class MDYPlateOrder(BaseModel):
    """开版数据表（明道云）的一行记录：仅做类型定义"""

    rowid: str
    created_at: str

    # 成员 / 人员
    colorist: MDYCollaboratorItem | List[MDYCollaboratorItem] | str | None = None

    # Relation（跨表关联）
    fabric_relation: List[MDYRelationItem] = Field(default_factory=list)
    customer_relation: List[MDYRelationItem] = Field(default_factory=list)

    # 基础字段
    production_method: str | None = None
    design_no: str | None = None
    plate_method: str | None = None
    level_rating: int | None = None
    fabric_source: str | None = None
    color_designer: str | None = None
    dev_progress: str | None = None
    need_marker_frame: str | None = None
    style_name: str | None = None
    approval_result: str | None = None

    plate_time: str | None = None  # DateTime: 'YYYY-MM-DD HH:MM:SS'
    required_finish_date: str | None = None  # Date: 'YYYY-MM-DD'
    record_datetime: str | None = None  # DateTime: 'YYYY-MM-DD HH:MM:SS'

    rework_reason: str | None = None
    start_plate_status: str | None = None
    sample_meters: int | float | None = None
    urgency: str | None = None
    width: str | None = None
    difficulty_level: str | None = None

    # 附件
    plate_images: List[MDYAttachmentItem] = Field(default_factory=list)

    # 评级/组合字段
    drawing_rating: str | None = None
    color_rating: str | None = None
    pattern_fit_rating: str | None = None
    record_id: str | None = None
    customer_name: str | None = None

    # 其它 Relation（可能为空）
    pattern_set: List[MDYRelationItem] = Field(default_factory=list)
    drawing_relation: List[MDYRelationItem] = Field(default_factory=list)
    color_relation: List[MDYRelationItem] = Field(default_factory=list)
    pattern_set_relation: List[MDYRelationItem] = Field(default_factory=list)
    modify_drawing_relation: List[MDYRelationItem] = Field(default_factory=list)
    image_development_relation: List[MDYRelationItem] = Field(default_factory=list)
    color_scheme_relation: List[MDYRelationItem] = Field(default_factory=list)
