from app.extensions import db
from datetime import datetime

# 1. 借用表
class TransBorrow(db.Model):
    __tablename__ = 'trans_borrow'
    id = db.Column(db.Integer, primary_key=True)
    sku = db.Column(db.String(100))
    source_table = db.Column(db.String(50))
    stock_id = db.Column(db.Integer)
    quantity = db.Column(db.Numeric(19, 4))
    borrow_time = db.Column(db.DateTime, default=datetime.now)
    expected_return_time = db.Column(db.DateTime)
    borrower_name = db.Column(db.String(100))
    actual_return_time = db.Column(db.DateTime)
    approver_name = db.Column(db.String(100))
    status = db.Column(db.String(20))

    def to_dict(self):
        return {
            'id': self.id,
            'sku': self.sku,
            'borrower_name': self.borrower_name,
            'status': self.status
        }

# 2. 维修表
class TransRepair(db.Model):
    __tablename__ = 'trans_repair'
    id = db.Column(db.Integer, primary_key=True)
    sku = db.Column(db.String(100))
    source_table = db.Column(db.String(50))
    stock_id = db.Column(db.Integer)
    arrival_date = db.Column(db.Date)
    expected_repair_time = db.Column(db.String(100))
    shipping_date = db.Column(db.Date)
    is_self_made = db.Column(db.Boolean, default=False)
    related_product_id = db.Column(db.Integer)
    related_contract_id = db.Column(db.String(100))
    repair_manager = db.Column(db.String(100))
    fault_description = db.Column(db.Text)
    repair_result = db.Column(db.Text)
    cost_price = db.Column(db.Numeric(19, 4))
    sale_price = db.Column(db.Numeric(19, 4))

    def to_dict(self):
        return {'id': self.id, 'sku': self.sku, 'status': 'repaired' if self.repair_result else 'pending'}

# 3. 报废表
class TransScrap(db.Model):
    __tablename__ = 'trans_scrap'
    id = db.Column(db.Integer, primary_key=True)
    sku = db.Column(db.String(100))
    source_table = db.Column(db.String(50))
    stock_id = db.Column(db.Integer)
    quantity = db.Column(db.Numeric(19, 4))
    reason = db.Column(db.Text)
    operator_name = db.Column(db.String(100))
    operation_time = db.Column(db.DateTime, default=datetime.now)
    approver_name = db.Column(db.String(100))
    approval_status = db.Column(db.String(20))
    cost_at_scrap = db.Column(db.Numeric(19, 4))
    total_loss = db.Column(db.Numeric(19, 4))

    def to_dict(self):
        return {'id': self.id, 'sku': self.sku, 'total_loss': float(self.total_loss) if self.total_loss else 0}