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.words_dao import WordsDao
from module_admin.entity.vo.words_vo import DeleteWordsModel, WordsModel, WordsPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil
import random 


class WordsService:
    """
    引导词模块服务层
    """
    
    # 随机获取引导词
    @classmethod
    async def get_random_guide_word_services(cls, query_db: AsyncSession, type: str):
        """
        随机获取引导词

        :param query_db: orm对象
        :param type: 引导词类型
        :return: 引导词信息
        """
        guide_word = await WordsDao.get_words_by_type(query_db, type)
        if guide_word: 
            return guide_word[random.randint(0, len(guide_word) - 1)]
        
        return guide_word

    # 批量禁用/启用引导词
    @classmethod
    async def edit_del_words_services(cls, query_db: AsyncSession, guide_ids: str, del_flg:str):

        try:
            await WordsDao.edit_del_words(query_db, guide_ids, del_flg)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='批量修改')
        except Exception as e:
            query_db.rollback()
            raise e


    @classmethod
    async def get_words_list_services(
        cls, query_db: AsyncSession, query_object: WordsPageQueryModel, is_page: bool = False
    ):
        """
        获取引导词列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 引导词列表信息对象
        """
        words_list_result = await WordsDao.get_words_list(query_db, query_object, is_page)

        return words_list_result


    @classmethod
    async def add_words_services(cls, query_db: AsyncSession, page_object: WordsModel):
        """
        新增引导词信息service

        :param query_db: orm对象
        :param page_object: 新增引导词对象
        :return: 新增引导词校验结果
        """
        try:
            await WordsDao.add_words_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_words_services(cls, query_db: AsyncSession, page_object: WordsModel):
        """
        编辑引导词信息service

        :param query_db: orm对象
        :param page_object: 编辑引导词对象
        :return: 编辑引导词校验结果
        """
        edit_words = page_object.model_dump(exclude_unset=True, exclude={'create_time', 'create_by', })
        words_info = await cls.words_detail_services(query_db, page_object.guide_id)
        if words_info.guide_id:
            try:
                await WordsDao.edit_words_dao(query_db, edit_words)
                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_words_services(cls, query_db: AsyncSession, page_object: DeleteWordsModel):
        """
        删除引导词信息service

        :param query_db: orm对象
        :param page_object: 删除引导词对象
        :return: 删除引导词校验结果
        """
        if page_object.guide_ids:
            guide_id_list = page_object.guide_ids.split(',')
            try:
                for guide_id in guide_id_list:
                    await WordsDao.delete_words_dao(query_db, WordsModel(guideId=guide_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 words_detail_services(cls, query_db: AsyncSession, guide_id: int):
        """
        获取引导词详细信息service

        :param query_db: orm对象
        :param guide_id: 引导词id
        :return: 引导词id对应的信息
        """
        words = await WordsDao.get_words_detail_by_id(query_db, guide_id=guide_id)
        if words:
            result = WordsModel(**CamelCaseUtil.transform_result(words))
        else:
            result = WordsModel(**dict())

        return result

    @staticmethod
    async def export_words_list_services(words_list: List):
        """
        导出引导词信息service

        :param words_list: 引导词信息列表
        :return: 引导词信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'guideId': '引导词id',
            'type': '引导词类型',
            'text': '文本内容',
            'createTime': '创建时间',
            'updateTime': '修改时间',
            'createBy': '创建者',
            'remark': '备注',
            'delFlag': '删除标志',
        }
        binary_data = ExcelUtil.export_list2excel(words_list, mapping_dict)

        return binary_data
