const util = require('../../../utils/util.js');
const app = getApp();
Page({
  data: {
    userInfo: app.globalData.userInfo,
    prompt: {
      title: "",
      cost: ""
    }
  },
  onReady() {
    this.prompt = this.selectComponent("#prompt");
  },
  onShow(){
    this.setData({ userInfo: app.globalData.userInfo});
  },
  chooseImg() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.uploadAli(res.tempFilePaths[0]);
      }
    })
  },
  uploadAli(img) {
    var _this = this, userInfo = app.globalData.userInfo;
    util.uploadFile("v2/user/avatar/ossPolicy", img, { "rid": (userInfo ? userInfo.rid : "")}, true).then((res) => {
      if (res.code == 0) {
        // res.uploadTask.onHeadersReceived((data) => {
          _this.setData({ percent: 100 });
          app.globalData.userInfo.avatar = res.url;
          _this.setData({ userInfo: app.globalData.userInfo });
          wx.setStorageSync("WXuserInfo", app.globalData.userInfo);
        // });
        res.uploadTask.onProgressUpdate((data) => {
          _this.setData({ percent: data.progress });
        });
      } else
        util.showTips(res.reason);
    });
  },
  promptNickname(){
    let that = this;
    this.prompt.showPrompt();
    this.data.prompt.title = '修改昵称';
    this.data.prompt.cost = this.data.userInfo.nickname;
    this.setData({prompt: this.data.prompt});
  },
  getInput(e) {
    this.data.prompt.cost = e.detail.value;
    this.setData({
      prompt: this.data.prompt
    });
  },
  confirm() {
    let that = this;
    let nickname = this.data.prompt.cost;
    if (util.isEmpty(nickname)) {
      util.showTips('请输入用户昵称。');
      return false;
    }
    util.ajax({
      func: "v2/user/nickname",
      data: { nickname },
      method: 'PUT',
      contentType: 'application/json'
    }, function (res) {
      if (res.code == 0) {
        let userInfo = app.globalData.userInfo;
        userInfo.nickname = nickname;
        that.setData({ userInfo });
        
        app.globalData.userInfo = userInfo;
        wx.setStorageSync("WXuserInfo", userInfo)
        that.cancel();
      } else {
        util.showTips(res.reason);
      }
    });
  },
  cancel() {
    this.prompt.hidePrompt();
  },
  navigatorURl(e) {
    util.navigator(e.currentTarget.dataset.url);
  },
  unty() {
    var that = this;
    wx.showModal({
      content: '确定解除本账号与微信绑定，解除后无法微信快捷登录？',
      success: function (res) {
        if (res.confirm) {
          util.ajax({ func: "user/unbound_weixin" }, function (res) {
            if (res.code == 0) {
              let userInfo = app.globalData.userInfo;
              userInfo.weixin = 0;
              that.setData({ userInfo });

              app.globalData.userInfo = userInfo;
              wx.setStorageSync("WXuserInfo", userInfo)
            }
          })
        }
      }
    })
  },
})