import { defineStore } from 'pinia';
import consola from 'consola'
import { genTestUserSig } from '/@/utils/generateTestUserSig'
import type { RemoteStream } from "trtc-js-sdk";
interface RtcState {
    socket: Nullable<SocketIOClient.Socket>,
    showDaoGou: boolean,
    sdkAppId: string,
    userId: string,
    roomId: string,
    role: 'leader' | 'customer'
    secretKey: string
    userSig: string
    audioDeviceId: string,
    videoDeviceId: string,
    cameraList: MediaDeviceInfo[],
    microphoneList: MediaDeviceInfo[],
    logs: any[],
    isJoined: boolean,
    isPublished: boolean,
    isShared: boolean,
    remoteStreams: RemoteStream[],
    // invitedRemoteStreams: any[],
    avatar: Nullable<string>,
    nickname: Nullable<string>,
    mode: string,
    chatList: ChatContentType[],
    memberList: UserInfoType[],
    audioMuted: boolean
}

interface DeviceListParams {
    cameraItems: MediaDeviceInfo[],
    microphoneItems: MediaDeviceInfo[],
}

export interface ChatContentType {
    role: RoleType,
    mode: string,
    Nickname: Nullable<string>,
    UserId: string,
    text: string,
}

export interface UserInfoType {
    Avatar: string
    Id: string
    InTime: string
    IsClient: string
    IsMuted: string
    IsWords: string
    JoinTime: string
    Nickname: string
    Role: RoleType
    RoomId: string
    UserId: string
    text?: string
}
export type RoleType = 'leader' | 'customer'
export interface SocketParams {
    userId: string
    roomId: string
    role: RoleType
    avatar: string
    nickname: string
    mode: string
}



export const useRtcStore = defineStore({
    id: 'rtc',
    state: (): RtcState => ({
        socket: null,
        showDaoGou: false,
        sdkAppId: "1400685498",
        nickname: '',
        userId: '',
        roomId: '',
        role: 'customer',
        secretKey: '7500f8938c46c5d3c64621ae7826905eec9723bf218fbcf121242e056a4ee14f',
        userSig: 'eJwtzcsOgjAQBdB-6RaDU2jLI3EhsrHRBdGNK2Po0IyvNAWJxvjvEmA5597c*bLj7hD26FnOohDYYrzJ4LOjhkZ*tejPd7wY9EJwnsV8brXmdnGODMu5AEggExBNSUcPHFQpnkopIJkU34784ApECjBvkB1e8MLJfWyLOAis06Wut4b0tVdL77RVTb35dGXby6o6rVfs9wdhLDRy',
        audioDeviceId: '',
        videoDeviceId: '',
        cameraList: [],
        microphoneList: [],
        logs: [],
        isJoined: false,
        isPublished: false,
        isShared: false,
        remoteStreams: [],
        // invitedRemoteStreams: [],
        avatar: null,
        mode: '',
        chatList: [],
        memberList: [],
        audioMuted: true
    }),
    getters: {
        isLeader(): boolean {
            return this.role === 'leader'
        },
        isMe() {
            return (userId: string) => this.userId === userId
        },
        genUserSig() {
            const { userSig } = genTestUserSig({
                sdkAppId: parseInt(this.sdkAppId, 10),
                userId: this.userId,
                secretKey: this.secretKey,
            });
            return userSig
        },
        isUserInRemoteStream() {
            return (userId: string) => {
                return this.remoteStreams.some(item => item.getUserId() === userId)
            }
        }
    },
    actions: {
        setSocketParams(params: SocketParams): void {
            this.avatar = params.avatar
            this.roomId = params.roomId
            this.userId = params.userId
            this.nickname = params.nickname
            this.role = params.role
            if (!['leader', 'customer'].includes(params.role)) {
                consola.info({
                    message: '角色参数有误',
                    level: 0,
                    tag: 'role'
                })
                this.role = 'customer'

            }
        },
        setAvatar(payload: string) {
            this.avatar = payload
            localStorage.setItem('leaderAvatar', payload || '')
        },
        setSocket(payload: SocketIOClient.Socket) {
            this.socket = payload
        },
        setShowDaoGou(payload: boolean) {
            this.showDaoGou = payload
        },

        setUserId(payload: string) {
            this.userId = payload
        },

        setRoomId(payload: string) {
            this.roomId = payload
        },
        setRole(payload: RoleType) {
            this.role = payload
        },

        setDeviceList(payload: DeviceListParams) {
            this.cameraList = payload.cameraItems
            this.microphoneList = payload.microphoneItems
        },

        setVideoDeviceId(payload: string) {
            this.videoDeviceId = payload
        },

        setAudioDeviceId(payload: string) {
            this.audioDeviceId = payload
        },

        setIsJoined(payload: boolean) {
            this.isJoined = payload
        },
        setIsPublished(payload: boolean) {
            this.isPublished = payload
        },

        addToChatList(content: ChatContentType) {
            this.chatList.push(content)
        },
        setMemberList(members: UserInfoType[]) {
            const memberList = members.reduce(function (prev: UserInfoType[], current: UserInfoType) {
                if (prev.findIndex((ele: UserInfoType) => ele.UserId === current.UserId) === -1) {
                    console.log(current);
                    prev.push(current);
                }
                return prev;
            }, []);
            this.memberList = memberList
        },
        mute() {
            this.audioMuted = true
        },
        unmute() {
            this.audioMuted = false
        },
        pushRemoteStreams(stream: RemoteStream) {
            this.remoteStreams.push(stream)
        },
        removeRemoteStreams(id: string) {
            const existStreamIndex = this.remoteStreams.findIndex(stream => stream.getId() === id)
            if (existStreamIndex > -1) {
                this.remoteStreams.splice(existStreamIndex, 1)
            }
        }
    }

})