from typing import Optional
from tortoise.expressions import Q
from tortoise.queryset import QuerySet

from app.models.valuation import ValuationAssessment
from app.schemas.valuation import (
    UserValuationCreate, 
    UserValuationQuery, 
    UserValuationList,
    UserValuationOut,
    UserValuationDetail
)


class UserValuationController:
    """用户端估值评估控制器"""
    
    def __init__(self):
        self.model = ValuationAssessment
    
    async def create_valuation(self, user_id: int, data: UserValuationCreate) -> UserValuationDetail:
        """用户创建估值评估"""
        valuation_data = data.model_dump()
        valuation_data['user_id'] = user_id
        valuation_data['status'] = 'pending'  # 默认状态为待审核
        
        valuation = await self.model.create(**valuation_data)
        return await self._to_user_detail(valuation)
    
    async def get_user_valuations(self, user_id: int, query: UserValuationQuery) -> UserValuationList:
        """获取用户的估值评估列表"""
        queryset = self.model.filter(user_id=user_id, is_active=True)
        
        # 构建查询条件
        if query.status:
            queryset = queryset.filter(status=query.status)
        if query.asset_name:
            queryset = queryset.filter(asset_name__icontains=query.asset_name)
        
        # 计算总数
        total = await queryset.count()
        
        # 分页查询
        offset = (query.page - 1) * query.size
        items = await queryset.offset(offset).limit(query.size).order_by('-created_at')
        
        # 转换为输出模型
        user_valuations = [await self._to_user_out(item) for item in items]
        
        pages = (total + query.size - 1) // query.size
        
        return UserValuationList(
            items=user_valuations,
            total=total,
            page=query.page,
            size=query.size,
            pages=pages
        )
    
    async def get_user_valuation_detail(self, user_id: int, valuation_id: int) -> Optional[UserValuationDetail]:
        """获取用户的估值评估详情"""
        valuation = await self.model.filter(
            id=valuation_id, 
            user_id=user_id, 
            is_active=True
        ).first()
        
        if not valuation:
            return None
        
        return await self._to_user_detail(valuation)
    
    async def get_user_valuation_statistics(self, user_id: int) -> dict:
        """获取用户的估值评估统计信息"""
        total = await self.model.filter(user_id=user_id, is_active=True).count()
        pending = await self.model.filter(user_id=user_id, status='pending', is_active=True).count()
        approved = await self.model.filter(user_id=user_id, status='approved', is_active=True).count()
        rejected = await self.model.filter(user_id=user_id, status='rejected', is_active=True).count()
        
        return {
            'total': total,
            'pending': pending,
            'approved': approved,
            'rejected': rejected
        }
    
    async def _to_user_out(self, valuation: ValuationAssessment) -> UserValuationOut:
        """转换为用户端输出模型"""
        return UserValuationOut(
            id=valuation.id,
            asset_name=valuation.asset_name,
            institution=valuation.institution,
            industry=valuation.industry,
            status=valuation.status,
            admin_notes=valuation.admin_notes,
            created_at=valuation.created_at,
            updated_at=valuation.updated_at
        )
    
    async def _to_user_detail(self, valuation: ValuationAssessment) -> UserValuationDetail:
        """转换为用户端详细模型"""
        return UserValuationDetail(
            id=valuation.id,
            asset_name=valuation.asset_name,
            institution=valuation.institution,
            industry=valuation.industry,
            annual_revenue=valuation.annual_revenue,
            rd_investment=valuation.rd_investment,
            three_year_income=valuation.three_year_income,
            funding_status=valuation.funding_status,
            inheritor_level=valuation.inheritor_level,
            inheritor_age_count=valuation.inheritor_age_count,
            inheritor_certificates=valuation.inheritor_certificates,
            heritage_level=valuation.heritage_level,
            patent_application_no=valuation.patent_application_no,
            historical_evidence=valuation.historical_evidence,
            patent_certificates=valuation.patent_certificates,
            pattern_images=valuation.pattern_images,
            application_maturity=valuation.application_maturity,
            application_coverage=valuation.application_coverage,
            cooperation_depth=valuation.cooperation_depth,
            offline_activities=valuation.offline_activities,
            online_accounts=valuation.online_accounts,
            sales_volume=valuation.sales_volume,
            link_views=valuation.link_views,
            circulation=valuation.circulation,
            last_market_activity=valuation.last_market_activity,
            monthly_transaction=valuation.monthly_transaction,
            price_fluctuation=valuation.price_fluctuation,
            status=valuation.status,
            admin_notes=valuation.admin_notes,
            created_at=valuation.created_at,
            updated_at=valuation.updated_at
        )


# 创建控制器实例
user_valuation_controller = UserValuationController()