from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.dao.role_dao import RoleDao
from module_admin.entity.vo.role_vo import DeleteRoleModel, RoleModel, RolePageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class RoleService:
    """
    系统角色模块服务层
    """

    @classmethod
    async def get_role_list_services(
        cls, query_db: AsyncSession, query_object: RolePageQueryModel, is_page: bool = False
    ):
        """
        获取系统角色列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 系统角色列表信息对象
        """
        role_list_result = await RoleDao.get_role_list(query_db, query_object, is_page)

        return role_list_result


    @classmethod
    async def add_role_services(cls, query_db: AsyncSession, page_object: RoleModel):
        """
        新增系统角色信息service

        :param query_db: orm对象
        :param page_object: 新增系统角色对象
        :return: 新增系统角色校验结果
        """
        try:
            await RoleDao.add_role_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_role_services(cls, query_db: AsyncSession, page_object: RoleModel):
        """
        编辑系统角色信息service

        :param query_db: orm对象
        :param page_object: 编辑系统角色对象
        :return: 编辑系统角色校验结果
        """
        edit_role = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'create_by', })
        role_info = await cls.role_detail_services(query_db, page_object.robot_role_id)
        if role_info.robot_role_id:
            try:
                await RoleDao.edit_role_dao(query_db, edit_role)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='系统角色不存在')

    @classmethod
    async def delete_role_services(cls, query_db: AsyncSession, page_object: DeleteRoleModel):
        """
        删除系统角色信息service

        :param query_db: orm对象
        :param page_object: 删除系统角色对象
        :return: 删除系统角色校验结果
        """
        if page_object.robot_role_ids:
            robot_role_id_list = page_object.robot_role_ids.split(',')
            try:
                for robot_role_id in robot_role_id_list:
                    await RoleDao.delete_role_dao(query_db, RoleModel(robotRoleId=robot_role_id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入机器人角色ID为空')

    @classmethod
    async def role_detail_services(cls, query_db: AsyncSession, robot_role_id: int):
        """
        获取系统角色详细信息service

        :param query_db: orm对象
        :param robot_role_id: 机器人角色ID
        :return: 机器人角色ID对应的信息
        """
        role = await RoleDao.get_role_detail_by_id(query_db, robot_role_id=robot_role_id)
        if role:
            result = RoleModel(**CamelCaseUtil.transform_result(role))
        else:
            result = RoleModel(**dict())

        return result

    @staticmethod
    async def export_role_list_services(role_list: List):
        """
        导出系统角色信息service

        :param role_list: 系统角色信息列表
        :return: 系统角色信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'robotRoleId': '机器人角色ID',
            'rolename': '角色名称',
            'detail': '角色介绍',
            'createTime': '创建时间',
            'createBy': '创建者',
            'updateTime': '修改时间',
            'updateBy': '修改者',
            'remark': '备注',
        }
        binary_data = ExcelUtil.export_list2excel(role_list, mapping_dict)

        return binary_data
