const app = getApp();
import {
    ApiModel
} from "../../utils/api";
const _Http = new ApiModel();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        iosX: false,
        sendText: "", //输入框内容
        headerTitle: "对话框",
        socketMsgQueue: [],
        lineCount: 1, //输入框行数
        toView: 'item0',
        keyboardHeight: 0, //键盘高度
        functionToChoose: "", //功能选项
        memePopup: false, //表情弹出
        pageNumber: 1,
        pageTotal: 1,
        triggered: false, //下拉状态
        unreadCount: 0, //对方发送未读信息
        joinHands: false, //是否显示合作按钮
        ownerid: 0, //供需id
        fimdialogtype: '', //对话框类型
        fimuserid: 0, //创建者id
        timsubjectid: 0, //话题id
        timdialogid: 0, //对话框id
        gambitList: [], //话题列表
        sendfrom: [],
        isEndGambit: true, //是否结束话题，用于点击编辑不结束话题
        fdatastatus: 0, // 0 1 2对接中
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //app.initSocket(); 链接websocket 用于测试
        const that = this;
        this.setData({
            timdialogid: options.id,
            userid: wx.getStorageSync('userData').userid
        });
        if (options.fdatastatus) {
            this.setData({
                fdatastatus: options.fdatastatus
            })
        }
        //判断是否存在安全距离
        let iosX = (getApp().globalData.safeAreaBottom == 0) ? false : true;
        this.setData({
            iosX
        })
        //获取表情包
        this.getMeme()
    },
    toCreate() {
        this.setData({
            isEndGambit: false
        })
        wx.navigateTo({
            url: '/pages/chatRoom/create?timdialogid=' + this.data.timdialogid,
        })
    },
    /* 创建话题,回复话题 */
    createGambit() {
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "system.im.imdialog.imdialog",
            "method": "createSubject",
            "content": {
                "timdialogid": this.data.timdialogid,
                "timsubjectid": this.data.timsubjectid,
                "fcontent": ""
            }
        }).then(res => {
            if (res.msg != '成功') return wx.showToast({
                title: res.data,
                icon: "none"
            })
            let gambitList = this.data.gambitList;
            gambitList.push(res.data[0]);
            this.setData({
                timsubjectid: res.data[0].timsubjectid,
                gambitList
            })
            app.globalData.SocketTask.send({
                data: JSON.stringify({
                    "classname": "message.message",
                    "method": "sendDataMessage",
                    "content": {
                        "timdialogid": this.data.timdialogid,
                        "ownertable": "timsubject",
                        "ownerid": this.data.timsubjectid,
                        "ftype": "话题",
                    }
                }),
                success(res) {
                    console.log("sddf", res)
                }
            })
        })
    },
    /* 结束话题 */
    endGambit(isGetList) {
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "system.im.imdialog.imdialog",
            "method": "closeSubject",
            "content": {
                "timsubjectid": this.data.timsubjectid,
                "timdialogid": this.data.timdialogid
            }
        }).then(res => {
            if (res.msg != '成功') return wx.showToast({
                title: res.data,
                icon: "none"
            });
            this.setData({
                timsubjectid: 0
            })
            if (isGetList) this.query_imdialogMessage();
        })
    },
    /* 发送信息 */
    sendMsg(type, data) {
        const content = this.data.sendText.trim(),
            that = this;
        if (this.data.fimdialogtype == '话题') {
            if (type === 'file') {
                console.log("附件类型", data)
                let list = this.data.gambitList[this.data.gambitList.length - 1].imsubjectcontent;
                _Http.basic({
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "changeFilesData",
                    "content": {
                        "files": [{
                            "tattachmentid": data[0].tattachmentid,
                            "fdocument": data[0].fdocument,
                            "ownertable": "timsubjectcontent",
                            "ownerid": list[list.length - 1].timsubjectcontenid,
                            "ftype": data[0].ftype
                        }]
                    }
                }).then(async s => {
                    console.log("附件位置修改", s)
                    let id = [{
                            message: {
                                data: {
                                    ownerid: this.data.timsubjectid
                                }
                            }
                        }],
                        item = await this.querySubject(id)
                    list = this.data.gambitList;
                    item[0].closedate = item[0].createdate;
                    item[0].sendfrom = this.data.sendfrom;
                    list[list.length - 1] = item[0];
                    this.setData({
                        gambitList: list
                    })
                    setTimeout(() => {
                        this.setData({
                            toView: 'bottom'
                        })
                    }, 300)
                })
            } else {
                if (content == '') return;
                _Http.basic({
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.im.imdialog.imdialog",
                    "method": "createSubject",
                    "content": {
                        "timdialogid": this.data.timdialogid,
                        "timsubjectid": this.data.timsubjectid,
                        "fcontent": content
                    }
                }, false).then(res => {
                    let list = this.data.gambitList,
                        time = res.data[0].createdate.split(".");
                    res.data[0].closedate = time[0];
                    res.data[0].sendfrom = this.data.sendfrom;
                    list[list.length - 1] = res.data[0];
                    this.setData({
                        gambitList: list,
                        sendText: ''
                    })
                    setTimeout(() => {
                        this.setData({
                            toView: 'bottom'
                        })
                    }, 300)
                })
            }
        } else {
            if (type === 'file') {
                app.globalData.SocketTask.send({
                    data: JSON.stringify({
                        "classname": "message.message",
                        "method": "sendFileMessage",
                        "content": {
                            "timdialogid": this.data.timdialogid,
                            "tattachmentid": data[0].tattachmentid
                        }
                    }),
                    success(res) {
                        console.log(res)
                    }
                })
            } else {
            console.log(type, data)
                if (content == '') return;
                app.globalData.SocketTask.send({
                    data: JSON.stringify({
                        "classname": "message.message",
                        "method": "sendTextMessage",
                        "content": {
                            "timdialogid": that.data.timdialogid,
                            "fmessage": content
                        }
                    }),
                    success(res) {
                        console.log(56465,res)
                        that.setData({
                            sendText: ''
                        })
                    }
                })
            }
        }
    },
    //历史信息查询
    query_imdialogMessage() {
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "system.im.imdialog.imdialog",
            "method": "query_imdialogMessage",
            "content": {
                "pageNumber": this.data.pageNumber,
                "pageSize": 20,
                "timdialogid": this.data.timdialogid
            }
        }, false).then(async res => {
            console.log("聊天记录", res)
            if (res.msg != '成功') return wx.showToast({
                title: res.data,
                icon: "none"
            });
            let list = res.data;
            list = list.reverse();
            if (res.pageNumber != 1) {
                if (this.data.fimdialogtype != '话题') {
                    list = list.concat(this.data.socketMsgQueue);
                    this.setData({
                        socketMsgQueue: list,
                        toView: `item${res.data.length - 1}`,
                        triggered: false
                    })
                } else {
                    let gambitList = await this.querySubject(list);
                    list = gambitList.concat(this.data.gambitList);
                    this.setData({
                        gambitList: list,
                        toView: `item${res.data.length - 1}`,
                        triggered: false
                    })
                }
            } else {
                if (this.data.fimdialogtype != '话题') {
                    this.setData({
                        socketMsgQueue: list,
                        toView: `item${res.data.length - 1}`,
                        pageTotal: res.pageTotal
                    })
                } else {
                    let gambitList = await this.querySubject(list);
                    this.setData({
                        gambitList,
                        toView: `item${res.data.length - 1}`,
                        pageTotal: res.pageTotal
                    })
                }
                setTimeout(() => {
                    this.setData({
                        toView: 'bottom'
                    })
                }, 500)
            }
        })
    },
    /* 根据话题ID查询详情 */
    async querySubject(array) {
        let list = [];
        for (let index = 0; index < array.length; index++) {
            await _Http.basic({
                "accesstoken": wx.getStorageSync('userData').token,
                "classname": "system.im.imdialog.imdialog",
                "method": "querySubject",
                "content": {
                    "timsubjectid": array[index].message.data.ownerid
                }
            }, false).then(res => {
                if (res.data.length != 0 && res.data[0].imsubjectcontent.length != 0) {
                    res.data[0].sendfrom = array[index].message.sendfrom;
                    res.data[0].timdialogid = array[index].message.timdialogid;
                    if (res.data[0].closedate != null) {
                        let time = res.data[0].closedate.split('.');
                        res.data[0].closedate = time[0];
                        res.data[0].finish = true;
                        list.push(res.data[0]);
                    } else {
                        let time = res.data[0].createdate.split('.');
                        res.data[0].createdate = time[0];
                        res.data[0].finish = false;
                        list.push(res.data[0]);
                    }
                }
            })
        }
        return list;
    },
    /* 加载分页 */
    scrolltoupper() {
        if (this.data.pageNumber < this.data.pageTotal) {
            this.setData({
                pageNumber: this.data.pageNumber + 1,
                triggered: true
            })
            this.query_imdialogMessage();
        } else {
            this.setData({
                triggered: true
            })
        }
    },
    //键盘弹出高度
    keyboardheightchange(e) {
        let {
            height
        } = e.detail;
        if (this.data.iosX && height > 150) height = height - 17;
        this.setData({
            keyboardHeight: height
        })
    },
    /* 确认合作 */
    confirmTheCooperation() {
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定达成合作',
            success: function (res) {
                if (res.confirm) {
                    _Http.basic({
                        "accesstoken": wx.getStorageSync('userData').token,
                        "classname": "customer.supplyanddemand.supplyanddemand",
                        "method": "updatesupplyanddemandstatus",
                        "content": {
                            "tsupplyanddemandid": that.data.ownerid,
                            "fstatus": "已解决",
                            "tenterprise_userid": that.data.fimuserid,
                            "timdialogid": that.data.timdialogid
                        }
                    }).then(res => {
                        let text = ' 恭喜达成合作';
                        if (res.msg != '成功') text = res.data;
                        wx.showToast({
                            title: text,
                            icon: "none"
                        })
                        if (res.msg == '成功') that.setData({
                            fdatastatus: 1
                        })
                    })
                }
            }
        })
    },
    /* 拒绝合作 */
    refuseToCooperate() {
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定拒绝',
            success: function (res) {
                if (res.confirm) {
                    _Http.basic({
                        "accesstoken": wx.getStorageSync('userData').token,
                        "classname": "customer.supplyanddemand.supplyanddemand",
                        "method": "updatesupplyanddemandstatus",
                        "content": {
                            "tsupplyanddemandid": that.data.ownerid,
                            "fstatus": "待对接",
                            "timdialogid": that.data.timdialogid
                        }
                    }).then(res => {
                        let text = ' 拒绝成功';
                        if (res.msg != '成功') text = res.data;
                        wx.showToast({
                            title: text,
                            icon: "none"
                        })
                        if (res.msg == '成功') that.setData({
                            fdatastatus: 0
                        })
                    })
                }
            }
        })
    },
    /* 输入框数据绑定 */
    sendInput(e) {
        this.setData({
            sendText: e.detail.value
        })
    },
    /* 发送表情 */
    sendMeme(e) {
        if (this.data.fimdialogtype == '话题') return wx.showToast({
            title: '当前状态不可发送',
            icon: "none"
        })
        const {
            item
        } = e.currentTarget.dataset;
        let data = [];
        data.push(item);
        this.sendMsg('file', data)
    },
    //功能选择
    selectionFunction(e) {
        const {
            name
        } = e.target.dataset,
            that = this;
        if (name == undefined || name == "") return;
        if (name == '表情') {
            let keyboardHeight = (this.data.iosX == true) ? 220 : 200;
            this.setData({
                keyboardHeight,
                memePopup: true
            })
            that.toBotton()
            let time1 = setInterval(() => {
                this.setData({
                    keyboardHeight
                })
                if (this.data.keyboardHeight == keyboardHeight && this.data.memePopup) clearInterval(time1);
            }, 100);
        } else if (name == '图片') {
            this.endMemePopup()
            wx.chooseMedia({
                count: 1,
                mediaType: ['image'],
                sourceType: ['album', 'camera'],
                maxDuration: 30,
                camera: 'back',
                success(res) {
                    let data = {
                        file: res.tempFiles[0].tempFilePath
                    };
                    that.afterRead(data)
                }
            })
        } else if (name == '历史') {
            wx.navigateTo({
                url: './history?id=' + that.data.timdialogid + '&type=' + that.data.fimdialogtype,
            })
        }
    },
    textareaFocus() {
        this.setData({
            memePopup: false, //表情弹出
        })
        this.toBotton()
    },
    //关闭表情
    endMemePopup(e) {
        this.setData({
            keyboardHeight: 0, //键盘高度
            memePopup: false, //表情弹出
        })
    },
    /* 文本域行数变化 */
    /*     linechange(e) {
            console.log(e)
            const {
                lineCount
            } = e.detail;
            if (lineCount == this.data.lineCount) return;
            this.setData({
                lineCount
            })
        }, */
    //获取表情包
    getMeme() {
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "system.system.docManage",
            "method": "queryDoc",
            "content": {
                "getdatafromdbanyway": true,
                "ownertable": "system",
                "ownerid": 0
            }
        }, false).then(res => {
            if (res.msg != '成功') return setTimeout(() => {
                this.getMeme();
            }, 3000);
            this.setData({
                memeList: res.data
            })
        })
    },
    afterRead({
        file
    }) {
        if (this.data.fimdialogtype == '话题') {
            if (this.data.timsubjectid == 0 || this.data.userid != this.data.fimuserid) {
                return wx.showToast({
                    title: '当前状态不可发送',
                    icon: "none"
                })
            } else {
                if (this.data.gambitList[this.data.gambitList.length - 1].imsubjectcontent.length < 1) return wx.showToast({
                    title: '当前状态不可发送',
                    icon: "none"
                })
            }
        }
        var that = this
        var index = file.lastIndexOf(".");
        var ext = file.substr(index + 1);
        var timestamp = Date.parse(new Date());
        wx.getFileSystemManager().readFile({
            filePath: file,
            // encoding:'utf-8',
            success: result => {
                //返回临时文件路径
                const fileData = result.data
                wx.request({
                    url: 'https://www.buwanjia.com/bwj/rest/webclientrest/', //仅为示例，并非真实的接口地址
                    data: {
                        "accesstoken": wx.getStorageSync('userData').token,
                        "classname": "system.system.docManage",
                        "method": "getFileName",
                        "content": {
                            "filename": 'wx' + timestamp,
                            "filetype": ext,
                            "ownertable": "timdialog",
                            "ownerid": that.data.timdialogid,
                            "ftype": "default",
                            "HttpMethod": 'put'
                        }
                    },
                    method: 'post',
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success(res) {
                        console.log(res)
                        that.uploadFile(res, fileData)
                    }
                })
            },
            fail: console.error
        })
    },
    uploadFile(res, data) {
        var that = this
        wx.request({
            url: res.data.data.obsuploadurl,
            method: "PUT",
            data: data,
            header: {
                'content-type': 'application/octet-stream' // 默认值
            },
            success() {
                wx.request({
                    url: 'https://www.buwanjia.com/bwj/rest/webclientrest/', //仅为示例，并非真实的接口地址
                    data: {
                        "accesstoken": wx.getStorageSync('userData').token,
                        "classname": "system.system.docManage",
                        "method": "uploadSuccess",
                        "content": {
                            "obsfilename": res.data.data.obsfilename
                        }
                    },
                    method: 'post',
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success(res) {
                        let file = res.data.data;
                        that.sendMsg('file', file)
                    }
                })
            }
        })
    },
    toBotton() {
        this.setData({
            toView: 'bottom'
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this;
        app.globalData.callback = function (res) {
            console.log(654654)
            //res  接收websocket onMessage事件返回的数据
            let objs = JSON.parse(res.data),
                unreadCount = that.data.unreadCount; /* triggered */
            console.log('接收', objs)
            if (objs.message) {
                if (objs.message.timdialogid != that.data.timdialogid) return;
            }
            that.data.socketMsgQueue.push(objs);
            /* 接受信息 */
            that.setData({
                socketMsgQueue: that.data.socketMsgQueue
            })
            if (objs.message.sendfrom) that.setData({
                sendfrom: objs.message.sendfrom
            })
            that.toBotton()
            /* if (wx.getStorageSync('userData').userid == objs.message.sendfrom.userid) {
            } else {
                that.setData({
                    socketMsgQueue: that.data.socketMsgQueue
                })
            } */
            /* ,
                toView: `item${that.data.socketMsgQueue.length - 1}` */
        };
        //详情
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "system.im.imdialog.imdialog",
            "method": "query_imdialogMain",
            "content": {
                "getdatafromdbanyway": true,
                "timdialogid": this.data.timdialogid
            }
        }).then(res => {
            console.log("详情", res)
            if (res.msg != '成功') return wx.showToast({
                title: res.data,
                icon: "none"
            });
            let title = res.data[0].fimdialogname.split('-'),
                headerTitle = (title[0] == res.data[0].fname) ? title[1] : title[0],
                joinHands = false;
            //供需类型对话框，判断对话框ID是否为当前账号，当前账号更改供需状态，非当前账号显示合作按钮
            if (res.data[0].fimdialogtype == '供需') {
                if (res.data[0].fimuserid == this.data.userid) {
                    _Http.basic({
                        "accesstoken": wx.getStorageSync('userData').token,
                        "classname": "customer.supplyanddemand.supplyanddemand",
                        "method": "updatesupplyanddemandstatus",
                        "content": {
                            "tsupplyanddemandid": res.data[0].ownerid,
                            "fstatus": "对接中",
                            "timdialogid": res.data[0].timdialogid
                        }
                    }, false).then(res => {
                        console.log("对接中", res)
                    })
                } else {
                    joinHands = true
                }
            }
            //返回数据
            this.setData({
                headerTitle,
                ownerid: res.data[0].ownerid,
                joinHands,
                fimuserid: res.data[0].fimuserid,
                fimdialogtype: res.data[0].fimdialogtype,
                timdialogid:res.data[0].timdialogid
            })
            //判断是否为话题类型对话框
            if (res.data[0].fimdialogtype == '话题') {
                _Http.basic({
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.im.imdialog.imdialog",
                    "method": "queryDialogUncloseSubject",
                    "content": {
                        "timdialogid": res.data[0].timdialogid
                    }
                }, false).then(s => {
                    if (s.msg != '成功') return wx.showToast({
                        title: res.data,
                        icon: "none"
                    });
                    if (s.data != '成功') {
                        this.setData({
                            timsubjectid: s.data[0].timsubjectid
                        })
                        if (this.data.isEndGambit) this.endGambit(true) //存在未关闭话题，调用关闭话题，并在关闭后重新获取历史话题
                    } else {
                        this.query_imdialogMessage(); //不存在未关闭话题，直接获取历史话题
                    }
                })
            } else {
                this.query_imdialogMessage(); //非话题类型对话框，直接获取历史记录
            }
        });

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        //重置未读信息
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "system.im.imdialog.imdialog",
            "method": "restUnReadMsgCount",
            "content": {
                "timdialogid": this.data.timdialogid
            }
        }).then(res => {
            console.log(res)
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})