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.entity.do.identification_record_do import IdentificationRecord
from module_admin.dao.identification_record_dao import Identification_recordDao
from module_admin.dao.door_dao import DoorDao
from module_admin.entity.vo.identification_record_vo import DeleteIdentification_recordModel, Identification_recordModel, Identification_recordPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil
from utils.haikang_util import HaikangUtil

from datetime import datetime
from dateutil import tz


class Identification_recordService:
    """
    识别记录模块服务层
    """

    @classmethod
    async def get_identification_record_list_services(
        cls, query_db: AsyncSession, query_object: Identification_recordPageQueryModel, is_page: bool = False
    ):
        """
        获取识别记录列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 识别记录列表信息对象
        """
        t = query_object.page_size
        query_object.page_size = query_object.page_size//2
        identification_record_list_result = await Identification_recordDao.get_identification_record_list(query_db, query_object, is_page)
        
        # 这里也要获取海康的识别记录, 查询时间需要满足ISO8601标准
        start_time = cls.time_2_iso8601(query_object.begin_create_time) if query_object.begin_create_time else None
        end_time  = cls.time_2_iso8601(query_object.end_create_time) if query_object.end_create_time else None
        
        # 获取门禁点列表, 获取机器人添加的门禁设备列表,有权限的.
        door_index_code_list = await DoorDao.get_door_index_code_list(query_db, permission='1')
        haikang_record_list = await HaikangUtil.query_door_events_v2(door_index_code_list
                                                                     ,pageNo=query_object.page_num
                                                                     , pageSize=max(t-query_object.page_size, t-len(identification_record_list_result.rows)) 
                                                                     ,startTime=start_time, endTime=end_time
                                                                     ,personName=query_object.person_name)

        # print(identification_record_list_result.rows)
        # print("*"*100)
        # print(haikang_record_list[1])
        return identification_record_list_result.rows + cls.parse_haikang_record_list(haikang_record_list[1]["list"])
        # return None


    @classmethod
    async def add_identification_record_services(cls, query_db: AsyncSession, page_object: Identification_recordModel):
        """
        新增识别记录信息service

        :param query_db: orm对象
        :param page_object: 新增识别记录对象
        :return: 新增识别记录校验结果
        """
        try:
            await Identification_recordDao.add_identification_record_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_identification_record_services(cls, query_db: AsyncSession, page_object: Identification_recordModel):
        """
        编辑识别记录信息service

        :param query_db: orm对象
        :param page_object: 编辑识别记录对象
        :return: 编辑识别记录校验结果
        """
        edit_identification_record = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'create_by'})
        identification_record_info = await cls.identification_record_detail_services(query_db, page_object.id)
        if identification_record_info.id:
            try:
                await Identification_recordDao.edit_identification_record_dao(query_db, edit_identification_record)
                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_identification_record_services(cls, query_db: AsyncSession, page_object: DeleteIdentification_recordModel):
        """
        删除识别记录信息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 Identification_recordDao.delete_identification_record_dao(query_db, Identification_recordModel(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 identification_record_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取识别记录详细信息service

        :param query_db: orm对象
        :param id: 主键 自增
        :return: 主键 自增对应的信息
        """
        identification_record = await Identification_recordDao.get_identification_record_detail_by_id(query_db, id=id)
        if identification_record:
            result = Identification_recordModel(**CamelCaseUtil.transform_result(identification_record))
        else:
            result = Identification_recordModel(**dict())

        return result

    @staticmethod
    async def export_identification_record_list_services(identification_record_list: List):
        """
        导出识别记录信息service

        :param identification_record_list: 识别记录信息列表
        :return: 识别记录信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': '主键 自增',
            'personName': '识别人姓名',
            'doorName': '门禁点',
            'status': '识别结果, 0 拒绝, 1 通过',
            'source': '识别来源',
            'picUri': '图像url',
            'createTime': '创建时间',
            'createBy': '创建者',
        }
        binary_data = ExcelUtil.export_list2excel(identification_record_list, mapping_dict)

        return binary_data
    
    @classmethod
    def time_2_iso8601(cls, time_str):
        # 解析日期并设置时区为东八区
        dt = datetime.strptime(time_str, "%Y-%m-%d").replace(tzinfo=tz.gettz("Asia/Shanghai"))

        # 转换为 ISO 8601 格式
        iso_format = dt.isoformat()
        
        return iso_format
    
    @classmethod
    def parse_haikang_record_list(cls, record_list: list):
        back = list()
        for record in record_list:
            back.append(IdentificationRecord(person_name=record['personName'], person_status="1", door_name=record['doorName'], pic_uri=record['picUri']
                                             , status="1", source="haikang", conf=100, create_time=record['eventTime']))
            
        return back
