import logging

from fastapi import APIRouter, Query
from fastapi.exceptions import HTTPException
from tortoise.expressions import Q

from app.controllers.table import codegen_controller
from app.schemas.base import Success, SuccessExtra
from app.schemas.codegen import *

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/table")


@router.get("/page", summary="查看列表")
async def list_role(
    page: int = Query(1, description="页码"),
    limit: int = Query(10, description="每页数量"),
    table_name: str = Query("", description="名称，用于查询"),
):
    q = Q()
    if table_name:
        q = Q(name__contains=table_name)
    total, role_objs = await codegen_controller.list(page=page, page_size=limit, search=q)
    data = [await obj.to_dict() for obj in role_objs]
    return SuccessExtra(data=dict(list=data, total=total, page=page, page_size=limit))


@router.post("/import/{db_connection}", summary="导入表")
async def get_role(db_connection, table: dict = None):
    print('db_connection, importTables', db_connection, table)
    data = await codegen_controller.import_table(db_connection, importTables=table['table'])
    # role_obj = await codegen_controller.get(id=role_id)
    return Success(data=data)


import json
@router.put("/field/{id}", summary="更新字段")
async def update_fields(id: int, fields_in: dict):
    fields_in['fields'] = json.dumps(fields_in['fields'])
    await codegen_controller.update(id=id, obj_in=fields_in)
    return Success(msg="Updated Successfully")

@router.get("/preview/{id}", summary="代码预览")
async def code_preview(id: int):
    data = await codegen_controller.preview(id)
    return Success(data=data)


@router.get("/{id}", summary="查看详细的表信息")
async def get_table_detail(id):
    table_obj = await codegen_controller.get(id=id)
    return Success(data=await table_obj.to_dict())

@router.post("/update", summary="更新")
async def update_role(role_in):
    await codegen_controller.update(id=role_in.id, obj_in=role_in)
    return Success(msg="Updated Successfully")


@router.delete("/", summary="删除")
async def delete_role(
    batch_ids: dict
):
    for id in batch_ids.get('data'):
        await codegen_controller.remove(id=id)
    return Success(msg="Deleted Success")


@router.get("/authorized", summary="查看权限")
async def get_role_authorized(id: int = Query(..., description="ID")):
    role_obj = await codegen_controller.get(id=id)
    data = await role_obj.to_dict(m2m=True)
    return Success(data=data)


@router.post("/authorized", summary="更新权限")
async def update_role_authorized(role_in):
    role_obj = await codegen_controller.get(id=role_in.id)
    await codegen_controller.update_roles(role=role_obj, menu_ids=role_in.menu_ids, api_infos=role_in.api_infos)
    return Success(msg="Updated Successfully")
