// nova-tourism/components/template2/my/index.js
let Parse = getApp().Parse;
const company = getApp().globalData.company
const qiniuUploader = require("../../../../utils/qiniuUploader");
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {

  },
  lifetimes: {
    created() {},
    attached() {
      this.refresh()
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async refresh() {
      this.getUptoken();
      this.getmy()
    },
    async getmy() {
      let uid = Parse.User.current().id
      console.log(uid);
      let ShopOrder = new Parse.Query('_User')
      let shopOrder = await ShopOrder.get(uid)
      this.setData({
        user: shopOrder.toJSON()
      })
      console.log(this.data.user);
    },
    /**
     * 
     * @param {*} e 
     * 更换头像
     */
    async onChooseAvatar(e) {
      console.log(e);
      console.log(e.detail.avatarUrl);
      let url = e.detail.avatarUrl
      let pathUrl = await this.updataAvatar(url)
      let user = Parse.User.current()
      user.set("avatar", pathUrl)
      await user.save()
      this.setData({
        avatarUrl: pathUrl
      })
      this.refresh()
    },
    //上传头像
    updataAvatar(url) {
      let that = this;
      return new Promise((resolve, rejcet) => {
        qiniuUploader.upload(
          url,
          async (res) => {
              let img = res.imageURL;
              resolve(img)
            },
            (error) => {
              console.log("error: " + error);
              resolve(false)
            }, {
              region: "SCN",
              uploadURL: that.data.uploadURL,
              domain: that.data.domain,
              uptoken: that.data.uptokenURL,
            }
        );
      })
    },
    async getUptoken() {
      // 根据config.js全局配置company的ID来获取上传口令
      let res = await Parse.Cloud.run('qiniu_uptoken', {
        company: getApp().globalData.company
      })
      this.setData({
        uptokenURL: res.uptoken,
        domain: res.domain,
        uploadURL: res.zoneUrl
      })
    },
    goUrl(e) {
      let {
        url
      } = e.currentTarget.dataset
      wx.navigateTo({
        url: url,
      })
    },
    merchant() {
      let merchant = wx.getStorageSync('merchant');
      if (merchant) {
        wx.navigateTo({
          url: '/nova-tourism/pages/my/merchant/merchant-home/index'
        });
      } else {
        wx.navigateTo({
          url: '/nova-tourism/pages/my/merchant/login/index'
        });
      }

    },
  }
})
