import { VueLikePage } from '../../utils/page'
import UserApi from '../../apis/user'
import DisplayApi from '../../apis/exhibition'
import { saveUserInfo } from '../../utils/storage'
import { API_BASE_URL  } from '../../config/config'
VueLikePage([], {
  data: {
    userInfo: {},
    tradeList: []
  },
  methods: {
    onLoad () {
      this.getAllTrade()
      let userInfo = Object.assign({}, getApp().globalData.userinfo)
      UserApi.getUserInfoById(userInfo.viewerId).then(res => {
        this.setData({
          userInfo: res.data
        })
        getApp().globalData.userinfo = res.data
      })
    },
    onShow () {
      
      
    },
    chooseImage () {
      return wx.chooseImage({
        count: 1,
        success: (res) => {
          const { tempFilePaths } = res
          return this.uploadAvatar(tempFilePaths[0])
        },
      })
    },
    updateUserInfo () {
      UserApi.updateUserInfo(this.data.userInfo).then(res => {
        wx.showToast({
          title: '修改成功',
        })
        getApp().globalData.userinfo = this.data.userInfo
        saveUserInfo(this.data.userInfo)
      })
    },
    uploadAvatar (filePath) {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
              filePath: filePath,
              name: 'file',
              url: `${API_BASE_URL}/im/upload`,
              header: {
                "Content-Type": "multipart/form-data"
                },
              success: (res) => {
                res = JSON.parse(res.data)
                let userInfo = this.data.userInfo
                userInfo.avatar = res.data
                this.setData({
                  userInfo
                })
                resolve({url: res.data});
              },
              fail: (err) => {
                  console.log(err, 'err')
              }
            })
      })
    },
    bindInput (e) {
      let userInfo = this.data.userInfo
      const { key } = e.currentTarget.dataset
      userInfo[key] = e.detail.value
      this.setData({
        userInfo
      })
    },
    getAllTrade () {
      return DisplayApi.getTradeList().then(res => {
        this.originTradeList = res.data
        this.setData({
          tradeList: res.data.map(item => item.name)
        })
      })
    },
    bindPickerChange (e) {
      let userInfo = this.data.userInfo
      userInfo.companyTrade = this.originTradeList[e.detail.value].name
      this.setData({
        userInfo
      })
    },
    changeCheckStatus (e) {
      const { value } = e.currentTarget.dataset
      this.setData({
        'userInfo.gender': value
      })
    }
  }
})