// pages/list/list.js
import IMOperator from "./im-operator";
import UI from "./ui";
import MsgManager from "./msg-manager";
import ImApi from './../../apis/im'
import { API_BASE_URL } from './../../config/config'
import UserApi from './../../apis/user'
/**
 * 聊天页面
 */
Page({

    /**
     * 页面的初始数据
     */
    data: {
        textMessage: '',
        chatItems: [],
        latestPlayVoicePath: '',
        chatStatue: 'open',
        extraArr: [{
            picName: 'choose_picture',
            description: '照片'
        }, {
            picName: 'take_photos',
            description: '拍摄'
        },],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // const friend = JSON.parse({});
        this.setData({
            pageHeight: wx.getSystemInfoSync().windowHeight,
            toId: options.toId
        });
        wx.setNavigationBarTitle({
            title: options.toName || '聊天页面'
        })
        
        this.getFriendDetail(options.toId).then(res => {
            this.imOperator = new IMOperator(this, res);
            this.getHistory(options.toId)
            this.UI = new UI(this);
            this.msgManager = new MsgManager(this);
            this.listener = (msg) => {
                if (msg.fromId === options.toId) {
                    this.onlyGetHistory(options.toId)
                    this.msgManager.showMsg({msg})
                }
            }
            this.imOperator.onSimulateReceiveMsg(this.listener);
        })
        
    },
    onHide () {
        
    },
    onReady() {
        this.chatInput = this.selectComponent('#chatInput');
    },
    onSendMessageEvent(e) {
        let content = e.detail.value;
        this.msgManager.sendMsg({type: 'TYPE_ONE', msgType: IMOperator.TextType, content,  toId: this.data.toId, fromId: getApp().globalData.userinfo.viewerId});
    },
    onVoiceRecordEvent(e) {
        const {detail: {recordStatus, duration, tempFilePath, fileSize,}} = e;
        if (recordStatus === 2) {
            this.msgManager.sendMsg({
                msgType: IMOperator.VoiceType,
                content: tempFilePath,
                duration: Math.floor(duration / 1000),
                toId: this.data.toId
            });
        }
        this.msgManager.stopAllVoice();
    },
    /**
     * 点击extra中的item时触发
     * @param e
     */
    onExtraItemClickEvent(e) {
        let chooseIndex = parseInt(e.detail.index);
        if (chooseIndex === 2) {
            this.myFun();
            return;
        }
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'],
            sourceType: chooseIndex === 0 ? ['album'] : ['camera'],
            success: (res) => {
                this.msgManager.sendMsg({msgType: IMOperator.ImageType, content: res.tempFilePaths[0], toId: this.data.toId})
            }
        });
    },
    /**
     * 点击extra按钮时触发
     * @param e
     */
    onExtraClickEvent(e) {
        console.log(e);
    },
    //模拟上传文件，注意这里的cbOk回调函数传入的参数应该是上传文件成功时返回的文件url，这里因为模拟，我直接用的savedFilePath
    simulateUploadFile({savedFilePath, duration, itemIndex}) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
              filePath: savedFilePath,
              name: 'file',
              url: `${API_BASE_URL}/im/upload`,
              header: {
                "Content-Type": "multipart/form-data"
                },
              success: (res) => {
                res = JSON.parse(res.data)
                resolve({url: `${API_BASE_URL}/im/download/${res.data}`});
              },
              fail: (err) => {
                  console.log(err, 'err')
              }
            })
        });
    },

    /**
     * 自定义事件
     */
    myFun() {
        wx.showModal({
            title: '小贴士',
            content: '演示更新会话状态',
            confirmText: '确认',
            showCancel: true,
            success: (res) => {
                if (res.confirm) {
                    this.msgManager.sendMsg({type: IMOperator.CustomType})
                }
            }
        })
    },

    resetInputStatus() {
        this.chatInput.closeExtraView();
    },

    onUnload() {
        this.msgManager.stopAllVoice();
        this.imOperator.removeSimulateReceiveMsg(this.listener)
    },

    async sendMsg({content, itemIndex}) {
        try {
            const {msg} = await this.imOperator.onSimulateSendMsg({content})
            this.UI.updateViewWhenSendSuccess(msg, itemIndex);
            return {msg};
        } catch (e) {
            console.error(e);
            this.UI.updateViewWhenSendFailed(itemIndex);
        }
    },
    /**
     * 重发消息
     * @param e
     */
    resendMsgEvent(e) {
        const itemIndex = parseInt(e.currentTarget.dataset.resendIndex);
        const item = this.data.chatItems[itemIndex];
        this.UI.updateDataWhenStartSending(item, false, false);
        this.msgManager.resend({...item, itemIndex});
    },

    getHistory (friend_id) {
        return ImApi.getMsgHistory(friend_id).then(res => {
            res.data.reverse().forEach(item => {
                if (item.content) {
                    item.isMy = item.fromId === getApp().globalData.userinfo.viewerId;
                    this.msgManager.showMsg({msg: this.imOperator.createNormalChatItem(item)})
                }
            })
        })
    },
    onlyGetHistory (friend_id) {
        return ImApi.getMsgHistory(friend_id)
    },
    getFriendDetail (friend_id) {
        return UserApi.getUserInfoById(friend_id).then(res => {
            return {
                friendHeadUrl: res.data.avatar,
                myHeadUrl: getApp().globalData.userinfo.avatar
            }
        })
    }
});
