<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationBarTitleText: '%myProfile.title%',
    navigationBarBackgroundColor: '#fff',
  },
}
</route>

<script lang="ts" setup>
import { updateInfo } from '@/api/login'
import { t } from '@/locale'
import { useUserStore } from '@/store'
import { getEnvBaseUploadUrl } from '@/utils'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'MyProfile', // 我的资料
})

const userStore = useUserStore()
const userInfo = computed(() => {
  return getUserInfoHook()
})

const uploading = ref(false)

// 更新头像
async function updateAvatar() {
  try {
    // 微信小程序从基础库 2.21.0 开始，wx.chooseImage 停止维护，请使用 uni.chooseMedia 代替。
    const res: any = await new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        success: resolve,
        fail: reject,
      })
      // #endif

      // #ifndef MP-WEIXIN
      uni.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: resolve,
        fail: reject,
      })
      // #endif
    })

    let tempFilePath = ''
    let size = 0

    // #ifdef MP-WEIXIN
    if (!res.tempFiles || res.tempFiles.length === 0)
      return
    tempFilePath = res.tempFiles[0].tempFilePath
    size = res.tempFiles[0].size
    // #endif

    // #ifndef MP-WEIXIN
    if (!res.tempFilePaths || res.tempFilePaths.length === 0)
      return
    tempFilePath = res.tempFilePaths[0]
    size = res.tempFiles?.[0]?.size || 0
    // #endif

    // 检查文件大小（限制为5MB）
    const maxSize = 5 * 1024 * 1024
    if (size > maxSize) {
      toast.error(t('myProfile.upload.sizeLimit'))
      return
    }

    uploading.value = true
    await uni.showLoading({
      title: t('myProfile.upload.uploading'),
      mask: true,
    })

    // 上传图片
    const uploadRes: any = await new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${getEnvBaseUploadUrl()}`,
        filePath: tempFilePath,
        name: 'file',
        success: resolve,
        fail: reject,
      })
    })
    console.log('uploadRes', uploadRes)
    // 解析上传结果
    const uploadData = JSON.parse(uploadRes.data)
    if (uploadData.code !== '200') {
      throw new Error(uploadData.message)
    }

    const avatarUrl = uploadData.data
    // 调用更新用户信息接口
    await updateInfo({
      headPic: avatarUrl,
    })
    // 更新本地用户信息
    const newUserInfo = { ...userInfo.value, headPic: avatarUrl }
    userStore.setUserInfo(newUserInfo)
    userStore.getUserInfo()

    uni.hideLoading()
    toast.success(t('myProfile.upload.success'))
  }
  catch (error: any) {
    uni.hideLoading()
    console.error('Update avatar failed:', error)
    toast.error(error.message || t('myProfile.upload.error'))
  }
  finally {
    uploading.value = false
  }
}
onLoad(() => {
  // 页面加载时的逻辑
  userStore.getUserInfo()
})
</script>

<template>
  <z-paging>
    <view class="py-20rpx">
      <wd-cell-group custom-class="mb-20rpx" border>
        <wd-cell :title="t('myProfile.avatar')" center>
          <view class="flex items-center justify-end" @click="updateAvatar">
            <view class="relative flex items-center justify-center">
              <wd-img width="64rpx" height="64rpx" round :src="userInfo.headPic" />
              <view v-if="uploading" class="absolute inset-0 flex items-center justify-center rounded-full bg-black bg-opacity-50">
                <wd-loading size="20rpx" color="#fff" />
              </view>
            </view>
            <wd-icon name="arrow-right" custom-class="ml-10rpx" size="36rpx" />
          </view>
        </wd-cell>
        <wd-cell :title="$t('myProfile.userId')" :value="userInfo.userNo" />
        <wd-cell :title="$t('myProfile.userName')" :value="userInfo.name" />
        <wd-cell :title="$t('myProfile.mobileNumber')" :value="userInfo.phoneNo" />
      </wd-cell-group>
      <wd-cell-group custom-class="mb-20rpx" border>
        <wd-cell :title="$t('myProfile.bankName')" :value="userInfo.bank" />
        <wd-cell :title="$t('myProfile.bankAccountName')" :value="userInfo.bankAccountName" />
        <wd-cell :title="$t('myProfile.bankAccountNo')" :value="userInfo.bankAccount" />
      </wd-cell-group>
    </view>
  </z-paging>
</template>

<style lang="scss" scoped>
//
</style>
