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

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

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

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

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

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

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