import api from '@/api'

// 上传头像mixin
export const avatarMixin = {
  data () {
    return {
      cropperOption: {
        visible: false,
        img: null
      }
    }
  },
  methods: {
    uploadImg (event) {
      let file = event.target.files[0]
      if (this.beforeAvatarUpload(file)) {
        this.readFileAsBlob(file)
      }
    },
    readFileAsBlob (file) {
      let self = this
      let reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = e => {
        self.cropperOption.img = e.target.result
        self.cropperOption.visible = true
      }
      reader.onerror = () => {
        self.readFileAsBlob(file)
      }
    },
    cropperClose () {
      this.cropperOption.visible = false
    },
    cropperSubmit (image) {
      let param = new FormData()
      param.append('user_id', this.$store.state.userId)
      param.append('token', this.$store.state.token)
      param.append('cover_photo', image)
      if (this.isMe) {
        api.user.changePhoto(param).then(({ data }) => {
          if (data.code === 0) {
            this.handleAvatarSuccess(image)
            this.cropperClose()
          }
        })
      } else {
        param.append('group_id', this.$store.state.curSession)
        api.group.changeCover(param).then(({ data }) => {
          if (data.code === 0) {
            this.handleAvatarSuccess(image)
            this.cropperClose()
          }
        })
      }
    },
    handleAvatarSuccess (file) {
      let imageUrl = URL.createObjectURL(file)
      this.$showTips(this.$t('public.uploadSucc'))
      if (this.isMe) {
        // 用户头像
        this.$store.commit('updateUserPhoto', imageUrl)
        this.$store.commit('updateMemberAvatar', {
          userId: this.$store.state.userId,
          imageUrl: imageUrl
        })
      } else {
        // 群头像
        this.$store.dispatch('updateSessionItem', {
          sessionId: this.$store.state.curSession,
          data: {
            cover_photo: imageUrl
          }
        })

        this.$store.commit('updateGroup', {
          key: 'coverPhoto',
          data: imageUrl
        })
        console.log('群头像update')
      }
    },
    beforeAvatarUpload (file) {
      const isIMG = file.type.indexOf('image') > -1
      const isLt1M = file.size / 1024 / 1024 < 2
      if (!isIMG || !isLt1M) {
        this.$showTips(this.$t('userinfo.maxUploadTips'))
      }
      return isIMG && isLt1M
    }
  }
}
