<template>
  <view>
    <view class="view">
      <label for="avatar">
        <view class="view-button">
          <view>头像</view>
          <view class="view-button" style="padding: 0">
            <image class="avatar" :src="userInfo.headUrl" mode="aspectFill"></image>
            <image
              class="icon-arrow"
              src="https://oss-lock.xhjcn.ltd/mp/icon_arrow.png"
              mode="aspectFill"
            ></image>
          </view>
        </view>
      </label>
      <view class="view-line"></view>
      <view class="view-button" @click="toUpdateName">
        <view>昵称</view>
        <view class="view-button" style="padding: 20rpx 0">
          <view class="name-info">{{ userInfo.nickname }}</view>
          <image
            class="icon-arrow"
            src="https://oss-lock.xhjcn.ltd/mp/icon_arrow.png"
            mode="aspectFill"
          ></image>
        </view>
      </view>
      <view class="view-line"></view>
      <label for="phone">
        <view class="view-button">
          <view>手机号</view>
          <view class="view-button" style="padding: 0">
            <view v-if="userInfo.mobile !== ''" class="info">{{ userInfo.mobile }}</view>
            <view v-else class="red-dot"></view>
            <image
              class="icon-arrow"
              src="https://oss-lock.xhjcn.ltd/mp/icon_arrow.png"
              mode="aspectFill"
            ></image>
          </view>
        </view>
      </label>
      <view class="view-line"></view>
      <view class="view-button" @click="toUpdateEmail">
        <view>邮箱</view>
        <view class="view-button" style="padding: 0">
          <view v-if="userInfo.email !== ''" class="info">{{ userInfo.email }}</view>
          <view v-else class="red-dot"></view>
          <image
            class="icon-arrow"
            src="https://oss-lock.xhjcn.ltd/mp/icon_arrow.png"
            mode="aspectFill"
          ></image>
        </view>
      </view>
      <view class="view-line"></view>
      <view class="view-button" @click="toUpdatePassword">
        <view>重置密码</view>
        <image
          class="icon-arrow"
          src="https://oss-lock.xhjcn.ltd/mp/icon_arrow.png"
          mode="aspectFill"
        ></image>
      </view>
      <view class="view-line"></view>
      <view class="view-button">
        <view>国家/地区</view>
        <view class="view-button" style="padding: 0">
          <view class="info">{{ userInfo.countryName }}</view>
        </view>
      </view>
    </view>
    <button
      open-type="chooseAvatar"
      style="display: none"
      id="avatar"
      @chooseavatar="chooseAvatar"
    ></button>
    <button
      open-type="getPhoneNumber"
      style="display: none"
      id="phone"
      @getphonenumber="rebindPhone"
    ></button>
  </view>
</template>

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

  export default {
    data() {
      return {
        pending: false
      }
    },
    computed: {
      ...mapState(useUserStore, ['userInfo'])
    },
    methods: {
      ...mapActions(useBasicStore, ['routeJump', 'getNetworkType']),
      ...mapActions(useUserStore, ['updateUserInfo', 'checkSession', 'getUserInfo']),
      async rebindPhone(detail) {
        if (!(detail.detail.encryptedData && detail.detail.iv)) {
          return
        }
        if (detail.detail.errMsg === 'getPhoneNumber:fail user deny') {
          return
        }
        if (this.pending) {
          return
        }
        this.pending = true
        const result = await this.checkSession()
        if (result) {
          const { code, message } = await rebindPhoneRequest({
            encryptedData: detail.detail.encryptedData,
            iv: detail.detail.iv
          })
          if (code === 0) {
            this.getUserInfo()
            uni.showToast({
              title: '更换成功',
              icon: 'none'
            })
          } else if (code === 421) {
            uni.showToast({
              title: '手机号已被其他账号绑定',
              icon: 'none'
            })
          } else if (code === 438) {
            /* empty */
          } else {
            uni.showToast({
              title: message,
              icon: 'none'
            })
          }
        } else {
          this.rebindPhone()
        }
        this.pending = false
      },
      chooseAvatar(e) {
        const that = this
        if (that.pending) {
          return
        }
        that.pending = true

        const path = e.detail.avatarUrl
        const list = path.split('/')
        const filename = list[list.length - 1]
        uni.getFileSystemManager().getFileInfo({
          filePath: path,
          async success(res) {
            const size = res.size
            const { code, data } = await getUploadParamsRequest({
              size,
              module: 'avatar',
              userId: that.userInfo.userId,
              filename
            })
            if (code === 0) {
              uni.uploadFile({
                url: data.uploadUrl,
                filePath: path,
                name: 'file',
                formData: data.formData,
                async success() {
                  const { code: updateCode } = await updateUserInfoRequest({
                    headUrl: data.fileUrl
                  })
                  if (updateCode === 0) {
                    that.updateUserInfo({
                      ...that.userInfo,
                      headUrl: data.fileUrl
                    })
                    uni.showToast({
                      title: '头像更新成功',
                      icon: 'none'
                    })
                  } else {
                    uni.showToast({
                      title: '头像更新失败',
                      icon: 'none'
                    })
                  }
                  that.pending = false
                },
                fail(res) {
                  console.log('上传失败', res)
                  console.log(data.uploadUrl, path, data.formData)
                  uni.showToast({
                    title: '头像更新失败',
                    icon: 'none'
                  })
                  that.pending = false
                }
              })
            } else {
              uni.showToast({
                title: '头像更新失败',
                icon: 'none'
              })
              that.pending = false
            }
          }
        })
      },
      toUpdateName() {
        this.routeJump({
          name: 'updateName'
        })
      },
      toUpdateEmail() {
        if (this.userInfo.email === '') {
          this.routeJump({
            name: 'updateEmail'
          })
        } else {
          this.routeJump({
            name: 'verifyEmail'
          })
        }
      },
      toUpdatePassword() {
        this.routeJump({
          name: 'updatePassword'
        })
      }
    }
  }
</script>

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

<style scoped lang="scss">
  .view {
    width: 710rpx;
    margin-top: 32rpx;
    margin-left: 20rpx;
    background: #ffffff;
    border-radius: 32rpx;
  }

  .view-button {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20rpx 0 40rpx;
    font-size: 32rpx;
    font-weight: bold;
    line-height: 80rpx;
    color: #292826;
  }

  .info {
    width: 400rpx;
    margin-right: 20rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: right;
    white-space: nowrap;
  }

  .name-info {
    width: 520rpx;
    margin-right: 20rpx;
    overflow: hidden;
    line-height: 40rpx;
    text-align: right;
    word-break: break-all;
  }

  .red-dot {
    width: 20rpx;
    height: 20rpx;
    margin-right: 20rpx;
    background: #ec433c;
    border-radius: 50%;
  }

  .icon-arrow {
    width: 40rpx;
    height: 40rpx;
  }

  .view-line {
    width: 100%;
    height: 3rpx;
    background: #ebebeb;
  }

  .avatar {
    width: 80rpx;
    height: 80rpx;
    margin-top: 20rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 50%;
  }
</style>
