let app = getApp();
const Http = require("../../utils/HttpBasics");
const util = require("../../utils/util.js");
const bgColor = require("../../utils/bgColor.js")
const config = require("../../config/config");
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    navigationBarHeight,
    avatarUrl: defaultAvatarUrl,
    nickName: '',
    username: '',
    date: '1988-03-12',
    dateEnd: '',
    dateFlag: 1,
    gender: '',
    sexArry: ['男', '女'],
    sexFlag: 1,
    height: '',
    weight: '',
    theme: wx.getSystemInfoSync().theme,
    typeLsit: {}
  },

  /**
   * 获取全局样式
   */
  getType() {
    Http.get({
      url: config.api.setType,
      data: {
        mouldType: app.globalData.mouldType
      }
    }).then(res => {
      const {
        code,
        data
      } = res
      if (code == 200) {
        app.globalData.typeLsit = data
        this.setData({
          typeLsit: data,
        })
      }
    })
  },

  getUserInfo(token) {
    let that = this
    Http.get({
      url: config.api.getScore,
      data: {
        token: token
      }
    }).then(res => {
      console.log(res, 'res')

      let avatarUrl = null
      if (res.data.avatarUrl.length > 1) {
        avatarUrl = res.data.avatarUrl
      } else {
        avatarUrl = defaultAvatarUrl
      }

      let gender = null
      let sexFlag = null
      if (1 * res.data.sex) {
        gender = res.data.sex - 1
        sexFlag = 2
      } else {
        gender = res.data.sex
        sexFlag = 1
      }

      let adress = null
      if (res.data.address) {
        adress = JSON.parse(res.data.address)
      }


      this.setData({
        avatarUrl: avatarUrl,
        nickName: res.data.nickName,
        username: res.data.name,
        gender: gender,
        sexFlag: sexFlag,
        date: util.fmtDate(parseInt(res.data.birthdate)),
        dateFlag: res.data.birthdate ? 2 : 1,
        height: res.data.height,
        weight: res.data.weight,
        address: adress ? adress.name + '(' + adress.address + ')' : ''
      })
    }).catch(err => {
      console.log(err, 'err');
    })
  },

  bindDateChange(e) {
    this.setData({
      date: e.detail.value,
      dateFlag: 2
    })
  },

  bindGenderChange(e) {
    this.setData({
      gender: e.detail.value,
      sexFlag: 2
    })
  },

  setAddress() {
    return
    let that = this;
    // wx.chooseL
    // ocation({
    //   success: function (res) {
    //     that.setData({
    //       address: res.name + '(' + res.address + ')',
    //       addressStr: JSON.stringify(res)
    //     })
    //   },
    //   fail: function (error) {
    //     console.log(error)
    //   },
    //   complete: function (data) {

    //   }
    // })
  },

  goSetChildren() {
    wx.navigateTo({
      url: '/pages/edit/edit?type=1',
    })
  },

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

  formSubmit(e) {
    const that = this

    let birthdate = null
    if (that.data.dateFlag == 2 && that.data.date) {
      birthdate = new Date(that.data.date).getTime();
    }

    const data = {
      avatarUrl: that.data.avatarUrl,
      nickName: e.detail.value.nickname.trim(),
      name: e.detail.value.username || "und",
      sex: 1 * that.data.gender + 1,
      birthdate: birthdate,
      height: e.detail.value.height ? e.detail.value.height : that.data.height,
      weight: e.detail.value.weight ? e.detail.value.weight : that.data.weight,
      address: that.data.addressStr || null,
    }
    console.log(data, 'data');
    if (!data.nickName) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'error',
        duration: 2000
      })
    }
    // else if (!data.name) {
    //   wx.showToast({
    //     title: '请输入真实姓名',
    //     icon: 'error',
    //     duration: 2000
    //   })
    // } 
    else if (data.nickName.length > 16) {
      wx.showToast({
        title: '昵称上限为16字符',
        icon: 'none',
        duration: 2000
      })
    } else {
      Http.post({
        url: "/user/updateUserInfo",
        data,
      }).then(res => {
        if (res.code == 200) {
          wx.showToast({
            title: "信息提交成功",
            icon: 'success',
            duration: 1500,
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: err.message || "提交失败",
          icon: 'none',
          duration: 1500,
        })
      })
    }
  },

  goCanelAccount() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '注销后请重新进入小程序',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.goCancelUser()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  goCancelUser() {
    Http.get({
      url: "/user/cancelUser"
    }).then(res => {
      if (res.code == 200) {
        wx.showToast({
          title: "注销成功",
          icon: 'success',
          duration: 1500,
        })

        wx.exitMiniProgram()

      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.message || "注销失败",
        icon: 'none',
        duration: 1500,
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (app.globalData.token) {
      this.getUserInfo(app.globalData.token)
    }
    this.getType()
    wx.onThemeChange((result) => {
      this.setData({
        theme: result.theme
      })
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  // },

  onChooseAvatar(e) {
    const that = this
    const { avatarUrl } = e.detail
    wx.uploadFile({
      url: config.url + config.api.fileUpload,
      header: {
        'token': app.globalData.token
      },
      filePath: avatarUrl,
      name: 'file',
      success: function (res) {
        that.setData({
          avatarUrl: JSON.parse(res.data).data.url
        })
        console.log(that.data.avatarUrl);
      }
    })

  },
})