# -*- coding: utf-8 -*-
# @Author  : {{ table.function_author }}
# @FileName: {{ underscore(table.class_name) }}_service.py
# @Time    : {{ datetime }}

from typing import List

from ruoyi_common.exception import ServiceException
from ruoyi_common.utils.base import LogUtil
from {{ get_import_path(table.package_name, table.module_name, 'domain') }} import {{ table.class_name }}
from {{ get_import_path(table.package_name, table.module_name, 'mapper') }}.{{ underscore(table.class_name) }}_mapper import {{ underscore(table.class_name) }}_mapper

class {{ underscore(table.class_name) }}_service:
    """{{ table.function_name }}服务类"""

    def select_{{ underscore(table.class_name) }}_list(self, {{ underscore(table.business_name) }}: {{ table.class_name }}) -> List[{{ table.class_name }}]:
        """
        查询{{ table.function_name }}列表

        Args:
            {{ underscore(table.business_name) }} ({{ table.class_name }}): {{ table.function_name }}对象

        Returns:
            List[{{ table.class_name }}]: {{ table.function_name }}列表
        """
        return {{ underscore(table.class_name) }}_mapper.select_{{ underscore(table.class_name) }}_list({{ underscore(table.business_name) }})

    {% if table.pk_column %}
    def select_{{ underscore(table.class_name) }}_by_id(self, {{ underscore(table.pk_column.java_field) }}: int) -> {{ table.class_name }}:
        """
        根据ID查询{{ table.function_name }}

        Args:
            {{ underscore(table.pk_column.java_field) }} (int): {{ table.pk_column.column_comment }}

        Returns:
            {{ table.class_name }}: {{ table.function_name }}对象
        """
        return {{ underscore(table.class_name) }}_mapper.select_{{ underscore(table.class_name) }}_by_id({{ underscore(table.pk_column.java_field) }})
    {% endif %}

    def insert_{{ underscore(table.class_name) }}(self, {{ underscore(table.business_name) }}: {{ table.class_name }}) -> int:
        """
        新增{{ table.function_name }}

        Args:
            {{ underscore(table.business_name) }} ({{ table.class_name }}): {{ table.function_name }}对象

        Returns:
            int: 插入的记录数
        """
        return {{ underscore(table.class_name) }}_mapper.insert_{{ underscore(table.class_name) }}({{ underscore(table.business_name) }})

    {% if table.pk_column %}
    def update_{{ underscore(table.class_name) }}(self, {{ underscore(table.business_name) }}: {{ table.class_name }}) -> int:
        """
        修改{{ table.function_name }}

        Args:
            {{ underscore(table.business_name) }} ({{ table.class_name }}): {{ table.function_name }}对象

        Returns:
            int: 更新的记录数
        """
        return {{ underscore(table.class_name) }}_mapper.update_{{ underscore(table.class_name) }}({{ underscore(table.business_name) }})
    {% endif %}

    {% if table.pk_column %}
    def delete_{{ underscore(table.class_name) }}_by_ids(self, ids: List[int]) -> int:
        """
        批量删除{{ table.function_name }}

        Args:
            ids (List[int]): ID列表

        Returns:
            int: 删除的记录数
        """
        return {{ underscore(table.class_name) }}_mapper.delete_{{ underscore(table.class_name) }}_by_ids(ids)
    {% endif %}

    def import_{{ underscore(table.class_name) }}(self, {{ underscore(table.business_name) }}_list: List[{{ table.class_name }}], is_update: bool = False) -> str:
        """
        导入{{ table.function_name }}数据

        Args:
            {{ underscore(table.business_name) }}_list (List[{{ table.class_name }}]): {{ table.function_name }}列表
            is_update (bool): 是否更新已存在的数据

        Returns:
            str: 导入结果消息
        """
        if not {{ underscore(table.business_name) }}_list:
            raise ServiceException("导入{{ table.function_name }}数据不能为空")

        success_count = 0
        fail_count = 0
        success_msg = ""
        fail_msg = ""

        for {{ underscore(table.business_name) }} in {{ underscore(table.business_name) }}_list:
            try:
                display_value = {{ underscore(table.business_name) }}
                {% if table.pk_column %}
                display_value = getattr({{ underscore(table.business_name) }}, "{{ underscore(table.pk_column.java_field) }}", display_value)
                existing = None
                if {{ underscore(table.business_name) }}.{{ underscore(table.pk_column.java_field) }} is not None:
                    existing = {{ underscore(table.class_name) }}_mapper.select_{{ underscore(table.class_name) }}_by_id({{ underscore(table.business_name) }}.{{ underscore(table.pk_column.java_field) }})
                if existing:
                    if is_update:
                        result = {{ underscore(table.class_name) }}_mapper.update_{{ underscore(table.class_name) }}({{ underscore(table.business_name) }})
                    else:
                        fail_count += 1
                        fail_msg += f"<br/> 第{fail_count}条数据，已存在：{display_value}"
                        continue
                else:
                    result = {{ underscore(table.class_name) }}_mapper.insert_{{ underscore(table.class_name) }}({{ underscore(table.business_name) }})
                {% else %}
                display_value = str(display_value)
                result = {{ underscore(table.class_name) }}_mapper.insert_{{ underscore(table.class_name) }}({{ underscore(table.business_name) }})
                {% endif %}
                if result > 0:
                    success_count += 1
                    success_msg += f"<br/> 第{success_count}条数据，操作成功：{display_value}"
                else:
                    fail_count += 1
                    fail_msg += f"<br/> 第{fail_count}条数据，操作失败：{display_value}"
            except Exception as e:
                fail_count += 1
                fail_msg += f"<br/> 第{fail_count}条数据，导入失败，原因：{e.__class__.__name__}"
                LogUtil.logger.error(f"导入{{ table.function_name }}失败，原因：{e}")

        if fail_count > 0:
            if success_msg:
                fail_msg = f"导入成功{success_count}条，失败{fail_count}条。{success_msg}<br/>" + fail_msg
            else:
                fail_msg = f"导入成功{success_count}条，失败{fail_count}条。{fail_msg}"
            raise ServiceException(fail_msg)
        success_msg = f"恭喜您，数据已全部导入成功！共 {success_count} 条，数据如下：" + success_msg
        return success_msg