// pages/activity/activity.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        images: [],
        images_params:[],
        type_picker_list:[],
        start_date:app.nowDate(),
        start_time:'',
        title:'',
        content:'',
        min_num:'',
        max_num:'',
        date:'',
        time:'',
        address:'',
        address_position:'',
        over_time:'',
        is_showRelease_modal:false,
    },
    //查看我的发布
    goMyRelease() {
        // wx.redirectTo({url:'/pages/order/order-detail/order-detail?id=' + this.data.order_id});
        wx.redirectTo({url:'/pages/meal/detail/detail?id=' + this.data.id})
    },
    close() {
        wx.redirectTo({url:'/pages/meal/detail/detail?id=' + this.data.id})
    },
    //完成按钮
    goBack() {
        // wx.redirectTo({url:'/pages/spell-list/spell-list?current=' + 0})
    },
    //输入标题
    inputTitle(e) {
        this.setData({title:e.detail.value})
    },
    //输入内容
    inputContent(e) {
        this.setData({content:e.detail.value})
    },
    //输入最低人数
    inputMinNum(e) {
        this.setData({min_num:e.detail.value})
    },
    //输入最高人数
    inputMaxNum(e) {
        this.setData({max_num:e.detail.value});
    },
    //输入最高人数失去焦点时
    maxNumBlur() {
        console.log('最低人数-最高人数',+this.data.min_num, +this.data.max_num,this.data.min_num>this.data.max_num,+this.data.min_num>+this.data.max_num);
        if(+this.data.min_num>+this.data.max_num) {
            wx.showToast({title:'最低人数不能高于最高人数',icon:'none'});
            this.setData({max_num:''});
        }
    },
    //输入地点
    inputAddress(e) {
        this.setData({address:e.detail.value})
    },
    //获取地址
    choosePosition() {
        //选择当前地址,经纬度
        const self = this;
        wx.chooseLocation({
            success(res) {
                console.log(res);
                self.setData({address_position: res.address,latng:res.latitude + ',' + res.longitude})
            },
        })
        //打开地图导航
        // wx.getLocation({  //获取当前经纬度
        //     type: 'wgs84', //返回可以用于wx.openLocation的经纬度,官方提示bug: iOS 6.3.30 type 参数不生效,只会返回 wgs84 类型的坐标信息
        //     success: function (res) {
        //         console.log('获取当前经纬度', res);
        //         wx.openLocation({//​使用微信内置地图查看位置。
        //             latitude: res.latitude,//要去的纬度-地址
        //             longitude: res.longitude,//要去的经度-地址
        //             name: "",
        //             address: ""
        //         })
        //     }
        // })
    },
    //获取分类
    getType() {
        let url = '/portal/Send/select';
        const list = [];
        app.post(url, {}, {}).then((res) => {
            console.log('获取分类', res);
            res.data.meals.forEach((item) => {
                list.push(item.name)
            });
            this.setData({type_picker_list: list,type_list: res.data.meals})
        })
    },
    //确定发布
    confirmRelease(e) {
        if(this.data.title === '') {
            wx.showToast({title:'请填写标题',icon:'none'})
        }else if(this.data.content === '') {
            wx.showToast({title:'请填写描述',icon:'none'})
        }else if(this.data.images_params.length === 0) {
            wx.showToast({title:'请上传图片',icon:'none'})
        }else if (this.data.min_num === '') {
            wx.showToast({title:'请填写最低人数',icon:'none'})
        }else if (this.data.max_num === '') {
            wx.showToast({title:'请填写最高人数',icon:'none'})
        }else if(this.data.current_type === undefined) {
            wx.showToast({title:'请选择类别',icon:'none'})
        }else if(this.data.date === '') {
            wx.showToast({title:'请选择日期',icon:'none'})
        }else if(this.data.time === '') {
            wx.showToast({title:'请选择时间',icon:'none'})
        }else if(this.data.address === '') {
            wx.showToast({title:'请填写餐厅',icon:'none'})
        }else if(this.data.address_position === '') {
            wx.showToast({title:'请定位地址',icon:'none'})
        }else if(this.data.over_time === '') {
            wx.showToast({title:'请填写截止时间',icon:'none'})
        }else {
            console.log('e', e,e.detail.formId);
            this.data.type_list.forEach((item,index) => {
                if(this.data.current_type === index) {
                    // console.log('index', index, item.id);
                    this.setData({type_id:item.id})
                }
            });
            const images_params = this.data.images_params.join(',');
            console.log('发布-images_params', images_params);
            let url = '/portal/Send/sendMeals';
            let header = {
                "XX-token": wx.getStorageSync('token')
            };
            let params = {
                token: wx.getStorageSync('token'),
                title: this.data.title,
                content:this.data.content,
                pic: images_params,
                number:this.data.min_num,
                max_number:this.data.max_num,
                select_id: this.data.type_id,//类别
                time: this.data.date + ' ' + this.data.time,
                name: this.data.address,
                address: this.data.address_position,
                latng: this.data.latng,
                over_time:this.data.over_time,//	报名截止时间
                formId: e.detail.formId,
            };
            var list = [];
            app.post(url, params, {}).then((res) => {
                console.log('确定发布', res);
                if(+res.code === 1 && res.message == '发布成功') {
                    this.setData({is_showRelease_modal:true,order_id:+res.data.id,id:+res.data.activeId})
                }else {
                    wx.showToast({title:res.message,icon:'none'})
                }
            })
        }
    },
    //上传图片
    choose(e) { //这里是选取图片的方法
        let that = this;
        wx.chooseImage({
            count: 6, //最多可以选择的图片总数
            sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function(res) {
                // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
                let tempFilePaths = res.tempFilePaths;
                //启动上传等待中...
                wx.showToast({
                    title: '正在上传...',
                    icon: 'loading',
                    mask: true,
                    duration: 10000
                })
                // console.log('tempFilePaths', tempFilePaths);
                let token = wx.getStorageSync('token');
                let uploadImgCount = 0;
                for (let i = 0, h = tempFilePaths.length; i < h; i++) {
                    wx.uploadFile({
                        url: 'http://wmatchrd.com/portal/Index/upload',
                        filePath: tempFilePaths[i],
                        name: 'file',
                        formData: {
                            'imgIndex': i
                        },
                        header: {
                            'content-type': 'application/x-www-form-urlencoded',
                            'XX-Token': token,
                            'XX-Device-Type': 'wxapp',
                        },
                        success: function(res) {
                            uploadImgCount++;
                            let data = JSON.parse(res.data);
                            console.log('data',data);
                            if (+data.code == 1) {
                                wx.hideToast();
                                //服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }
                                let images = that.data.images;
                                let images_params = that.data.images_params;
                                images.push(data.data.preview_url);
                                images_params.push(data.data.filepath);
                                that.setData({
                                    images: images,
                                    images_params:images_params,
                                });
                                console.log('images---images_params',images,images_params)
                                //如果是最后一张,则隐藏等待中
                                // if (uploadImgCount == tempFilePaths.length) {
                                //     wx.hideToast();
                                // }
                            } else {
                                wx.hideToast();
                                wx.showModal({
                                    title: '提示',
                                    content: data.msg,
                                    showCancel: false
                                })
                            }

                        },
                        fail: function(res) {
                            wx.hideToast();
                            wx.showModal({
                                title: '错误提示',
                                content: '上传图片失败',
                                showCancel: false,
                                success: function(res) {}
                            })
                        }
                    });
                }
            }
        });
    },
    // 删除图片
    deleteImg(e) {
        var imgs = this.data.images;
        var images_params = this.data.images_params;
        var index = e.currentTarget.dataset.index;
        imgs.splice(index, 1);
        images_params.splice(index, 1);
        this.setData({
            images: imgs,
            images_params:images_params,
        });
    },

    // 预览图片
    previewImg: function (e) {
        //获取当前图片的下标
        var index = e.currentTarget.dataset.index;
        //所有图片
        var imgs = this.data.images;
        wx.previewImage({
            //当前显示图片
            current: imgs[index],
            //所有图片
            urls: imgs
        })
    },
    //选择分类
    bindTypeChange(e) {
        this.setData({current_type: +e.detail.value})
    },
    //选择时间
    bindTimeChange(e) {
        this.setData({time:e.detail.value,hour:e.detail.value.split(':')[0],minute: e.detail.value.split(':')[1]})
        // console.log('time',e.detail.value,e.detail.value.split(':'),e.detail.value.split(':')[0],e.detail.value.split(':')[1]);
    },
    //选择日期
    bindDateChange(e) {
        this.setData({is_choose_date:true,date:e.detail.value,month:e.detail.value.split('-')[1],day: e.detail.value.split('-')[2]})
        // console.log(e.detail.value,this.data.start_date,);
        if(this.data.is_choose_date && (this.data.date === this.data.start_date[0])) { //如果是当天,开始时间要控制在当前时间以后
            this.setData({start_time:app.nowTime()})
        }else {
            this.setData({start_time:'00:00'})
        }
        // console.log(this.data.start_time);
    },
    //输入截止时间
    inputOverTime(e) {
        this.setData({over_time:e.detail.value});
        if(this.data.over_time.indexOf('.') !== -1) {
            wx.showToast({title:'截止时间为整数',icon:'none'});
            this.setData({over_time:''});
        }else {
            let newTime = new Date().getTime();//当前时间戳
            let end_time = app.preTime(this.data.date + ' ' +this.data.time, this.data.over_time);//截止时间
            let endTime = new Date(end_time).getTime(); //截止时间戳
            // console.log('newTime', 'endTime', 'end_time', newTime, endTime, end_time,this.data.date + ' ' +this.data.time);
            if (endTime - newTime <= 0) {  //不可发布目前时间到截止小时內的订单
                wx.showToast({title:'截止时间无效',icon:'none'});
                this.setData({over_time:''})
            }
        }

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

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getType();
    },

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

    },

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

    },

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

    },

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

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        let self = this;
        if(res.from === 'button') {
            return {
                title: self.data.title, // 默认是小程序的名称(可以写slogan等)
                path: '/pages/meal/detail/detail?id=' + self.data.id, // 默认是当前页面,必须是以‘/’开头的完整路径
                imageUrl: self.data.images[0], //自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径,支持PNG及JPG,不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
                success: function (res) {
                    if (res.errMsg == 'shareAppMessage:ok') {
                    }
                },
                fail: function () {
                    // 转发失败之后的回调
                    if (res.errMsg == 'shareAppMessage:fail cancel') {
                        // 用户取消转发
                    } else if (res.errMsg == 'shareAppMessage:fail') {
                        // 转发失败,其中 detail message 为详细失败信息
                    }
                },
                complete: function () {
                    // 转发结束之后的回调(转发成不成功都会执行)
                }
            }
        }
    },
})