<template>
  <view>
    <input class="input" :value="nickname" maxlength="20" placeholder="请输入昵称"
           placeholder-class="input-placeholder" :focus="true" @input="updateInput"></input>
    <view class="button" @click="updateName">保存</view>
  </view>
</template>

<script>
import { mapActions, mapState } from 'pinia'
import { useUserStore } from '@/stores/user'
import { updateUserInfoRequest } from '@/api/user'

export default {
  data() {
    return {
      nickname: ''
    }
  },
  computed: {
    ...mapState(useUserStore, ['userInfo'])
  },
  onLoad() {
    this.nickname = this.userInfo.nickname
  },
  methods: {
    ...mapActions(useUserStore, ['updateUserInfo']),
    updateInput(data) {
      this.nickname = data.detail.value
      console.log(data)
    },
    async updateName() {
      if(this.nickname === '') {
        uni.showToast({
          title: '昵称不能为空',
          icon: 'none'
        })
        return
      }
      const { code } = await updateUserInfoRequest({
        nickname: this.nickname
      })
      if(code === 0) {
        this.updateUserInfo({
          ...this.userInfo,
          nickname: this.nickname
        })
        uni.navigateBack({
          complete() {
            uni.showToast({
              title: '昵称更新成功',
              icon: 'none'
            })
          }
        })
      } else {
        uni.showToast({
          title: '昵称更新失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: $uni-bg-color-grey;
}
</style>

<style scoped lang="scss">
.input {
  border-radius: 16rpx;
  background: #FFFFFF;
  margin-left: 35rpx;
  margin-top: 48rpx;
  height: 108rpx;
  width: 616rpx;
  padding-left: 32rpx;
  padding-right: 32rpx;
}

.input-placeholder {
  height: 108rpx;
  font-size: 36rpx;
  font-weight: bold;
  line-height: 108rpx;
}

.button {
  margin-top: 32rpx;
  margin-left: 35rpx;
  width: 680rpx;
  height: 96rpx;
  background: #63b8af;
  border-radius: 16rpx;
  line-height: 96rpx;
  text-align: center;
  font-size: 32rpx;
  color: #FFFFFF;
}
</style>
