import Notice from "$utils/class/notice";

import * as AgoraRTM from '../../../sdk/agora-rtm-sdk/agora-rtm-sdk.js';

import config from "./config";

import {AgoraRTMIMStatus} from './const/status';

import {AgoraRTMessage, AgoraRTPcMessage} from './const/channel';
import user from '$config/user';

export {AgoraRTMessage,AgoraRTMIMStatus,AgoraRTPcMessage}

export default class AgoraRTMIM extends Notice {

    socket:any = undefined

    socketChannel:any = undefined

    constructor() {
        super();
        if (this.socket === undefined) {
            this.socket = AgoraRTM.createInstance(config.appKey);
        }
    }

    install(roomId){
        return new Promise((resolve, reject)=>{
            this.setStatus(AgoraRTMIMStatus.loginIng);

            return this.socket.login({
                // token: user.user  && user.user.login_token || '',
                uid: user.uid().toString()
            }).then((data)=>{

                this.setStatus(AgoraRTMIMStatus.joinIng);
                this.socketChannel = this.socket.createChannel(roomId);
                this.installSocketMessage();
                return this.socketChannel.join().then(()=>{
                    this.setStatus(AgoraRTMIMStatus.join);

                    return resolve(data);
                }).catch(()=>{
                    this.setStatus(AgoraRTMIMStatus.joinFail);
                    reject();
                });


            }).catch(()=>{
                this.setStatus(AgoraRTMIMStatus.loginFail);
                reject();
            });
        });
    }

    // 安装消息监听器
    installSocketMessage(){

        [AgoraRTMessage.join,AgoraRTMessage.leave].map((item)=>{
            this.socketChannel.on(item,(data)=> {
                this.triggerListener(item,data);
            })
        });

        // 设置监听
        return this.socketChannel.on(AgoraRTMessage.message,(data)=> {
            let resultData;
            // 解析数据
            try {
                resultData = JSON.parse(data.text);
            } catch (e) {
                resultData = {};
            }

            this.triggerMessage(resultData,data);
        });

    }

    triggerMessage(resultData,data={}){

        if (this.watch[resultData.messageType]) {
            resultData = this.watch[resultData.messageType](resultData);
        }

        // 触发 消息
        this.triggerListener(AgoraRTMessage.message, {
            ...(data || {}),
            data:resultData,
            type: resultData.messageType
        });

        // 触发 消息类型
        this.triggerListener(resultData.messageType,{
            type: resultData.messageType,
            data:resultData
        });
    }

    watch = {
      [AgoraRTMessage.chat]:function(item){

          // 如果存在进场转换消息类型
          if (item.star_img || item.star_play_img || item.star_entry_room) {
              item.messageType = AgoraRTMessage.joinHome;
          }

          return item;

      }
    }

    // 发送消息
    send(data,type=AgoraRTMessage.chat){
        return new Promise((resolve, reject)=>{
            if (this.status === AgoraRTMIMStatus.join) {
                data.messageType = type;
                if (this.sendWatch[type]) {
                    data = this.sendWatch[type](data);
                }
                this.socketChannel && this.socketChannel.sendMessage({
                    text:JSON.stringify(data)
                }).then(resolve).catch(reject);
            } else {
                reject();
            }
        });
    }

    sendWatch = {
        [AgoraRTMessage.joinHome]:function(item){
            item.messageType = AgoraRTMessage.chat;
            return item;
        }
    }

    // 追加用户信息
    addUserInfo(data,entry:boolean=false){

        if (data && user.isLogin()) {
            data.nickName = user.user.nick_name;
            data.user_id = user.user.uid;
            data.headimgurl = user.user.head_pic;
            data.vip_img = user.user.contribution_level_image;
            data.qp_base_image = user.user.qp_base_image;
            data.qp_play_image = user.user.qp_play_image;

            if (entry) {
                data.star_img = user.user.zq_base_image;
                data.star_play_img = user.user.zq_play_image;
                data.star_entry_room = '1';
                data.vip_tx = user.user.zq_play_image;
                data.userInfo = {
                    nick_name: user.user.nick_name,
                    uid: user.user.uid,
                    head_pic: user.user.head_pic,
                    sex: user.user.sex,
                    birthday: user.user.birthday
                };
            }
            data.gold_img = user.user.charm_level_image;
        }

        return data;

    }

    // 追加礼物信息
    addGiftInfo(data,toGiftData){
        if (data) {
            data.e_name = toGiftData.gift.gift_name;
            data.giftNum = toGiftData.number || 1;
            data.giftId = toGiftData.gift.gid;
            data.type = toGiftData.gift.gift_type;
            data.show_gift_img = toGiftData.gift.play_image;
            data.show_gift_pc_img = toGiftData.gift.pcplay_image;
            data.show_img = toGiftData.gift.base_image;
            data.userInfo = toGiftData.userInfo;
            data.gift_price =toGiftData.gift.gift_price

            return  data;
        } else {
            return data;
        }
    }

    // 追加排麦状态用户信息
    addQueueWheat(data,user,status:boolean=true){

        if (data) {
            data.queueWheat = {
                user: {
                    uid:user.uid,
                    sex: user.sex,
                    birthday: user.birthday,
                    head_pic: user.head_pic,
                    nick_name: user.nick_name
                },
                status
            }
            return  data;
        } else {
            return data;
        }

    }

    // 设置当前所处于的状态
    public status:AgoraRTMIMStatus = AgoraRTMIMStatus.none;
    // 设置当前状态
    setStatus(status:AgoraRTMIMStatus){
        if (this.status !== status) {
            this.status = status;
            // 触发status 发生变化
            this.triggerListener(AgoraRTMIMStatus.none,status);
        }
    }

    destroy() {
        super.destroy();
        this.socketChannel && this.socketChannel.leave();
        this.socket && this.socket.logout();
        this.socket = undefined;
        this.socketChannel = undefined;
    }

}
