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.sys_statistics_dao import Sys_statisticsDao
from module_admin.entity.vo.sys_statistics_vo import DeleteSys_statisticsModel, Sys_statisticsModel, Sys_statisticsPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil
from datetime import datetime, timedelta, time


class Sys_statisticsService:
    """
    系统统计数据模块服务层
    """
    # 展厅讲解次数加1
    @classmethod
    async def add_explain_count_services(cls, query_db: AsyncSession, user_name: str):
        """
        新增展厅讲解次数
        :param query_db: orm对象
        :return:
        """
        await Sys_statisticsDao.add_count(query_db, "exhibition_explanation", user_name, 1)
        await query_db.commit()
        return CrudResponseModel(is_success=True, message='更新成功')
    # 访客引导量加1
    @classmethod
    async def add_visitor_guide_count_services(cls, query_db: AsyncSession, user_name: str):
        """
        新增访客引导量
        :param query_db: orm对象
        :return:
        """
        await Sys_statisticsDao.add_count(query_db, "visitor_guide", user_name, 1)
        await query_db.commit()
        return CrudResponseModel(is_success=True, message='更新成功')
    # 门禁通行量加1
    @classmethod
    async def add_door_pass_count_services(cls, query_db: AsyncSession, user_name: str):
        """
        新增门禁通行量
        :param query_db: orm对象
        :return:
        """
        await Sys_statisticsDao.add_count(query_db, "access_control_count", user_name, 1)
        await query_db.commit()
        return CrudResponseModel(is_success=True, message='更新成功')
    # 大模型调用量加1
    @classmethod
    async def add_model_call_count_services(cls, query_db: AsyncSession, user_name: str):
        """
        新增模型调用次数
        :param query_db: orm对象
        :return:
        """
        # await Sys_statisticsDao.add_model_call_count(query_db, user_name)
        await Sys_statisticsDao.add_count(query_db, "llm_call", user_name, 1)
        await query_db.commit()
        return CrudResponseModel(is_success=True, message='更新成功')

    # 根据时间区间获取门禁识别成功率
    @classmethod
    async def get_access_control_success_rate_services(cls, query_db: AsyncSession, day: int):
        end_date = datetime.now().date() - timedelta(days=1)
        start_date = end_date - timedelta(days=day)
        result = await Sys_statisticsDao.get_access_control_success_rate(query_db, start_date, end_date)
        return result



    # 根据时间区间获取访客数量
    @classmethod
    async def get_visitor_count_services(cls, query_db: AsyncSession, day: int):
        end_date = datetime.now().date() - timedelta(days=1)
        start_date = end_date - timedelta(days=day)
        result = await Sys_statisticsDao.get_visitor_count(query_db, start_date, end_date)
        # if len(result) < day:

        return result



    # 获取系统统计数据
    @classmethod
    async def get_statistics_data_services(cls, query_db: AsyncSession):

        # 当前日期
        today = datetime.now().date()
        yesterday = today - timedelta(days=1)
        data_1 = await Sys_statisticsDao.get_statistics_data(query_db, yesterday)
        data_2 = await Sys_statisticsDao.get_statistics_data(query_db, today)
        if data_1 is None:
            data_1 = {
                "llm_call": 0,
                "access_control_count": 0,
                "visitor_guide": 0,
                "exhibition_explanation": 0
            }
        else:
            data_1 =dict(data_1)
        if data_2 is None:
            data_2 = {
                "llm_call": 0,
                "access_control_count": 0,
                "visitor_guide": 0,
                "exhibition_explanation": 0
            }
        else:
            data_2 =dict(data_2)
        #
        for k, v in data_1.items():
            data_1[k] = data_2[k] - v

        return {
            'change': data_1,
            'today': data_2
        }

    @classmethod
    async def get_sys_statistics_list_services(
        cls, query_db: AsyncSession, query_object: Sys_statisticsPageQueryModel, is_page: bool = False
    ):
        """
        获取系统统计数据列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 系统统计数据列表信息对象
        """
        sys_statistics_list_result = await Sys_statisticsDao.get_sys_statistics_list(query_db, query_object, is_page)

        return sys_statistics_list_result


    @classmethod
    async def add_sys_statistics_services(cls, query_db: AsyncSession, page_object: Sys_statisticsModel):
        """
        新增系统统计数据信息service

        :param query_db: orm对象
        :param page_object: 新增系统统计数据对象
        :return: 新增系统统计数据校验结果
        """
        try:
            await Sys_statisticsDao.add_sys_statistics_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_sys_statistics_services(cls, query_db: AsyncSession, page_object: Sys_statisticsModel):
        """
        编辑系统统计数据信息service

        :param query_db: orm对象
        :param page_object: 编辑系统统计数据对象
        :return: 编辑系统统计数据校验结果
        """
        edit_sys_statistics = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'create_by', })
        sys_statistics_info = await cls.sys_statistics_detail_services(query_db, page_object.statistic_id)
        if sys_statistics_info.statistic_id:
            try:
                await Sys_statisticsDao.edit_sys_statistics_dao(query_db, edit_sys_statistics)
                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_sys_statistics_services(cls, query_db: AsyncSession, page_object: DeleteSys_statisticsModel):
        """
        删除系统统计数据信息service

        :param query_db: orm对象
        :param page_object: 删除系统统计数据对象
        :return: 删除系统统计数据校验结果
        """
        if page_object.statistic_ids:
            statistic_id_list = page_object.statistic_ids.split(',')
            try:
                for statistic_id in statistic_id_list:
                    await Sys_statisticsDao.delete_sys_statistics_dao(query_db, Sys_statisticsModel(statisticId=statistic_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 sys_statistics_detail_services(cls, query_db: AsyncSession, statistic_id: int):
        """
        获取系统统计数据详细信息service

        :param query_db: orm对象
        :param statistic_id: 统计项目ID
        :return: 统计项目ID对应的信息
        """
        sys_statistics = await Sys_statisticsDao.get_sys_statistics_detail_by_id(query_db, statistic_id=statistic_id)
        if sys_statistics:
            result = Sys_statisticsModel(**CamelCaseUtil.transform_result(sys_statistics))
        else:
            result = Sys_statisticsModel(**dict())

        return result

    @staticmethod
    async def export_sys_statistics_list_services(sys_statistics_list: List):
        """
        导出系统统计数据信息service

        :param sys_statistics_list: 系统统计数据信息列表
        :return: 系统统计数据信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'statisticId': '统计项目ID',
            'statDate': '统计日期',
            'llmCall': '大模型调用量',
            'accessControlCount': '门禁通行量',
            'visitorGuide': '访客引导次数',
            'exhibitionExplanation': '展厅讲解次数',
            'accessControlSuccessRate': '门禁识别成功率(%)',
            'createTime': '创建时间',
            'createBy': '创建者',
            'updateTime': '修改时间',
            'updateBy': '修改者',
        }
        binary_data = ExcelUtil.export_list2excel(sys_statistics_list, mapping_dict)

        return binary_data
