const Apps = getApp();
const api = require('../../config/api.js');
const util = require('../../config/util.js');
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: 0,
        title: '动态修改',
        imagecount: 4,
        indeximagecount: 4,
        baseurl: Apps.globalData.baseimgurl,
        indexlist: [],
        replylist: [],
        wordsid: 0,
        wordstextname: '',
        title: '',
        content: '',
        images: '',
        upload_picture_list: [],
        imagesListp: [],
        imagestr: [],
        accesstoken: '',
        scrollTop: 0,
        ispic: 0,
        jztype:1
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // console.log(options);
        this.setData({
            id: options.id,
            jztype:options.jztype
        });       
        if(options.jztype==2){
            this.pageScrollToBottom();
        }
    },

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

        this.getwordsinfo(this.data.id);
        this.getwordsreply();
    },

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

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

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

    },

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

    },

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

    },
    deleteword:function(par){
        //删除留言
        const that = this;
        let url = Apps.globalData.baseUrl + '/wordslist/deleteword';
        var param = {
            wordid: par
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);

            this.getwordsinfo(that.data.id);
            this.getwordsreply();

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    deletewordreply:function(par){
        //删除留言
        const that = this;
        let url = Apps.globalData.baseUrl + '/indexclasslist/deletewordreply';
        var param = {
            wordid: par
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);

            this.getwordsinfo(that.data.id);
            this.getwordsreply();

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    getwordsinfo: function (e) {
        const that = this;
        let url = Apps.globalData.baseUrl + '/indexclasslist/getsinglewords';
        var param = {
            id: e,
            user_id:wx.getStorageSync('wxuserid')
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);

            that.setData({
                indexlist: res.data,
                wordsid: res.data.id
            });

        }).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 + '/indexclasslist/wordsclickcount';
        var param = {
            words_id: e1,
            user_id: e2,
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {
          
            this.getwordsinfo(this.data.id);
            this.getwordsreply();

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

        const that = this;
        let url = Apps.globalData.baseUrl + '/indexclasslist/wordsreply';
        var param = {
            wordsid: that.data.id,
            user_id:wx.getStorageSync('wxuserid')
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {
           
            that.setData({
                replylist: res.data
            });

        }).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) {
                    
                    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++) {

                        // that.getpicchekc(that.data.imagesListp[i]);

                        // if (that.data.ispic == 1) {

                            wx.uploadFile({
                                url: Apps.globalData.baseUrl + '/indexclasslist/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);
            }
        })

    },
    isjumpblack:function(){
        console.log(wx.getStorageSync('userisblack'));
        if(wx.getStorageSync('userisblack')>=2){

            wx.showToast({
                title: "您已被禁言,请联系管理员",//提示文字
                duration: 5000,//显示时长
                mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
                icon: 'none', //图标，支持"success"、"loading"  
                success: function () {
                   
                 },//接口调用成功
                fail: function () { },  //接口调用失败的回调函数  
                complete: function () { } //接口调用结束的回调函数  
            })
        }        
    },
    formSubmit: function (e) {

        Apps.islogin();       
        this.getacctoken();

        if(wx.getStorageSync('userisblack')>=2){
            this.isjumpblack();
            return;
        }

        this.setData({
                wordstextname:e.detail.value.wordsname
        })
        // let content = this.data.wordstextname;
        let content=e.detail.value.wordsname;
        if (content == '') {
            wx.showToast({
                title: '留言内容为空,请填写内容',
                icon: 'none',
                duration: 1500
            })
            return false;
        }

        this.getmsgcheck(content, this.data.accesstoken);
        // this.pageScrollToBottom();
     
    },
    bindTextAreaBlur: function (e) {
        this.setData({
            wordstextname: e.detail.value
        })
    },
    uploadpicsimage: function (e) {

        const that = this;
        let url = Apps.globalData.baseUrl + '/indexclasslist/uploadpics';
        var param = {
            url: e
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    wordsadd: function (content, imagestr) {

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

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    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();

    },
    deletebtnclick: function (params) {

        //删除主贴，看是否是自己的
        console.log(params);     
        // Toast('删除成功');
        const that = this;
        wx.showModal({
            title: '删除提示',
            content: '您将删除该留言信息',
            cancelText: '退出',
            confirmText: '确认',
            success: function (res) {
                if (res.cancel) {
                    //这个跳转是左边按钮的跳转链接
                    //这里取消操作
                    console.log(res);                   

                } else {
                    let wordid=params.currentTarget.id;
                    that.deleteword(wordid);
                }
            }
        })
     

        
    },
    deletebtnclickly:function(params){
           //删除回复贴，看是否是自己的        
         console.log(params); 
        //  let wordid=params.currentTarget.id;
        //  this.deletewordreply(wordid);
        //  Toast('删除成功');

         const that = this;
         wx.showModal({
             title: '删除提示',
             content: '您将删除该留言信息',
             cancelText: '退出',
             confirmText: '确认',
             success: function (res) {
                 if (res.cancel) {
                     //这个跳转是左边按钮的跳转链接
                     //这里取消操作
                     console.log(res);                   
 
                 } else {
                    let wordid=params.currentTarget.id;
                    that.deletewordreply(wordid);
                 }
             }
         })

    },
    addinccomment: function (params) {
        //增加评论数
        let userid = wx.getStorageSync('wxuserid');
        const that = this;
        let url = Apps.globalData.baseUrl + '/indexclasslist/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);
        });
    },
    // 删除图片
    removeChooseImage(e) {
        let imgs = this.data.imagestr;
        let { index } = e.currentTarget.dataset;
        imgs.splice(index, 1);
        this.setData({
            imagestr: imgs
        })
    },
    // 预览图片
    previewBigImage(e) {
        let that = this;
        let imgs = that.data.imagestr;
        let index = e.currentTarget.dataset.index;
        let arr = [];
        imgs.forEach(function (item, index) {
            arr[index] = that.data.baseurl + item
        });
        wx.previewImage({
            //当前显示图片
            current: arr[index],
            //所有图片
            urls: arr
        })
    },
    preview: function (params) {
        let that = this;
        console.log(params)
        let currentUrl = params.currentTarget.dataset.src;
        let arrindex = params.currentTarget.dataset.id;
        let rearr = that.data.replylist[arrindex].pics;
        console.log(rearr);
        let arr = [];
        rearr.forEach(function (item, index) {
            arr[index] = that.data.baseurl + item
        });
        console.log(arr);
        wx.previewImage({
            current: currentUrl, // 当前显示图片的http链接
            urls: arr // 需要预览的图片http链接列表
        })
    },
    preview2: function (params) {
        let that = this;
        let currentUrl = params.currentTarget.dataset.src;
        let arrindex = params.currentTarget.dataset.id;
        let rearr = that.data.indexlist[arrindex].pics;
        console.log(rearr);
        let arr = [];
        rearr.forEach(function (item, index) {
            arr[index] = that.data.baseurl + item
        });
        wx.previewImage({
            current: currentUrl, // 当前显示图片的http链接
            urls: arr // 需要预览的图片http链接列表
        })
    }, communityinfoclick: function (e) {
        //社区留言信息
        wx.navigateTo({
            url: '/pages/communityinfo/communityinfo?id=' + e.currentTarget.id,
        })
    },
    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);
        });
    },
    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": accesstoken //that.data.accesstoken
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(params, that.data.imagestr);
           
            that.wordsadd(params, that.data.imagestr);

            // 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);
        });
    },
    getpicchekc: function (params) {
        // let url="https://api.weixin.qq.com/wxa/media_check_async?access_token="+wx.getStorageSync('accesstoen');

        let url = Apps.globalData.baseUrl + '/user/checkpic'
        var param = {
            "openid": wx.getStorageSync('wxopenid'),
            "scene": 2,
            "version": 2,
            "media_url": params,
            "media_type": 2,
            "version": 2,
            "access_token": wx.getStorageSync('accesstoen')
        };

        //此处为使用封装的post请求
        util.post(url, param).then((res) => {

            console.log("res===========");
            console.log(res);
            this.setData({
                ispic: 1
            })

        }).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()
    },

})