// 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 AgentApi from '../../apis/agent'
/**
 * 聊天页面
 */
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.getAgencyDetail(options.toId).then(res => {
            console.log(res)
            this.imOperator = new IMOperator(this, res);
            this.getHistory(options.toId)
            this.UI = new UI(this);
            this.msgManager = new MsgManager(this);
            this.listener = (msg) => {
                console.log(msg, '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.user_id});
    },
    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);
        console.log(item)
        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.user_id;
                    this.msgManager.showMsg({msg: this.imOperator.createNormalChatItem(item)})
                }
            })
        })
    },
    onlyGetHistory (friend_id) {
        return ImApi.getMsgHistory(friend_id)
    },
    getAgencyDetail (agency_id) {
        agency_id = getApp().globalData.userinfo.agency_user_id || agency_id
        const isAgency = getApp().globalData.userinfo.agency_user_id ? true : false
        if (agency_id) {
            return AgentApi.fetchAgentDetail(agency_id).then(res => {
                return {
                    friendHeadUrl: isAgency ? 'data:image/svg+xml;base64,PHN2ZyBpZD0iaW1nX215X2F2YXRhcl9kZWZhdWx0IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2MCIgaGVpZ2h0PSI2MCIgdmlld0JveD0iMCAwIDYwIDYwIj4NCiAgPGRlZnM+DQogICAgPHN0eWxlPg0KICAgICAgLmNscy0xIHsNCiAgICAgICAgZmlsbDogI2Q5ZmZmZjsNCiAgICAgIH0NCg0KICAgICAgLmNscy0yIHsNCiAgICAgICAgZmlsbDogIzczOGM5YjsNCiAgICAgIH0NCg0KICAgICAgLmNscy0zIHsNCiAgICAgICAgZmlsbDogI2Y4ZjFlMDsNCiAgICAgIH0NCg0KICAgICAgLmNscy00IHsNCiAgICAgICAgZmlsbDogIzMwMmIyYjsNCiAgICAgIH0NCg0KICAgICAgLmNscy01IHsNCiAgICAgICAgZmlsbDogI2U0ZWVlZjsNCiAgICAgIH0NCg0KICAgICAgLmNscy02IHsNCiAgICAgICAgZmlsbDogI2YxZjVmMzsNCiAgICAgIH0NCiAgICA8L3N0eWxlPg0KICA8L2RlZnM+DQogIDxwYXRoIGlkPSLot6/lvoRfMzcwIiBkYXRhLW5hbWU9Iui3r+W+hCAzNzAiIGNsYXNzPSJjbHMtMSIgZD0iTTMwLjcyNiwzMC40N20tMzAsMGEzMCwzMCwwLDEsMCwzMC0zMCwzMCwzMCwwLDAsMC0zMCwzMFoiIHRy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