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.info_dao import InfoDao
from module_admin.entity.vo.info_vo import DeleteInfoModel, InfoModel, InfoPageQueryModel, InfoUpdateModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class InfoService:
    """
    机器人信息模块服务层
    """


    @classmethod
    async def refresh_robot_services(cls, query_db: AsyncSession, robot_ids: str):
        return await InfoDao.refresh_robot_by_ids(query_db, robot_ids)

    @classmethod
    async def get_info_list_services(
        cls, query_db: AsyncSession, query_object: InfoPageQueryModel, is_page: bool = False
    ):
        """
        获取机器人信息列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 机器人信息列表信息对象
        """
        info_list_result = await InfoDao.get_info_list(query_db, query_object, is_page)

        return info_list_result


    @classmethod
    async def add_info_services(cls, query_db: AsyncSession, page_object: InfoModel):
        """
        新增机器人信息信息service

        :param query_db: orm对象
        :param page_object: 新增机器人信息对象
        :return: 新增机器人信息校验结果
        """
        try:
            await InfoDao.add_info_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_info_services(cls, query_db: AsyncSession, page_object: InfoUpdateModel):
        """
        编辑机器人信息信息service

        :param query_db: orm对象
        :param page_object: 编辑机器人信息对象
        :return: 编辑机器人信息校验结果
        """
        edit_info = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'create_by', 'del_flag', })
        info_info = await cls.info_detail_services(query_db, page_object.robot_id)
        if info_info.robot_id:
            try:
                await InfoDao.edit_info_dao(query_db, edit_info)
                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_info_services(cls, query_db: AsyncSession, page_object: DeleteInfoModel):
        """
        删除机器人信息信息service

        :param query_db: orm对象
        :param page_object: 删除机器人信息对象
        :return: 删除机器人信息校验结果
        """
        if page_object.robot_ids:
            robot_id_list = page_object.robot_ids.split(',')
            try:
                for robot_id in robot_id_list:
                    await InfoDao.delete_info_dao(query_db, InfoModel(robotId=robot_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 info_detail_services(cls, query_db: AsyncSession, robot_id: int):
        """
        获取机器人信息详细信息service

        :param query_db: orm对象
        :param robot_id: 机器人ID
        :return: 机器人ID对应的信息
        """
        info = await InfoDao.get_info_detail_by_id(query_db, robot_id=robot_id)
        if info:
            result = InfoModel(**CamelCaseUtil.transform_result(info))
        else:
            result = InfoModel(**dict())

        return result

    @staticmethod
    async def export_info_list_services(info_list: List):
        """
        导出机器人信息信息service

        :param info_list: 机器人信息信息列表
        :return: 机器人信息信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'robotId': '机器人ID',
            'name': '机器人名称',
            'model': '机器人型号',
            'serial': '序列号',
            'online': '机器人在线状态(0在线, 1离线)',
            'power': '电量',
            'runTime': '总运行时长',
            'position': '位置',
            'image': '机器人外观图地址',
            'createTime': '创建时间',
            'createBy': '创建者',
            'updateTime': '修改时间',
            'updateBy': '修改者',
            'delFlag': '删除标志(0存在, 2删除)',
            'remark': '备注',
        }
        binary_data = ExcelUtil.export_list2excel(info_list, mapping_dict)

        return binary_data
