const DEFAULT_PAGE = 0;
const Apps = getApp();
const api = require('../../config/api.js');
const util = require('../../config/util.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseurl: Apps.globalData.baseimgurl,
        messagelist: [],
        startPageX: 0,
        currentView: DEFAULT_PAGE,
        imagecount: 4,
        indeximagecount: 4,
        active: 1,
        challengeactive: 1,
        toView: `card_${DEFAULT_PAGE}`,
        list: [],
        replylist: [],
        imageslists: [], //图片预览
        showview: false,
        upload_picture_list: [],
        imagesListp: [],
        imagestr: [],
        id: 1,
        accesstoken: '',
        typeid: wx.getStorageSync('jmparm') == null ? 1 : wx.getStorageSync('jmparm'),
        page: 1, //页面数,
        pagecount: 0

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {


        if (options.length > 0) {
            this.setData({
                active: options.id == '' ? 1 : options.id,
                page: 1,
                typeid: wx.getStorageSync('jmparm')
            })
        }

    },
    displayview: function () {
        wx.navigateTo({
            url: '/pages/createwords/createwords?typeid=' + this.data.typeid,
        })

    }, contentclick: function (params) {

        let id = params.currentTarget.id;
        let xid = params.currentTarget.dataset.xid;

        this.setData({
            wordstextname: '@' + id
        });

        this.addinccomment(xid)
        wx.showToast({
            title: '@成功,请移底部留言',//提示文字
            duration: 2000,//显示时长
            mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
            icon: 'success', //图标，支持"success"、"loading"  
            success: function () { },//接口调用成功
            fail: function () { },  //接口调用失败的回调函数  
            complete: function () { } //接口调用结束的回调函数  
        })

        //  this.pageScrollToBottom();

    }, addinccomment: function (params) {
        //增加评论数
        console.log(params);
        let userid = wx.getStorageSync('wxuserid');
        const that = this;
        let url = Apps.globalData.baseUrl + '/wordslist/addcommentrepycount';
        var param = {
            id: params,
            userid: userid
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {
            console.log(res);
            // this.wrodtypelist(this.data.courseid)

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    // pageScrollToBottom() {
    //   wx.createSelectorQuery().select('#time-mo').boundingClientRect(function (rect) {

    //   //  rect.id      // 节点的ID
    //    rect.dataset // 节点的dataset
    //    rect.left    // 节点的左边界坐标
    //    rect.right   // 节点的右边界坐标
    //    rect.top     // 节点的上边界坐标
    //    rect.bottom  // 节点的下边界坐标
    //    rect.width   // 节点的宽度
    //    rect.height  
    //     console.log(rect.bottom*15)
    //     console.log(rect.bottom)
    //     // 使页面滚动到底部
    //     wx.pageScrollTo({
    //       scrollTop: rect.bottom*15
    //     })
    //   }).exec()
    // },  

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        Apps.islogin();
        this.setData({
            active: wx.getStorageSync('jmparm') == '' ? 1 : wx.getStorageSync('jmparm'),
            typeid: wx.getStorageSync('jmparm') == '' ? 1 : wx.getStorageSync('jmparm')
        })
        //头部消息
        this.msglist();
        //留言类型
        this.wrodtypelist();
        //回复留言列表  
        this.getwords();
    },

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

    },
    getacctoken: function () {
        const that = this;
        let url = Apps.globalData.baseUrl + '/user/acctoken';
        var param = {
            pareid: '1213'
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {

            wx.setStorageSync('accesstoen', res.access_token)
            that.setData({
                accesstoken: res.access_token
            });

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

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

    },

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

    },

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

    },
    touchStart(e) {
        this.startPageX = e.changedTouches[0].pageX;
    },
    touchEnd(e) {

        const moveX = e.changedTouches[0].pageX - this.startPageX;
        const maxPage = this.data.list.length - 1;
        if (Math.abs(moveX) >= 150) {
            if (moveX > 0) {
                this.currentView = this.currentView !== 0 ? this.currentView - 1 : 0;
            } else {
                this.currentView = this.currentView !== maxPage ? this.currentView + 1 : maxPage;
            }
        }
        this.setData({
            toView: `card_${this.currentView}`
        });
    },
    touchecard(e) {

        wx.setStorageSync('jmparm', e.currentTarget.id);
        this.setData({
            active: e.currentTarget.id,
            typeid: e.currentTarget.id
        })
        this.getwords();
    },
    duizhiticlick: function () {
        wx.navigateTo({
            url: '/pages/allpapers/allpapers',
        })
    },
    messagelistclick: function () {
        wx.navigateTo({
            url: '/pages/messagelist/messagelist',
        })
    },
    communityinfoclick: function (e) {

        wx.navigateTo({
            url: '/pages/communityinfo/communityinfo?id=' + e.currentTarget.id,
        })
    },
    communityinfocommentclick: function (e) {

        wx.navigateTo({
            //communityinfocomment
            url: '/pages/communityinfo/communityinfo?id=' + e.currentTarget.id + '&jztype=2',
        })
    },
    messagelistclick: function (e) {
        //资讯列表分类
        wx.navigateTo({
            url: '/pages/messagelist/messagelist?typeid=' + e.currentTarget.id,
        })
    },
    messageclick: function (e) {
        wx.navigateTo({
            url: '/pages/messageencyclopedias/messageencyclopedias?id=' + e.currentTarget.id,
        })
    },
    msglist: function () {

        const that = this;
        let url = Apps.globalData.baseUrl + '/msglist/msgindexlist';
        var param = {
            id: '123456789'
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {
            console.log(res);
            that.setData({
                messagelist: res.data.sort()

            });

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    wrodtypelist: function () {

        const that = this;
        let url = Apps.globalData.baseUrl + '/wordslist/getwordslist';
        var param = {
            id: '123456789'
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {
            that.setData({
                list: res.data,
                active: this.data.active
            });

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    getwordspics: function (id) {
        //得到单个信息图片数
        const that = this;
        let url = Apps.globalData.baseUrl + '/wordslist/getwordssingle';
        var param = {
            id: id
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {

            console.log(res.data.pics);
            that.setData({
                imageslists: res.data.pics,
            });

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    getwords: function () {

        const that = this;
        let url = Apps.globalData.baseUrl + '/wordslist/getwords';
        var param = {
            typeid: that.data.typeid,
            page: that.data.page
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {
            console.log(res);
            let counts = res.data.length;
            that.setData({
                replylist: res.data,
                pagecount: counts == 0 ? 1 : counts
            });

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    wordsclick: function (ee) {

        let e1 = ee.currentTarget.id;
        let e2 = wx.getStorageSync('wxuserid');
        const that = this;
        let url = Apps.globalData.baseUrl + '/wordslist/wordsclickcount';
        var param = {
            words_id: e1,
            user_id: e2,
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {

            //头部消息
            that.msglist();
            //留言类型
            that.wrodtypelist();
            that.getwords();

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    bindTextAreaBlur: function (e) {
        this.setData({
            wordstextname: e.detail.value
        })
    },
    preview: function (params) {
        let that = this;
        let currentUrl = params.currentTarget.dataset.src;
        let arrindex = params.currentTarget.dataset.id;
        let picsid = params.currentTarget.dataset.pics; //单条信息ID

        // that.getwordspics(picsid); //得到单条信息图片       
        console.log(that.data.replylist[picsid]);
        let rearr = that.data.replylist[picsid].pics;
        let arr = [];
        rearr.forEach(function (item, index) {
            arr[index] = that.data.baseurl + item
        });
        console.log('-----');
        console.log(arr);

        wx.previewImage({
            current: currentUrl, // 当前显示图片的http链接
            urls: arr // 需要预览的图片http链接列表
        })
    },
    getmsgcheck: function (params, accesstoken) {
        // $url ='https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' .$accessToken;
        const that = this;
        // let url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token='+wx.getStorageSync('accesstoen');
        let url = Apps.globalData.baseUrl + '/user/checkmsg'
        var param = {
            "openid": wx.getStorageSync('wxopenid'),
            "scene": 2,
            "version": 2,
            "content": params,
            "access_token": wx.getStorageSync('accesstoen')
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {

            console.log(res);
            console.log(res.errcode);
            if (res.errcode == "0") {
                that.wordsadd(params, that.data.imagestr)
            } else {

                wx.showToast({
                    title: '留言内容有敏感词请重新输入',//提示文字
                    duration: 2000,//显示时长
                    mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
                    icon: 'none', //图标，支持"success"、"loading"  
                    success: function () { },//接口调用成功
                    fail: function () { },  //接口调用失败的回调函数  
                    complete: function () { } //接口调用结束的回调函数  
                })
            }

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    uploadpic: function () {
        var that = this;
        let imagesList = [];
        let maxSize = 1024 * 1024;
        let maxLength = 6;
        let flag = true;
        wx.chooseImage({
            count: 9, //最多可以选择的图片总数
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                wx.showToast({
                    title: '正在上传...',
                    icon: 'loading',
                    mask: true,
                    duration: 500
                })
                for (let i = 0; i < res.tempFiles.length; i++) {
                    if (res.tempFiles[i].size > maxSize) {
                        flag = false;
                        console.log(111)
                        wx.showModal({
                            content: '图片太大，不允许上传',
                            showCancel: false,
                            success: function (res) {
                                if (res.confirm) {
                                    console.log('用户点击确定')
                                }
                            }
                        });
                    }
                }
                if (res.tempFiles.length > maxLength) {
                    console.log('222');
                    wx.showModal({
                        content: '最多能上传' + maxLength + '张图片',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                console.log('确定');
                            }
                        }
                    })
                }
                if (flag == true && res.tempFiles.length <= maxLength) {
                    that.setData({
                        imagesListp: res.tempFilePaths
                    })
                    that.data.imagestr = [];
                    var arr = '';
                    for (let i = 0; i < that.data.imagesListp.length; i++) {
                        wx.uploadFile({
                            url: Apps.globalData.baseUrl + '/wordslist/uploadpics',
                            filePath: that.data.imagesListp[i],
                            name: 'file',
                            success: function (res) {
                                //打印
                                console.log("------------响应数据：");
                                console.log(res.data);

                                var message = JSON.parse(res.data);
                                that.data.imagestr.push(message);
                                that.setData({
                                    imagestr: that.data.imagestr
                                });
                            },
                        })
                    }
                }
                console.log(res);
            },
            fail: function (res) {
                console.log(res);
            }
        })

    },
    wordsadd: function (content, imagestr) {

        const that = this;
        let url = Apps.globalData.baseUrl + '/wordslist/wordsxqadd';
        var param = {
            content: content,
            imagestr: imagestr,
            userid: wx.getStorageSync('wxuserid') == '' ? 3 : wx.getStorageSync('wxuserid'),
            wordstype_ids: this.data.typeid
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res.data);
            if (res.data > 0) {
                wx.showToast({
                    title: '留言内容成功',
                    icon: 'none',
                    duration: 1500
                })
                this.getwords();

                that.setData({
                    wordstextname: ''
                })

            }

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    formSubmit: function (e) {

        this.getacctoken();
        let content = this.data.wordstextname;
        console.log(content)
        if (content == '') {
            wx.showToast({
                title: '留言内容为空,请填写内容',
                icon: 'none',
                duration: 1500
            })
            return false;
        }
        this.getmsgcheck(content, this.data.accesstoken);
    },
    // 触底加载
    onReachBottom: function () {

        this.setData({
            page: this.data.page + 1
        })
        let newpage = (this.data.page + 1); //页数触底加1
        console.log(newpage);
        if (newpage * 10 >= this.data.pagecount) {

            wx.showToast({
                title: '触底了,没有可加载的数据了',
                icon: 'none',
                duration: 1500
            })

        } else {
            this.getwords();
        }

    }
})