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.door_dao import DoorDao
from module_admin.dao.info_dao import InfoDao
from module_admin.entity.vo.door_vo import DeleteDoorModel, DoorModel, DoorPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil
from utils.haikang_util import HaikangUtil


class DoorService:
    """
    门禁设备模块服务层
    """
    
    @classmethod
    async def get_video_uri_service(cls, robot_id: int , query_db: AsyncSession):
        """获取机器人视频流
        """
        video_uri = await InfoDao.get_video_uri(robot_id, query_db)
        return video_uri
        
    
    @classmethod
    async def get_door_status_service(cls, query_db: AsyncSession):
        """获取门禁状态

        Args:
            query_db (AsyncSession): orm对象
        Returns:
            _type_: _description_
        """
        
        door_indexcode_name = await DoorDao.get_door_door_status(query_db)
        
        t_d = dict()
        index_code_list = list()
        for t in door_indexcode_name:
            t_d[t["indexCode"]] = t["name"]
            index_code_list.append(t["indexCode"])
        
        door_online_status_result = await HaikangUtil.door_online_status(index_code_list)
        
        if door_online_status_result[0]:
            back = list()
            for door_online_status in door_online_status_result[1]['list']:
                back.append({
                    "name": t_d.get(door_online_status['indexCode'], None),
                    "online": door_online_status['online']
                })
            
            return True, back
        return door_online_status_result

    @classmethod
    async def get_door_list_services(
        cls, query_db: AsyncSession, query_object: DoorPageQueryModel, is_page: bool = False
    ):
        """
        获取门禁设备列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 门禁设备列表信息对象
        """
        door_list_result = await DoorDao.get_door_list(query_db, query_object, is_page)
        
        # 获取门禁在线状态

        return door_list_result


    @classmethod
    async def add_door_services(cls, query_db: AsyncSession, page_object: DoorModel):
        """
        新增门禁设备信息service

        :param query_db: orm对象
        :param page_object: 新增门禁设备对象
        :return: 新增门禁设备校验结果
        """
        try:
            await DoorDao.add_door_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_door_services(cls, query_db: AsyncSession, page_object: DoorModel):
        """
        编辑门禁设备信息service

        :param query_db: orm对象
        :param page_object: 编辑门禁设备对象
        :return: 编辑门禁设备校验结果
        """
        edit_door = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'create_by', })
        door_info = await cls.door_detail_services(query_db, page_object.id)
        if door_info.id:
            try:
                await DoorDao.edit_door_dao(query_db, edit_door)
                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_door_services(cls, query_db: AsyncSession, page_object: DeleteDoorModel):
        """
        删除门禁设备信息service

        :param query_db: orm对象
        :param page_object: 删除门禁设备对象
        :return: 删除门禁设备校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await DoorDao.delete_door_dao(query_db, DoorModel(id=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='传入主键自增为空')

    @classmethod
    async def door_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取门禁设备详细信息service

        :param query_db: orm对象
        :param id: 主键自增
        :return: 主键自增对应的信息
        """
        door = await DoorDao.get_door_detail_by_id(query_db, id=id)
        if door:
            result = DoorModel(**CamelCaseUtil.transform_result(door))
        else:
            result = DoorModel(**dict())

        return result

    @staticmethod
    async def export_door_list_services(door_list: List):
        """
        导出门禁设备信息service

        :param door_list: 门禁设备信息列表
        :return: 门禁设备信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': '主键自增',
            'indexCode': '设备索引编码',
            'name': '门禁名称',
            'installLocation': '位置名称',
            'status': '设备状态, 0 离线, 1 正常在线',
            'permission': '权限, 0 禁用, 1 正常调用',
            'createTime': '创建时间',
            'createBy': '创建者',
            'updateTime': '更新时间',
            'updateBy': '更新者',
        }
        binary_data = ExcelUtil.export_list2excel(door_list, mapping_dict)

        return binary_data
