let util = require('../../../utils/util')
let apiArr = require('../../../api/water_filter')

const __staticUrl = require('../../../config/env.js').static_url
Page({
    data: {
        avatarUrl: (__staticUrl + '/person/Group_309.png?2'),
        userInfo: {
            name: '张三',
            phone: '13800138000'
        },
        stats: {
            newInstall: 12,
            filterReplace: 8,
            repair: 5
        },
        fileList: [],
        sexOptions: ['男', '女'],
        avatarUrl2:""
    },

    SubscribeMessage(){
        wx.navigateTo({
          url: '/pages/SubscribeMessage/SubscribeMessage',
        })
    },


    changeSex(e) {
        const sexIndex = e.detail.value;
        this.setData({
          sexIndex,
          'userInfo.sex': sexIndex + 1 // 更新性别值
        });
        // 这里可以添加保存性别到服务器的逻辑
      },

      deviceList(){
          wx.navigateTo({
            url: '../device/index',
          })
      },

    loginOut(){
        wx.removeStorageSync('is_master')
        wx.redirectTo({
            url:"/pages/newLogin/newLogin"
        })
    },

      editMaster(){
          wx.navigateTo({
            url: '/packages/master/masterInfo/index',
          })
      },

    getMasterInfo() {
        let that = this
        wx.showLoading({
          title: '加载中...',
          mask:true
        })
        util.postUrl(apiArr.masterInfo, {
            user_id: wx.getStorageSync('userId')
        }, res => {
            wx.hideLoading()
            wx.setStorageSync('master', res)
            that.setData({
                userInfo: res,
                sexIndex:res.sex - 1
            })

            if (res.avatar) {
                let  avatarUrl = res.avatar.startsWith('http')? res.avatar : util.img_url + res.avatar
                console.log(res.avatar.startsWith('http'));
                that.setData({
                    avatarUrl
                })
            }

        })
    },
    updateName(e){
        let that = this
        that.setData({
            "userInfo.name":e.detail.value
        })
    },
    updatePhone(e){
        let that = this
        that.setData({
            "userInfo.phone":e.detail.value
        })
    },
    saveUserInfo(){
        let that = this
        util.postUrl(apiArr.editMasterInfo,{
            info_id:that.data.userInfo.info_id,
            name:that.data.userInfo.name,
            sex:that.data.userInfo.sex,
            region:that.data.userInfo.region,
            address:that.data.userInfo.address,
            avatar:that.data.avatarUrl2,
            phone:that.data.userInfo.phone
        },res=>{
            console.log(res);
            if(res.msg == '操作成功'){
                wx.showToast({
                  title: '修改成功！',
                })
            }else{
                wx.showToast({
                    title: res.msg,
                    icon:"none"
                  })
            }
        })
    },
    onLoad(e) {
        // 这里可以添加获取用户信息和统计数据的逻辑
        let that = this

        that.getMasterInfo()

        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })

    },

    // 选择头像
    chooseAvatar() {
        let that = this
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                const tempFilePath = res.tempFiles[0].tempFilePath;
                // 这里可以添加上传头像到服务器的逻辑
                util.uploadFileUrl(tempFilePath, (res) => {
                    let datas = JSON.parse(res)
                    console.log(datas.data);
                    let url = util.img_url + datas.data.path
                    let url2 =  datas.data.path
                    let fileList = that.data.fileList
                    let obj = {
                        url: url,
                        name: 'avatar'
                    }
                    fileList.push(obj)
                    that.setData({
                        fileList,
                        avatarUrl: url,
                        avatarUrl2:url2
                    })
                })
            }
        });
    },

    onShareAppMessage(){
        return {
            title: '人人爱净水',  // 分享卡片标题（必填）
            path: '/pages/water_filter/water_filter',  // 用户点击后跳转的路径（可选，默认当前页）
            imageUrl: (__staticUrl + '/share.png')  // 自定义图片（可选，比例建议 5:4）
          }
    },
    onShareTimeline() {
        return {
            title: '人人爱净水', // 自定义标题
            query: '', // 自定义页面路径中的参数
            imageUrl: (__staticUrl + '/share.png') // 自定义分享图片路径
        }
    },
});