"""
机构网点相关数据模型
"""
from datetime import datetime
from sqlalchemy import Column, BigInteger, String, Integer, Text, ForeignKey, DateTime, Index
from sqlalchemy.orm import relationship
from app.db.base import Base


class Organization(Base):
    """机构/网点表"""

    __tablename__ = "organizations"

    id = Column(BigInteger, primary_key=True, index=True)
    org_code = Column(String(50), unique=True, nullable=False, index=True, comment="机构代码")
    org_name = Column(String(200), nullable=False, comment="机构名称")
    org_type = Column(String(20), nullable=False, comment="机构类型: province, city, outlet")
    parent_id = Column(BigInteger, ForeignKey("organizations.id"), nullable=True, comment="父机构ID")
    tree_path = Column(String(1000), nullable=True, comment="树形路径: /1/2/3/")
    tree_level = Column(Integer, default=0, nullable=False, comment="层级")
    address = Column(String(500), nullable=True, comment="地址")
    contact_person = Column(String(100), nullable=True, comment="联系人")
    contact_phone = Column(String(20), nullable=True, comment="联系电话")
    status = Column(String(20), default="active", nullable=False, comment="状态: active, inactive")
    sort_order = Column(Integer, default=0, nullable=False, comment="排序")
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    created_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)
    updated_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)
    deleted_at = Column(DateTime, nullable=True)
    deleted_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)

    # 关系
    parent = relationship("Organization", remote_side=[id], foreign_keys=[parent_id])
    children = relationship("Organization", foreign_keys=[parent_id], backref="children_ref")
    created_user = relationship("User", foreign_keys=[created_by])
    updated_user = relationship("User", foreign_keys=[updated_by])
    deleted_user = relationship("User", foreign_keys=[deleted_by])

    def __repr__(self):
        return f"<Organization(id={self.id}, org_code={self.org_code}, org_name={self.org_name})>"
