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: true,
        upload_picture_list: [],
        imagesListp: [],
        imagestr: [],
        id: 0,
        accesstoken: '',
        typeid: 1,
        title: '怼社区',
        page: 1, //页面数,
        pagecount: 0,
        wordstextname: '',
        classid:1
    },

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


      console.log("options===================");
        console.log(options);

        Apps.islogin();
         this.setData({
            typeid: options.typeid,
            classid:options.typeid
        })
        this.getacctoken();
    },
    bindTextAreaBlur: function (e) {
        console.log(e.detail.value);
        this.setData({
            wordstextname: e.detail.value
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

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

       
    },
    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 () { } //接口调用结束的回调函数  
            })
        }        
    },

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

    },

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

    },

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

    },

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

    },

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

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

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

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

        let content = this.data.wordstextname;
        console.log(content)
        if (content == '') {
            wx.showToast({
                title: '留言内容为空,请填写内容',
                icon: 'none',
                duration: 1500
            })
            return false;
        }
        console.log(this.data.imagestr);
        // this.wordsadd(content,this.data.imagestr);
        this.getmsgcheck(content, this.data.accesstoken);
        wx.setStorageSync('jmparm', this.data.typeid);
        wx.navigateTo({
          url: '/pages/indexclasssubwork/indexclasssubwork',
        })
       
    },
    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 + '/indexclasslistsubwork/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);
            }
        })

    },
    // 删除图片
    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
        })
    },
    wordsadd: function (content, imagestr) {

        const that = this;
        let url = Apps.globalData.baseUrl + '/indexclasslistsubwork/wordsxqadd';
        var param = {
            content: content,
            imagestr: imagestr,
            userid: wx.getStorageSync('wxuserid') == '' ? 3 : wx.getStorageSync('wxuserid'),
            wordstype_ids: this.data.typeid,
            indexclasslist_id: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.data.typeid);
                wx.redirectTo({
                  url: '/pages/indexclasssubwork/indexclasssubwork?id='+that.data.typeid,
                })
                that.setData({
                    wordstextname: '',
                    imagestr: []
                })

            }

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    }
})