{%- set is_tree = table.tpl_category == 'tree' %}
from typing import List

from flask import g
from flask_login import login_required
from pydantic import BeforeValidator
from typing_extensions import Annotated
from werkzeug.datastructures import FileStorage

from ruoyi_common.base.model import AjaxResponse, TableResponse
from ruoyi_common.constant import HttpStatus
from ruoyi_common.descriptor.serializer import BaseSerializer, JsonSerializer
from ruoyi_common.descriptor.validator import QueryValidator, BodyValidator, PathValidator, FileDownloadValidator, FileUploadValidator
from ruoyi_common.domain.enum import BusinessType
from ruoyi_common.utils.base import ExcelUtil
from ruoyi_framework.descriptor.log import Log
from ruoyi_framework.descriptor.permission import HasPerm, PreAuthorize
from {{ get_import_path(table.package_name, table.module_name, 'controller') }} import {{ underscore(table.class_name) }} as {{ underscore(table.class_name) }}_bp
from {{ get_import_path(table.package_name, table.module_name, 'domain') }} import {{ class_name_pascal }}
from {{ get_import_path(table.package_name, table.module_name, 'service') }}.{{ underscore(table.class_name) }}_service import {{ class_name_pascal }}Service

# 使用 controller/__init__.py 中定义的蓝图
gen = {{ underscore(table.class_name) }}_bp

{{ underscore(table.class_name) }}_service = {{ class_name_pascal }}Service()


def _clear_page_context():
    if hasattr(g, "criterian_meta"):
        g.criterian_meta.page = None

@gen.route('/list', methods=["GET"])
{%- if is_tree %}
@QueryValidator()
{%- else %}
@QueryValidator(is_page=True)
{%- endif %}
@PreAuthorize(HasPerm('{{ table.module_name }}:{{ table.business_name }}:list'))
@JsonSerializer()
def {{ underscore(table.business_name) }}_list(dto: {{ class_name_pascal }}):
    """查询{{ table.function_name }}列表"""
    {{ underscore(table.class_name) }}_entity = {{ class_name_pascal }}()
    # 转换PO到Entity对象
    for attr in dto.model_fields.keys():
        if hasattr({{ underscore(table.class_name) }}_entity, attr):
            setattr({{ underscore(table.class_name) }}_entity, attr, getattr(dto, attr))
{%- if is_tree %}
    {{ underscore(table.class_name) }}_entity.page_num = None
    {{ underscore(table.class_name) }}_entity.page_size = None
    _clear_page_context()
{%- endif %}
    {{ underscore(table.business_name) }}s = {{ underscore(table.class_name) }}_service.select_{{ underscore(table.class_name) }}_list({{ underscore(table.class_name) }}_entity)
    return TableResponse(code=HttpStatus.SUCCESS, msg='查询成功', rows={{ underscore(table.business_name) }}s)

{% if table.pk_column %}
@gen.route('/<int:{{ table.pk_column.java_field }}>', methods=['GET'])
@PathValidator()
@PreAuthorize(HasPerm('{{ table.module_name }}:{{ table.business_name }}:query'))
@JsonSerializer()
def get_{{ underscore(table.business_name) }}({{ underscore(table.pk_column.java_field) }}: int):
    """获取{{ table.function_name }}详细信息"""
    {{ underscore(table.class_name) }}_entity = {{ underscore(table.class_name) }}_service.select_{{ underscore(table.class_name) }}_by_id({{ underscore(table.pk_column.java_field) }})
    return AjaxResponse.from_success(data={{ underscore(table.class_name) }}_entity)
{% endif %}

@gen.route('', methods=['POST'])
@BodyValidator()
@PreAuthorize(HasPerm('{{ table.module_name }}:{{ table.business_name }}:add'))
@Log(title='{{ table.function_name }}管理', business_type=BusinessType.INSERT)
@JsonSerializer()
def add_{{ underscore(table.business_name) }}(dto: {{ class_name_pascal }}):
    """新增{{ table.function_name }}"""
    {{ underscore(table.class_name) }}_entity = {{ class_name_pascal }}()
    # 转换PO到Entity对象
    for attr in dto.model_fields.keys():
        if hasattr({{ underscore(table.class_name) }}_entity, attr):
            setattr({{ underscore(table.class_name) }}_entity, attr, getattr(dto, attr))
    result = {{ underscore(table.class_name) }}_service.insert_{{ underscore(table.class_name) }}({{ underscore(table.class_name) }}_entity)
    if result > 0:
        return AjaxResponse.from_success(msg='新增成功')
    return AjaxResponse.from_error(code=HttpStatus.ERROR, msg='新增失败')

