const DEFAULT_PAGE = 0;
const Apps = getApp();
const api = require('../../config/api.js');
const util = require('../../config/util.js');
import Dialog from '@vant/weapp/dialog/dialog';
Page({

    data: {
        myimg: 'https://ndnd.duiduiedu.com/uploads/pics/minemainhead.png',
        userinfo: '',
        avatar: '',
        id: 0,
        show: false,
        popmsgdata: null,
        username: '',
        userdatainfo: ''
    },
    getUserInfo(event) {
        console.log(event.detail);
    },
    onClose() {
        this.setData({ show: false });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function (options) {

    },
    usernamemdclick: function (params) {
        this.setData({ showpopup: true });
        console.log(params);
    },
    onClosepopup: function (params) {
        this.setData({ showpopup: false });
    },
    onChangeuser: function (params) {
        console.log(params.detail);
        this.setData({
            username: params.detail
        })
    },
    saveusername: function (params) {
        //保存用户名称
        console.log(this.data.username);
        this.updateusername(wx.getStorageSync('wxuserid'), this.data.username);

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

        //   if (Apps.globalData.currentuserinfo == null){
        //     wx.redirectTo({
        //       url: '/pages/userlogin/userlogin',
        //     })
        // }

        this.loaddata();
        this.popmsg();
        this.userisblack(wx.getStorageSync('userinfo').mobile); //是否黑名单



        // }

    },
    kfbtn:function (params) {
      
      try {
        wx.openCustomerServiceChat({
          extInfo: {
            url: 'https://work.weixin.qq.com/kfid/kfc79f714830ba6cc05' //客服ID
          },
          corpId: 'wwaf23716917173cba', //企业微信ID
          success(res) {}
        })
      } catch (error) {
        showToast("请更新至微信最新版本")
      }

    },
    userisblack: function (mobile) {
        //用户是否黑名单
        //直播列表
        const that = this;
        let url = Apps.globalData.baseUrl + '/user/isblack';
        var param = {
            mobile: mobile
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);
            wx.setStorageSync('userisblack', res);
        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    aboutclick: function () {
        //关于我们
        wx.navigateTo({
            url: '/pages/messageencyclopedias/messageencyclopedias?id=1',
        })
    },
    onChooseAvatar: function (params) {
        console.log(params);
    },
    onClickShow: function () {
        //加载数据
        let url = Apps.globalData.baseUrl + '/user/signdata';
        var param = {
            user_id: wx.getStorageSync('wxuserid')
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {

            let titles = "签到成功";
            if (res == 1) {
                // titles = "签到成功";
                this.popmsg();
            } else if (res == 2) {
                // titles = "连续签到成功";
                this.popmsg();
            } else if (res == 3) {
                // titles = "重新签到成功";
                this.popmsg();
            } else {
                titles = "今天已签到成功，无须再签到"
                wx.showToast({
                    title: titles,//提示文字
                    duration: 2000,//显示时长
                    mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
                    icon: 'none', //图标，支持"success"、"loading"  
                    success: function () { },//接口调用成功
                    fail: function () { },  //接口调用失败的回调函数  
                    complete: function () { } //接口调用结束的回调函数  
                })

            }

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

    },
    onClickHide(e) {
        this.setData({ show: false });
        //签到
    },
    noop(e) {
        //加载数据
        console.log(e);
        let url = Apps.globalData.baseUrl + '/user/mpopmsg';
        var param = {
            user_id: wx.getStorageSync('wxuserid'),
            id: e.currentTarget.id,
            xid: e.currentTarget.dataset.xid
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);
            this.setData({ show: false });
            this.loaddata();
            this.popmsg();

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

    },
    loaddata: function (params) {

        // if (Apps.globalData.currentuserinfo == null){
        //     wx.redirectTo({
        //       url: '/pages/userlogin/userlogin',
        //     })
        // }
        // Apps.islogin();  // 已在 onShow 中检查，此处移除避免重复跳转

        //加载数据
        let url = Apps.globalData.baseUrl + '/user/getuserinfobyopenid';
        var param = {
            // id: Apps.globalData.currentuserinfo.id
            id: wx.getStorageSync('wxuserid')
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);
            // 移除重复的登录跳转，避免跳转两次
            // if (res.data == null) {
            //     //如果用户在数据中没有数据则重新注册
            //     wx.navigateTo({
            //         url: '/pages/userlogin/userlogin',
            //     })
            // }
            if (res.data) {
                Apps.globalData.userinfo = res.data;
                // const userdatainfo = wx.getStorageSync('userinfo');
                console.log("res==============")
                console.log(res)
                this.setData({
                    userinfo: res.data,
                    myimg: res.data.avatar,
                    username: res.data.username,
                    userdatainfo: res.data
                })
                wx.setStorageSync('wxuserid', res.data.id);
                wx.setStorageSync('userinfo', res.data);
                wx.setStorageSync('wxopenid', res.data.openid);
            }

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    vipclick: function (params) {
        wx.navigateTo({
            url: '/pages/vipquanyi/vipquanyi',
        })
    },
    myaddressclick: function (params) {
        wx.navigateTo({
            url: '/pages/myaddress/myaddress',
        })
    },
    vipchargeclick: function (params) {
        wx.navigateTo({
            url: '/pages/viprecharge/viprecharge',
        })
    },
    collectioncourseclick: function (params) {
        wx.navigateTo({
            url: '/pages/collectionsub/collectionsub',
        })
    },
    collectioncourse: function (params) {
        wx.navigateTo({
            url: '/pages/collectioncourse/collectioncourse',
        })
    },
    vipquanyiclick: function (params) {
        wx.redirectTo({
            url: '/pages/viprecharge/viprecharge',
        })
    },
    chargeshopclick: function (params) {
        wx.navigateTo({
            url: '/pages/chargeshop/chargeshop',
        })
    },
    mycommunityinfoclick: function (params) {
        wx.navigateTo({
            url: '/pages/mycommunityinfo/mycommunityinfo', //我的怒贴
        })
    },
    myexamanalysisclick: function (params) {
        wx.navigateTo({
            url: '/pages/myexamanalysis/myexamanalysis', //我的怒贴
        })
    },
    popmsg: function () {

        //加载弹窗
        if (wx.getStorageSync('wxuserid') == null)
            return;

        let url = Apps.globalData.baseUrl + '/user/getpopmsg';
        var param = {
            id: wx.getStorageSync('wxuserid')
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);
            if (res.data != null) {
                this.setData({
                    show: true,
                    popmsgdata: res.data
                });
            }
        }).catch((errMsg) => {
            console.log(errMsg);
        });

    },
    myonChooseAvatar: function (e) {
        console.log("fan------------")
        console.log(e.detail.avatarUrl);
        const tempFilePaths = e.detail.avatarUrl;
        const that = this;
        wx.uploadFile({
            url: Apps.globalData.baseUrl + '/wordslist/uploadpics', //仅为示例，非真实的接口地址
            filePath: tempFilePaths,
            name: 'file',
            formData: {
                'user': 'test'
            },
            success(res) {
                const dataurl = Apps.globalData.baseimgurl + JSON.parse(res.data);
                that.updateuserimage(wx.getStorageSync('wxuserid'), dataurl);
                that.setData({
                    myimg: dataurl
                })
            }
        })
    },
    updateuserimage: function (id, avatar) {

        //更新用户头像
        const that = this;
        let url = Apps.globalData.baseUrl + '/user/updateuserimage';
        var param = {
            id: id,
            avatar: avatar
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    updateusername: function (id, username) {

        //更新用户头像
        const that = this;
        let url = Apps.globalData.baseUrl + '/user/updateusername';
        var param = {
            id: id,
            username: username
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            that.loaddata();
        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    handleLogout: function () {
        try {
          wx.removeStorageSync('wxopenid');
          wx.removeStorageSync('wxuserid');
          wx.removeStorageSync('userinfo');
          wx.removeStorageSync('userisblack');
        } catch (e) {
          console.log('清理本地登录信息失败:', e);
        }
        this.setData({
          userinfo: '',
          userdatainfo: '',
          myimg: 'https://ndnd.duiduiedu.com/uploads/pics/minemainhead.png',
        });
        wx.showToast({
          title: '已退出登录',
          icon: 'success',
          duration: 1500,
        });
        // 如需跳到登录页，可放开：
        wx.redirectTo({ url: '/pages/userlogin/userlogin' });
      }
})