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.robot_role_pairing_dao import PairingDao
from module_admin.dao.explanation_style_robot_pair_dao import Explanation_style_robot_pairDao
from module_admin.entity.vo.robot_role_pairing_vo import DeletePairingModel, PairingModel, PairingPageQueryModel, \
    ChangeRobotRoleModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class PairingService:
    """
    角色-机器人-映射模块服务层
    """

    @classmethod
    async def change_robot_role_services(cls, query_db: AsyncSession,change_pairing: ChangeRobotRoleModel):
        try:
            # 现修改原本角色status为0
            print("xxxxxxxxxxxxxxx", change_pairing.robot_id)
            await PairingDao.edit_pairing_status(query_db, change_pairing.robot_id, None, '0')
            # 再修改新的角色status为1
            print("xxxxxxxxxxxxxxx", change_pairing.pairing_id)
            await PairingDao.edit_pairing_status(query_db, None, change_pairing.pairing_id, '1')

            await query_db.commit()

        except Exception as e:
            await query_db.rollback()
            raise e
    @classmethod
    async def get_role_pairing_list_services(cls, query_db: AsyncSession, robot_id: int):
        pairing_list = await PairingDao.get_role_pairing_list(query_db, robot_id)

        # style_list = list()
        style = None
        # print(pairing_list)
        for pairing in pairing_list:

            if pairing["status"] == '1':
                style = await Explanation_style_robot_pairDao.get_robot_role_style(query_db, robot_id, pairing["robot_role_id"])
            # style_list.append(style)

        return pairing_list, style

    @classmethod
    async def get_role_pairing_list_services_v1(cls, query_db: AsyncSession, robot_id: int) -> list:
        """ 获取机器人角色对齐风格列表

        Args:
            query_db (AsyncSession): db
            robot_id (int): 机器人id

        Returns:
            list: 机器人角色风格对齐列表
        """

        pairing_list = await PairingDao.get_role_pairing_list(query_db, robot_id)

        style_list = list()

        for pairing in pairing_list:

            style = await Explanation_style_robot_pairDao.get_robot_role_style(
                query_db, robot_id, pairing["robot_role_id"]
            )
            style_list.append(style)

        return pairing_list, style_list

    @classmethod
    async def get_pairing_list_services(
        cls, query_db: AsyncSession, query_object: PairingPageQueryModel, is_page: bool = False
    ):
        """
        获取角色-机器人-映射列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 角色-机器人-映射列表信息对象
        """
        pairing_list_result = await PairingDao.get_pairing_list(query_db, query_object, is_page)

        return pairing_list_result

    @classmethod
    async def add_pairing_services(cls, query_db: AsyncSession, page_object: PairingModel):
        """
        新增角色-机器人-映射信息service

        :param query_db: orm对象
        :param page_object: 新增角色-机器人-映射对象
        :return: 新增角色-机器人-映射校验结果
        """
        try:
            await PairingDao.add_pairing_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_pairing_services(cls, query_db: AsyncSession, page_object: PairingModel):
        """
        编辑角色-机器人-映射信息service

        :param query_db: orm对象
        :param page_object: 编辑角色-机器人-映射对象
        :return: 编辑角色-机器人-映射校验结果
        """
        edit_pairing = page_object.model_dump(exclude_unset=True, exclude={})
        pairing_info = await cls.pairing_detail_services(query_db, page_object.pairing_id)
        if pairing_info.pairing_id:
            try:
                await PairingDao.edit_pairing_dao(query_db, edit_pairing)
                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_pairing_services(cls, query_db: AsyncSession, page_object: DeletePairingModel):
        """
        删除角色-机器人-映射信息service

        :param query_db: orm对象
        :param page_object: 删除角色-机器人-映射对象
        :return: 删除角色-机器人-映射校验结果
        """
        if page_object.pairing_ids:
            pairing_id_list = page_object.pairing_ids.split(',')
            try:
                for pairing_id in pairing_id_list:
                    await PairingDao.delete_pairing_dao(query_db, PairingModel(pairingId=pairing_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 pairing_detail_services(cls, query_db: AsyncSession, pairing_id: int):
        """
        获取角色-机器人-映射详细信息service

        :param query_db: orm对象
        :param pairing_id: 主键ID
        :return: 主键ID对应的信息
        """
        pairing = await PairingDao.get_pairing_detail_by_id(query_db, pairing_id=pairing_id)
        if pairing:
            result = PairingModel(**CamelCaseUtil.transform_result(pairing))
        else:
            result = PairingModel(**dict())

        return result

    @staticmethod
    async def export_pairing_list_services(pairing_list: List):
        """
        导出角色-机器人-映射信息service

        :param pairing_list: 角色-机器人-映射信息列表
        :return: 角色-机器人-映射信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'pairingId': '主键ID',
            'robotRoleId': '机器人角色ID',
            'robotId': '机器人ID',
            'status': '使用情况(0停用,1使用)',
            'updateTime': '更新时间',
            'updateBy': '修改者',
        }
        binary_data = ExcelUtil.export_list2excel(pairing_list, mapping_dict)

        return binary_data