{% if table.pk_column %}
@gen.route('', methods=['PUT'])
@BodyValidator()
@PreAuthorize(HasPerm('{{ table.module_name }}:{{ table.business_name }}:edit'))
@Log(title='{{ table.function_name }}管理', business_type=BusinessType.UPDATE)
@JsonSerializer()
def update_{{ underscore(table.business_name) }}(dto: {{ class_name_pascal }}):
    """修改{{ table.function_name }}"""
    {{ underscore(table.class_name) }}_entity = {{ class_name_pascal }}()
    # 转换PO到Entity对象
    for attr in dto.model_fields.keys():
        if hasattr({{ underscore(table.class_name) }}_entity, attr):
            setattr({{ underscore(table.class_name) }}_entity, attr, getattr(dto, attr))
    result = {{ underscore(table.class_name) }}_service.update_{{ underscore(table.class_name) }}({{ underscore(table.class_name) }}_entity)
    if result > 0:
        return AjaxResponse.from_success(msg='修改成功')
    return AjaxResponse.from_error(code=HttpStatus.ERROR, msg='修改失败')
{% endif %}

{% if table.pk_column %}
@gen.route('/<ids>', methods=['DELETE'])
@PathValidator()
@PreAuthorize(HasPerm('{{ table.module_name }}:{{ table.business_name }}:remove'))
@Log(title='{{ table.function_name }}管理', business_type=BusinessType.DELETE)
@JsonSerializer()
def delete_{{ underscore(table.business_name) }}(ids: str):
    """删除{{ table.function_name }}"""
    try:
        id_list = [int(id) for id in ids.split(',')]
        result = {{ underscore(table.class_name) }}_service.delete_{{ underscore(table.class_name) }}_by_ids(id_list)
        if result > 0:
            return AjaxResponse.from_success(msg='删除成功')
        return AjaxResponse.from_error(code=HttpStatus.ERROR, msg='删除失败')
    except Exception as e:
        return AjaxResponse.from_error(msg=f'删除失败: {str(e)}')
{% endif %}

@gen.route('/export', methods=['POST'])
@FileDownloadValidator()
@PreAuthorize(HasPerm('{{ table.module_name }}:{{ table.business_name }}:export'))
@Log(title='{{ table.function_name }}管理', business_type=BusinessType.EXPORT)
@BaseSerializer()
def export_{{ underscore(table.business_name) }}(dto: {{ class_name_pascal }}):
    """导出{{ table.function_name }}列表"""
    {{ underscore(table.class_name) }}_entity = {{ class_name_pascal }}()
    # 转换PO到Entity对象
    for attr in dto.model_fields.keys():
        if hasattr({{ underscore(table.class_name) }}_entity, attr):
            setattr({{ underscore(table.class_name) }}_entity, attr, getattr(dto, attr))
    _clear_page_context()
    {{ underscore(table.class_name) }}_entity.page_num = None
    {{ underscore(table.class_name) }}_entity.page_size = None
    {{ underscore(table.business_name) }}s = {{ underscore(table.class_name) }}_service.select_{{ underscore(table.class_name) }}_list({{ underscore(table.class_name) }}_entity)
    # 使用ExcelUtil导出Excel文件
    excel_util = ExcelUtil({{ class_name_pascal }})
    return excel_util.export_response({{ underscore(table.business_name) }}s, "{{ table.function_name }}数据")

@gen.route('/importTemplate', methods=['POST'])
@login_required
@BaseSerializer()
def import_template():
    """下载{{ table.function_name }}导入模板"""
    excel_util = ExcelUtil({{ class_name_pascal }})
    return excel_util.import_template_response(sheetname="{{ table.function_name }}数据")

@gen.route('/importData', methods=['POST'])
@FileUploadValidator()
@PreAuthorize(HasPerm('{{ table.module_name }}:{{ table.business_name }}:import'))
@Log(title='{{ table.function_name }}管理', business_type=BusinessType.IMPORT)
@JsonSerializer()
def import_data(
    file: List[FileStorage],
    update_support: Annotated[bool, BeforeValidator(lambda x: x != "0")]
):
    """导入{{ table.function_name }}数据"""
    file = file[0]
    excel_util = ExcelUtil({{ class_name_pascal }})
    {{ underscore(table.business_name) }}_list = excel_util.import_file(file, sheetname="{{ table.function_name }}数据")
    msg = {{ underscore(table.class_name) }}_service.import_{{ underscore(table.class_name) }}({{ underscore(table.business_name) }}_list, update_support)
    return AjaxResponse.from_success(msg=msg)
