import { api } from 'shared/api'
import type { ResultDomain, PageRequest } from 'shared/types'
import type {
    TbChatRoomDTO,
    TbChatRoomMemberDTO,
    TbChatRoomMessageDTO,
    TbCustomerServiceDTO,
    TbWordCloudDTO,
    TbVideoMeetingDTO,
    ChatRoomVO,
    ChatMemberVO,
    ChatRoomMessageVO,
    CustomerServiceVO,
    VideoMeetingVO
} from '@/types/workcase'

/**
 * @description    工单对话相关接口（ChatRoom、客服、词云管理）
 * @filename    workcaseChat.ts
 * @author    cascade
 * @copyright xyzh
 * @since 2025-12-22
 */
export const workcaseChatAPI = {
    baseUrl: '/urban-lifeline/workcase/chat',

    // ====================== ChatRoom聊天室管理 ======================

    /**
     * 创建聊天室
     */
    async createChatRoom(chatRoom: TbChatRoomDTO): Promise<ResultDomain<TbChatRoomDTO>> {
        const response = await api.post<TbChatRoomDTO>(`${this.baseUrl}/room`, chatRoom)
        return response.data
    },

    /**
     * 更新聊天室
     */
    async updateChatRoom(chatRoom: TbChatRoomDTO): Promise<ResultDomain<TbChatRoomDTO>> {
        const response = await api.put<TbChatRoomDTO>(`${this.baseUrl}/room`, chatRoom)
        return response.data
    },

    /**
     * 关闭聊天室
     */
    async closeChatRoom(roomId: string, closedBy: string): Promise<ResultDomain<boolean>> {
        const response = await api.post<boolean>(`${this.baseUrl}/room/${roomId}/close`, null, {
            params: { closedBy }
        })
        return response.data
    },

    /**
     * 获取聊天室详情
     */
    async getChatRoomById(roomId: string): Promise<ResultDomain<TbChatRoomDTO>> {
        const response = await api.get<TbChatRoomDTO>(`${this.baseUrl}/room/${roomId}`)
        return response.data
    },

    /**
     * 分页查询聊天室（含当前用户未读数）
     * @param pageRequest - 分页请求，filter.guestId用于过滤聊天室（guest用）
     * 注：userId从token中自动获取，无需传递
     */
    async getChatRoomPage(pageRequest: PageRequest<TbChatRoomDTO>): Promise<ResultDomain<ChatRoomVO>> {
        const response = await api.post<ChatRoomVO>(`${this.baseUrl}/room/page`, pageRequest)
        return response.data
    },

    // ====================== ChatRoom成员管理 ======================

    /**
     * 添加聊天室成员
     */
    async addChatRoomMember(member: TbChatRoomMemberDTO): Promise<ResultDomain<TbChatRoomMemberDTO>> {
        const response = await api.post<TbChatRoomMemberDTO>(`${this.baseUrl}/room/member`, member)
        return response.data
    },

    /**
     * 移除聊天室成员
     */
    async removeChatRoomMember(memberId: string): Promise<ResultDomain<boolean>> {
        const response = await api.delete<boolean>(`${this.baseUrl}/room/member/${memberId}`)
        return response.data
    },

    /**
     * 获取聊天室成员列表
     */
    async getChatRoomMemberList(roomId: string): Promise<ResultDomain<ChatMemberVO>> {
        const response = await api.get<ChatMemberVO>(`${this.baseUrl}/room/${roomId}/members`)
        return response.data
    },

    /**
     * 获取当前用户在指定聊天室的未读消息数
     */
    async getUnreadCount(roomId: string, userId: string): Promise<ResultDomain<number>> {
        const response = await api.get<number>(`${this.baseUrl}/room/${roomId}/unread`, 
            { userId }
        )
        return response.data
    },

    // ====================== ChatRoom消息管理 ======================

    /**
     * 发送聊天室消息
     */
    async sendMessage(message: TbChatRoomMessageDTO): Promise<ResultDomain<TbChatRoomMessageDTO>> {
        const response = await api.post<TbChatRoomMessageDTO>(`${this.baseUrl}/room/message`, message)
        return response.data
    },

    /**
     * 分页查询聊天室消息
     */
    async getChatMessagePage(pageRequest: PageRequest<TbChatRoomMessageDTO>): Promise<ResultDomain<ChatRoomMessageVO>> {
        const response = await api.post<ChatRoomMessageVO>(`${this.baseUrl}/room/message/page`, pageRequest)
        return response.data
    },

    /**
     * 删除聊天室消息
     */
    async deleteMessage(messageId: string): Promise<ResultDomain<boolean>> {
        const response = await api.delete<boolean>(`${this.baseUrl}/room/message/${messageId}`)
        return response.data
    },

    // ====================== 客服人员管理 ======================

    /**
     * 添加客服人员
     */
    async addCustomerService(customerService: TbCustomerServiceDTO): Promise<ResultDomain<TbCustomerServiceDTO>> {
        const response = await api.post<TbCustomerServiceDTO>(`${this.baseUrl}/customer-service`, customerService)
        return response.data
    },

    /**
     * 更新客服人员
     */
    async updateCustomerService(customerService: TbCustomerServiceDTO): Promise<ResultDomain<TbCustomerServiceDTO>> {
        const response = await api.put<TbCustomerServiceDTO>(`${this.baseUrl}/customer-service`, customerService)
        return response.data
    },

    /**
     * 删除客服人员
     */
    async deleteCustomerService(userId: string): Promise<ResultDomain<boolean>> {
        const response = await api.delete<boolean>(`${this.baseUrl}/customer-service/${userId}`)
        return response.data
    },

    /**
     * 分页查询客服人员
     */
    async getCustomerServicePage(pageRequest: PageRequest<TbCustomerServiceDTO>): Promise<ResultDomain<CustomerServiceVO>> {
        const response = await api.post<CustomerServiceVO>(`${this.baseUrl}/customer-service/page`, pageRequest)
        return response.data
    },

    /**
     * 更新客服在线状态
     */
    async updateCustomerServiceStatus(userId: string, status: string): Promise<ResultDomain<boolean>> {
        const response = await api.post<boolean>(`${this.baseUrl}/customer-service/${userId}/status/${status}`)
        return response.data
    },

    /**
     * 获取可接待客服列表
     */
    async getAvailableCustomerServices(): Promise<ResultDomain<CustomerServiceVO>> {
        const response = await api.get<CustomerServiceVO>(`${this.baseUrl}/customer-service/available`)
        return response.data
    },

    /**
     * 自动分配客服
     */
    async assignCustomerService(roomId: string): Promise<ResultDomain<CustomerServiceVO>> {
        const response = await api.post<CustomerServiceVO>(`${this.baseUrl}/room/${roomId}/assign`)
        return response.data
    },

    // ====================== 词云管理 ======================

    /**
     * 添加词云
     */
    async addWordCloud(wordCloud: TbWordCloudDTO): Promise<ResultDomain<TbWordCloudDTO>> {
        const response = await api.post<TbWordCloudDTO>(`${this.baseUrl}/wordcloud`, wordCloud)
        return response.data
    },

    /**
     * 更新词云
     */
    async updateWordCloud(wordCloud: TbWordCloudDTO): Promise<ResultDomain<TbWordCloudDTO>> {
        const response = await api.put<TbWordCloudDTO>(`${this.baseUrl}/wordcloud`, wordCloud)
        return response.data
    },

    /**
     * 查询词云列表
     */
    async getWordCloudList(filter: TbWordCloudDTO): Promise<ResultDomain<TbWordCloudDTO>> {
        const response = await api.post<TbWordCloudDTO>(`${this.baseUrl}/wordcloud/list`, filter)
        return response.data
    },

    /**
     * 分页查询词云
     */
    async getWordCloudPage(pageRequest: PageRequest<TbWordCloudDTO>): Promise<ResultDomain<TbWordCloudDTO>> {
        const response = await api.post<TbWordCloudDTO>(`${this.baseUrl}/wordcloud/page`, pageRequest)
        return response.data
    },

    // ====================== 视频会议管理（Jitsi Meet） ======================

    /**
     * 创建视频会议
     */
    async createVideoMeeting(meeting: TbVideoMeetingDTO): Promise<ResultDomain<VideoMeetingVO>> {
        const response = await api.post<VideoMeetingVO>(`${this.baseUrl}/meeting/create`, meeting)
        return response.data
    },

    /**
     * 获取会议信息
     */
    async getVideoMeetingInfo(meetingId: string): Promise<ResultDomain<VideoMeetingVO>> {
        const response = await api.get<VideoMeetingVO>(`${this.baseUrl}/meeting/${meetingId}`)
        return response.data
    },

    /**
     * 获取聊天室活跃会议
     */
    async getActiveMeeting(roomId: string): Promise<ResultDomain<VideoMeetingVO>> {
        const response = await api.get<VideoMeetingVO>(`${this.baseUrl}/meeting/room/${roomId}/active`)
        return response.data
    },

    /**
     * 加入会议（生成用户专属JWT）
     */
    async joinVideoMeeting(meetingId: string): Promise<ResultDomain<VideoMeetingVO>> {
        const response = await api.post<VideoMeetingVO>(`${this.baseUrl}/meeting/${meetingId}/join`)
        return response.data
    },

    /**
     * 开始会议
     */
    async startVideoMeeting(meetingId: string): Promise<ResultDomain<boolean>> {
        const response = await api.post<boolean>(`${this.baseUrl}/meeting/${meetingId}/start`)
        return response.data
    },

    /**
     * 结束会议
     */
    async endVideoMeeting(meetingId: string): Promise<ResultDomain<VideoMeetingVO>> {
        const response = await api.post<VideoMeetingVO>(`${this.baseUrl}/meeting/${meetingId}/end`)
        return response.data
    },

    // ====================== 聊天室评分管理 ======================

    /**
     * 提交聊天室服务评分
     * @param roomId 聊天室ID
     * @param commentLevel 评分（1-5星）
     */
    async submitComment(roomId: string, commentLevel: number): Promise<ResultDomain<boolean>> {
        const response = await api.post<boolean>(`/urban-lifeline/workcase/chat/room/${roomId}/comment`, null, {
            params: { commentLevel }
        })
        return response.data
    }
}
