// pages/center/center.js
var app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        randomName: true,
        showPhone: true,
        gotCode: false,
        restTime: 120,
        timer: '',
        userAvatar: '',
        token: '',
        userInfo: {},
        usercenterUrl: app.usercenterUrl,
        sourcePath: '/route/file/download/true/',
        phone: '',
        code: '',
        isLoading: false
    },
    // 选择头像来源
    changeAvatar: function () {
        var self = this
        wx.showActionSheet({
            itemList: ['从相册中选择', '拍照'],
            success: function (res) {
                if (!res.cancel) {
                    if (res.tapIndex == 0) {
                        self.chooseAvatar('album')
                    } else {
                        self.chooseAvatar('camera')
                    }
                }
            }
        })
    },
    // 选择图片
    chooseAvatar: function (type) {
        var self = this
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: [type],
            success: function (res) {
                var avatar = res.tempFilePaths[0];
                app.restAjax.file(app.restAjax.path('{usercenterUrl}/app/file/uploadimage', [app.usercenterUrl]), avatar, 'image', {
                    headers: {
                        token: self.data.token
                    }
                }, function (code, data) {
                    var id = JSON.parse(data).data
                    self.uploadAvatar(id)
                }, function (code, data) {
                    console.log(data)
                })
                self.setData({
                    userAvatar: avatar
                })
            }
        })
    },
    // 上传
    uploadAvatar: function (avatarId) {
        var self = this
        app.restAjax.put(app.restAjax.path('{usercenterUrl}/app/user/updateuseravatar', [app.usercenterUrl]), {
            avatar: avatarId
        }, {
            headers: {
                token: self.data.token
            }
        }, function (code, data) {
            wx.setStorageSync('token', data.data);
            self.getUserInfo()
        }, function (code, data) {
            console.log(data)
        })
    },
    // 获取token
    getToken: function () {
        var self = this
        wx.getStorage({
            key: 'token',
            success: function (res) {
                self.setData({
                    token: res.data
                })
                self.getUserInfo()
            },
        })
    },
    //收货地址
    toAddressManage() {
        wx.navigateTo({
            url: '/subpages/goodsaddress/goodsaddress',
        })
    },
    //我的订单
    toShopOrder() {
        wx.navigateTo({
            url: '/subpages/goodsorder/goodsorder',
        })
    },
    //购物车
    toShopCar() {
        wx.navigateTo({
            url: '/subpages/goodscar/goodscar',
        })
    },
    /**
     * 跳转到我的活动
     */
    toMyJoinActivity() {
        wx.navigateTo({
            url: '/pages/myActivity/myActivity',
        })
    },
    /**
     * 跳转到我的预订列表
     */
    toMyOrder: function () {
        wx.navigateTo({
            url: '../order/order',
        })
    },
    /**
     * 跳转到我的志愿团队页面
     */
    toMyTeam: function () {
        wx.navigateTo({
            url: '../myVolunteerTeam/myVolunteerTeam',
        })
    },
    /**
     * 跳转到我的志愿活动页面
     */
    toMyVolunteerActivity: function () {
        wx.navigateTo({
            url: '../myVolunteerActivity/myVolunteerActivity',
        })
    },
    /**
     * 跳转到我发布的朋友圈页面
     */
    toMyFirend: function () {
        wx.navigateTo({
            url: '../myFriendCircle/myFriendCircle',
        })
    },
    /**
     * 跳转到我预定的场馆页面
     */
    toMyOrder: function () {
        wx.navigateTo({
            url: '../order/order',
        })
    },
    // 获取输入的手机号
    phoneNum: function (res) {
        this.setData({
            phone: res.detail.value
        })
    },
    // 校验手机号
    testPhone: function () {
        var self = this
        if (self.data.phone) {
            if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(self.data.phone)) {
                wx.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none',
                    duration: 1500
                })
            } else {
                self.getCode()
            }
        } else {
            wx.showToast({
                title: '手机号不能为空',
                icon: 'none',
                duration: 1500
            })
        }
    },
    // 提交绑定手机
    submitPhone: function () {
        var self = this;
        self.setData({
            isConfirm: true
        })
        app.restAjax.put(app.restAjax.path('{usercenterUrl}/app/user/updateminiappdefaultusername', [app.usercenterUrl]), {
            phone: self.data.phone
        }, {
            headers: {
                token: self.data.token
            }
        }, function (code, data) {
            wx.setStorageSync('token', data.data);
            wx.setStorageSync('isRandomUsername', 0)
            clearInterval(self.data.timer)
            self.setData({
                showPhone: false
            })
            wx.showTabBar();
            self.getUserInfo()
        }, function (code, data) {
            app.dialog.msg(data.msg);
            self.setData({
                isConfirm: false
            })
        })
    },
    // // 验证码
    // inputCode: function (e) {
    //   this.setData({
    //     code: e.detail.value
    //   })
    // },
    getPhoneNumber: function (e) {
        var self = this
        self.setData({
            isLoading: true
        })
        console.log(e)
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
            var info = {
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv
            }
            // app.dialog.loading('正在加载');
            app.restAjax.put(app.restAjax.path('{usercenterUrl}/app/miniapp/update-phone', [app.usercenterUrl]), info, {
                headers: {
                    token: self.data.token
                }
            }, function (code, data) {
                // wx.hideLoading();
                self.setData({
                    isLoading: false
                })
                wx.setStorageSync('token', data.data);
                wx.setStorageSync('isRandomUsername', '0');
                self.setData({
                    randomName: false,
                    token: data.data
                })
                self.getUserInfo()
                app.dialog.msg('绑定成功');
            })
        } else {
            self.setData({
                isLoading: false
            })
        }
    },
    // 判断用户是否为随机名称
    isRandomName: function () {
        var self = this
        wx.getStorage({
            key: 'isRandomUsername',
            success: function (res) {
                if (res.data == 1) {
                    self.setData({
                        randomName: true
                    })
                } else {
                    self.setData({
                        randomName: false
                    })
                }
            }
        })
    },
    // 获取用户信息
    getUserInfo: function () {
        var self = this
        app.restAjax.get(app.restAjax.path('{usercenterUrl}/app/user/get-app-user', [app.usercenterUrl]), {}, {
            headers: {
                token: self.data.token
            }
        }, function (code, data) {
            self.setData({
                userInfo: data
            })
        }, function (code, data) {
            app.dialog.msg(data.msg);
        })
    },
    cancelPhone: function () {
        this.setData({
            showPhone: false
        })
        wx.showTabBar()
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.isRandomName();
        this.getToken();
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})