from .finance_parse import parse_finance_data
from tortoise.expressions import Q
from tortoise.transactions import atomic

from app.models.automation import Task, TaskStatus
from app.schemas.task import TaskModel, DecodeTaskParams, DecodeTaskResult

class TaskController(object):
    async def get_task(self, name, type):
        q = Q()
        # 获取所有未被软删除的任务
        q &= Q(is_deleted=False)
        if name: q &= Q(name__contains=name)
        if type: q &= Q(type=type)
        all_tasks = await self.model.filter(q).order_by("id")
        return all_tasks
    
    async def list(self, name, type, page: int = 1, page_size: int = 10, order: list[str] = ["id"]):
        q = Q()
        if name: q &= Q(name__contains=name)
        if type: q &= Q(type=type)
        query = Task.filter(q)
        return await query.count(), await query.offset((page - 1) * page_size).limit(page_size).order_by(*order)

    @atomic()
    async def create_task(self, name: str, obj_in: DecodeTaskParams):
        task_obj = TaskModel.create_decode_task(name, obj_in)
        task_obj.result = task_obj.result or {}
        obj = Task(**task_obj.model_dump())
        await obj.save()
        return obj, task_obj

    @atomic()
    async def update_task(self, obj_in: TaskModel, task_id: int, status: TaskStatus, result: DecodeTaskResult):
        task_obj = await Task.get(id=task_id)
        obj_in.status = status
        obj_in.set_result(result)
        
        # 更新任务信息
        task_obj.update_from_dict(obj_in.model_dump(exclude_unset=True))
        await task_obj.save()

task_controller = TaskController()
