import {dealChatTime} from "../../utils/time";
import ImApi from '../../apis/im'
import { fotmatDate } from '../../utils/date'

export default class IMOperator {
    static VoiceType = 'voice';
    static TextType = 'text';
    static ImageType = 'image';
    static CustomType = 'custom';
    static VrCardType = 'vr'
    constructor(page, opts = {}) {
        this._opts = opts;
        this._latestTImestamp = 0;//最新消息的时间戳
        this._myHeadUrl = this._opts.myHeadUrl;
        this._otherHeadUrl = this._opts.friendHeadUrl;
    }

    getFriendId() {
        return this._opts.friendId;
    }

    onSimulateReceiveMsg(cbOk, toId) {
        this.listener = (msg) => {
            if (!msg) {
                return;
            }
            msg.isMy = msg.fromId === getApp().globalData.userinfo.user_id;
            const item = this.createNormalChatItem(msg);
            this._latestTImestamp = item.timestamp;
            //这里是收到好友消息的回调函数，建议传入的item是 由 createNormalChatItem 方法生成的。
            cbOk && cbOk(item);
        }
        getApp().getIMHandler().setOnReceiveMessageListener({
            listener: this.listener
        });

    }
    removeSimulateReceiveMsg () {
        getApp().getIMHandler().removeOnReceiveMessageListener({
            listener: this.listener
        });
    }
    async onSimulateSendMsg({content}) {
        //这里content即为要发送的数据
        //这里的content是一个对象了，不再是一个JSON格式的字符串。这样可以在发送消息的底层统一处理。
        try {
            content = {
                fromId: content.fromId,
                fromName: getApp().globalData.userinfo.name || getApp().globalData.userinfo.phone,
                toId: content.toId,
                toName: 'xu',
                type: content.type,
                msgType: content.msgType,
                content: content.content
            }
            const {content: contentSendSuccess} = await getApp().getIMHandler().sendMsg({content});
            //这个contentSendSuccess格式一样,也是一个对象
            const msg = this.createNormalChatItem(contentSendSuccess);
            this._latestTImestamp = msg.timestamp;
            return Promise.resolve({msg});
        } catch (e) {
            return Promise.reject(e);
        }
    }

    createChatItemContent({msgType = IMOperator.TextType, content = '', duration, toId, type="TYPE_ONE"} = {}) {
        return {
            content,
            msgType,
            type,
            toId,
            conversationId: 0,//会话id，目前未用到
            fromId: getApp().globalData.userinfo.user_id,
            duration
        };
    }

    createNormalChatItem({type = IMOperator.TextType, content = '', isMy = true, enable,duration, msgType, sendTime=fotmatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')} = {}) {
        if (!content) return;
        const currentTimestamp = Date.now();
        const time = dealChatTime(sendTime, this._latestTImestamp);
        let obj = {
            friendId: this.getFriendId(),//好友id
            isMy,//我发送的消息？
            showTime: time.ifShowTime,//是否显示该次发送时间
            time: time.timeStr,//发送时间 如 09:15,
            timestamp: currentTimestamp,//该条数据的时间戳，一般用于排序
            type,//内容的类型，目前有这几种类型： text/voice/image/custom | 文本/语音/图片/自定义
            content,// 显示的内容，根据不同的类型，在这里填充不同的信息。
            headUrl: isMy ? this._myHeadUrl : this._otherHeadUrl,//显示的头像，自己或好友的。
            sendStatus: 'success',//发送状态，目前有这几种状态：sending/success/failed | 发送中/发送成功/发送失败
            duration: duration || content.duration,//语音时长 单位秒
            isPlaying: false,//语音是否正在播放,
            msgType,
            toId: arguments[0].toId,
            fromId: arguments[0].fromId,
            enable
        };
        if (type !== IMOperator.TextType) {
            obj.saveKey = content;//saveKey是存储文件时的key
        }
        return obj;
    }

    static createCustomChatItem() {
        return {
            timestamp: Date.now(),
            type: IMOperator.CustomType,
            content: '会话已关闭'
        }
    }

}

