from sqlalchemy import delete, select, update, func
from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.entity.do.message_do import Message
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.entity.vo.message_vo import MessageModel, MessagePageQueryModel
from utils.page_util import PageUtil
from datetime import datetime, time


class MessageDao:
    """
    系统消息模块数据库操作层
    """

    @classmethod
    async def get_alarm_type_distribution(cls, db: AsyncSession):
        stmt = (
            select(Message.specific_type, func.count(Message.specific_type).label("cnt"))
            .where(Message.type == '0')
            .group_by(Message.specific_type)
        )
        return (await db.execute(stmt)).mappings().all()

    @classmethod
    async def handle_all_message(cls, db: AsyncSession):
        query = (
            update(Message)
            .where(Message.status == '0', Message.type == '0')
            .values(status='1')
        )


        await db.execute(query)



    @classmethod
    async def get_message_detail_by_id(cls, db: AsyncSession, message_id: int):
        """
        根据消息主键获取系统消息详细信息

        :param db: orm对象
        :param message_id: 消息主键
        :return: 系统消息信息对象
        """
        message_info = (
            (
                await db.execute(
                    select(Message)
                    .where(
                        Message.message_id == message_id
                    )
                )
            )
            .scalars()
            .first()
        )

        return message_info

    @classmethod
    async def count_message(cls, db: AsyncSession):
        query_unhandled_message_count = (
            select(func.count(Message.message_id))
            .where(Message.status=='0', Message.type=='0')
        )

        unhandled_message_count = (
            await db.execute(query_unhandled_message_count)
        ).scalar()

        query_handled_message_count = (
            select(func.count(Message.message_id))
            .where(Message.status=='1', Message.type=='0')
        )

        handled_message_count = (
            await db.execute(query_handled_message_count)
        ).scalar()

        return unhandled_message_count+ handled_message_count, unhandled_message_count, handled_message_count

    @classmethod
    async def get_message_detail_by_info(cls, db: AsyncSession, message: MessageModel):
        """
        根据系统消息参数获取系统消息信息

        :param db: orm对象
        :param message: 系统消息参数对象
        :return: 系统消息信息对象
        """
        message_info = (
            (
                await db.execute(
                    select(Message).where(
                    )
                )
            )
            .scalars()
            .first()
        )

        return message_info

    @classmethod
    async def get_message_list(cls, db: AsyncSession, query_object: MessagePageQueryModel, is_page: bool = False):
        """
        根据查询参数获取系统消息列表信息

        :param db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 系统消息列表信息对象
        """
        query = (
            select(Message)
            .where(
                Message.type == query_object.type if query_object.type else True,
                Message.status == query_object.status if query_object.status else True,
                # Message.detail == query_object.detail if query_object.detail else True,
                Message.create_time.between(
                    datetime.combine(datetime.strptime(query_object.begin_create_time, '%Y-%m-%d'), time(00, 00, 00)),
                    datetime.combine(datetime.strptime(query_object.end_create_time, '%Y-%m-%d'), time(23, 59, 59)),
                )
                if query_object.begin_create_time and query_object.end_create_time else True,
                Message.update_time.between(
                    datetime.combine(datetime.strptime(query_object.begin_update_time, '%Y-%m-%d'), time(00, 00, 00)),
                    datetime.combine(datetime.strptime(query_object.end_update_time, '%Y-%m-%d'), time(23, 59, 59)),
                )
                if query_object.begin_update_time and query_object.end_update_time else True
            )
            .order_by(Message.message_id)
            .distinct()
        )
        message_list = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)

        return message_list

    @classmethod
    async def add_message_dao(cls, db: AsyncSession, message: MessageModel):
        """
        新增系统消息数据库操作

        :param db: orm对象
        :param message: 系统消息对象
        :return:
        """
        db_message = Message(**message.model_dump(exclude={}))
        db.add(db_message)
        await db.flush()

        return db_message

    @classmethod
    async def edit_message_dao(cls, db: AsyncSession, message: dict):
        """
        编辑系统消息数据库操作

        :param db: orm对象
        :param message: 需要更新的系统消息字典
        :return:
        """
        await db.execute(update(Message), [message])

    @classmethod
    async def delete_message_dao(cls, db: AsyncSession, message: MessageModel):
        """
        删除系统消息数据库操作

        :param db: orm对象
        :param message: 系统消息对象
        :return:
        """
        await db.execute(delete(Message).where(Message.message_id.in_([message.message_id])))

