<template>
  <view class="user" :style="{color: color}">
    <image class="user-image" 
      :style="{width: isMini ? '80rpx' : '110rpx', height: isMini ? '80rpx' : '110rpx'}"
      mode="aspectFill" :src="avatarUrl" />
    <view class="user-text">
      <view v-if="authStore.token && authStore.name" 
        :style="{fontSize: isMini ? '24rpx' : '32rpx'}">
        {{ authStore.name }}
        <text class="user-text-bt" style="font-size: 24rpx;"
          v-if="!isMini" @click="openEditDialog">修改</text>
      </view>
      
      
      <text class="user-text-bt" 
        v-if="!authStore.token || !authStore.name"
        :style="{fontSize: isMini ? '24rpx' : '32rpx'}"
        @click="auth?.exec()"
        >立即登录</text>
      <text class="user-text-bt" 
        v-else-if="isMini" @click="openEditDialog">修改</text>
      <text v-else style="font-size: 24rpx; margin-top: 10rpx;">手机号：{{ authStore.phone || '未绑定' }}</text>
    </view>
  </view>

  <!-- 修改用户信息弹窗 -->
  <MessageBox
    ref="editDialogRef"
    title="修改用户信息"
    :on-ok="handleSaveUserInfo"
    text-ok="保存"
  >
    <view class="edit-form">
      <!-- 头像选择 -->
      <view class="edit-form-item">
        <text class="edit-form-label">头像</text>
        <button class="edit-form-avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="edit-form-avatar" mode="aspectFill" :src="editAvatarUrl" />

        </button>
      </view>
      <!-- 昵称输入 -->
      <view class="edit-form-item">
        <text class="edit-form-label">昵称</text>
        <input 
          class="edit-form-input" 
          type="nickname" 
          :maxlength="8"
          v-model="editForm.name"
          placeholder="请输入昵称"
          @blur="onNicknameBlur"
        />
      </view>
    </view>
  </MessageBox>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { useGlobal } from '@/hooks/useGlobal'
import { useAuthStore } from '@/store/modules/useAuthStore'
import { useApi } from '@/hooks/useApi'
import MessageBox from './MessageBox.vue'

defineProps<{
  isMini?: boolean;
  color?: string;
}>()

// 全局工具
const { toast, auth } = useGlobal()
const authStore = useAuthStore()

// 编辑弹窗
const editDialogRef = ref<InstanceType<typeof MessageBox>>()

// 编辑表单
const editForm = reactive({
  avatar: '',
  name: ''
})

const avatarUrl = computed(() => {
  if (authStore.avatar) {
    return `${useApi().transUrl(authStore.avatar)}`
  }
  return '/static/default_avatar.png'
})


const editAvatarUrl = computed(() => {
  if (editForm.avatar || authStore.avatar) {
    return `${useApi().transUrl(editForm.avatar || authStore.avatar)}`
  }
  return '/static/default_avatar.png'
})

// 打开编辑弹窗
const openEditDialog = () => {
  // 初始化表单数据
  editForm.avatar = authStore.avatar || ''
  editForm.name = authStore.name || ''
  editDialogRef.value?.showDialog()
}

// 选择头像并上传
const onChooseAvatar = async (e: any) => {
  const tempFilePath = e.detail?.avatarUrl
  if (!tempFilePath) return

  try {
    toast.value.loading('上传中...')
    
    // 使用 uni.uploadFile 上传头像
    const uploadRes = await uni.uploadFile({
      url: `${useApi().host}${useApi().uploadFile}`,
      filePath: tempFilePath,
      name: 'files',
      header: {
        'Authorization': `${authStore.token}`
      }
    })

    if (uploadRes.statusCode === 200 || uploadRes.statusCode === 201) {
      const data = JSON.parse(uploadRes.data)
      // 获取服务器返回的图片地址
      const serverUrl = data?.data?.[0] || data?.[0]
      if (serverUrl) {
        editForm.avatar = serverUrl
        toast.value.success('上传成功')
      } else {
        throw new Error('上传失败')
      }
    } else {
      throw new Error('上传失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    toast.value.error('上传失败')
  }
}

// 昵称输入框失焦
const onNicknameBlur = (e: any) => {
  const value = e.detail?.value
  if (value) {
    editForm.name = value
  }
}

// 保存用户信息
const handleSaveUserInfo = async () => {
  if (!editForm.name?.trim()) {
    toast.value.warning('请输入昵称')
    throw new Error('请输入昵称')
  }

  console.log('editForm', editForm)

  try {
    // 调用接口保存用户信息
    await useApi().userApi.updateProfileuser({
      updateProfileVo: {
        name: editForm.name.trim(),
        avatar: editForm.avatar
      }
    })
    
    // 更新本地状态
    authStore.setName(editForm.name)
    if (editForm.avatar) {
      authStore.setAvatar(editForm.avatar)
    }
    
    toast.value.success('保存成功')
  } catch (error) {
    toast.value.error('保存失败')
    throw error
  }
}
</script>

<style scoped lang="scss">
.user {
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  padding: 20rpx;
  gap: 20rpx;

  .user-image {
    border-radius: 50%;
    box-sizing: border-box;
    border: 1px solid #000000a1;
  }

  .user-text {
    display: flex;
    align-items: flex-start;
    justify-content: center;
    flex-direction: column;
    gap: 10rpx;

    .user-text-bt {
      box-sizing: border-box;
      padding: 6rpx 20rpx;
      background-color: #000;
      border-radius: 12rpx;
      font-size: 20rpx;
      color: #FFA007;
    }
  }
}

// 编辑表单样式
.edit-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 32rpx;

  .edit-form-item {
    display: flex;
    align-items: center;
    gap: 24rpx;
  }

  .edit-form-label {
    width: 80rpx;
    font-size: 28rpx;
    color: #333;
    flex-shrink: 0;
  }

  .edit-form-avatar-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
    padding: 0;
    margin: 0;
    background: transparent;
    border: none;
    
    &::after {
      display: none;
    }
  }

  .edit-form-avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    border: 2rpx dashed #ddd;
  }

  .edit-form-avatar-tip {
    font-size: 22rpx;
    color: #999;
  }

  .edit-form-input {
    flex: 1;
    height: 72rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    background: #f5f5f5;
    border-radius: 12rpx;
    box-sizing: border-box;
  }
}
</style>
