<template>
  <view class="page-profile">
    <!-- 头像区域 -->
    <view class="avatar-section">
      <view class="avatar-wrapper" @click="handleAvatarTap">
        <image
          class="avatar"
          :src="formData.avatar || '/static/img/default-avatar.png'"
          mode="aspectFill"
        />
        <view class="avatar-mask">
          <text class="avatar-text">点击更换</text>
        </view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <view class="form-item">
        <view class="form-label">昵称</view>
        <input
          class="form-input"
          v-model="formData.nickname"
          placeholder="请输入昵称"
          maxlength="20"
        />
      </view>

      <view class="form-item">
        <view class="form-label">手机号</view>
        <view class="form-value disabled">{{ userInfo?.phone }}</view>
      </view>

      <view class="form-item">
        <view class="form-label">真实姓名</view>
        <input
          class="form-input"
          v-model="formData.realName"
          placeholder="请输入真实姓名"
          maxlength="50"
          :disabled="isVerified"
        />
      </view>

      <view class="form-item">
        <view class="form-label">身份证号</view>
        <input
          class="form-input"
          v-model="formData.idCard"
          placeholder="请输入身份证号"
          maxlength="18"
          :disabled="isVerified"
        />
      </view>

      <view v-if="isVerified" class="verified-badge">
        <text class="verified-icon">✓</text>
        <text class="verified-text">已实名认证</text>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="button-section">
      <base-button
        type="primary"
        size="large"
        block
        :loading="loading"
        @click="handleSave"
      >
        保存
      </base-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/store/user';
import { updateUserProfile } from '@/api/user/auth';
import { chooseAndUpload } from '@/utils/upload';
import BaseButton from '@/components/base/BaseButton.vue';

const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
const loading = ref(false);

const formData = ref({
  nickname: '',
  avatar: '',
  realName: '',
  idCard: ''
});

const isVerified = computed(() => {
  return !!(userInfo.value?.realName && userInfo.value?.idCard);
});

onMounted(() => {
  if (userInfo.value) {
    formData.value.nickname = userInfo.value.nickname || '';
    formData.value.avatar = userInfo.value.avatar || '';
    formData.value.realName = userInfo.value.realName || '';
    formData.value.idCard = userInfo.value.idCard || '';
  }
});

async function handleAvatarTap() {
  try {
    uni.showLoading({ title: '上传中...' });
    const urls = await chooseAndUpload({ count: 1 });
    formData.value.avatar = urls[0];
    uni.showToast({ title: '上传成功', icon: 'success' });
  } catch (error: any) {
    uni.showToast({
      title: error.message || '上传失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
}

async function handleSave() {
  if (!formData.value.nickname.trim()) {
    uni.showToast({ title: '请输入昵称', icon: 'none' });
    return;
  }

  // 如果填写了实名信息，需要验证
  if (formData.value.realName || formData.value.idCard) {
    if (!formData.value.realName.trim()) {
      uni.showToast({ title: '请输入真实姓名', icon: 'none' });
      return;
    }
    if (!formData.value.idCard.trim()) {
      uni.showToast({ title: '请输入身份证号', icon: 'none' });
      return;
    }
    if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(formData.value.idCard)) {
      uni.showToast({ title: '请输入正确的身份证号', icon: 'none' });
      return;
    }
  }

  loading.value = true;

  try {
    const updateData: any = {
      nickname: formData.value.nickname,
      avatar: formData.value.avatar
    };

    // 只有未实名认证时才能提交实名信息
    if (!isVerified.value && formData.value.realName && formData.value.idCard) {
      updateData.realName = formData.value.realName;
      updateData.idCard = formData.value.idCard;
    }

    const res = await updateUserProfile(updateData);

    if (res.code === 200) {
      // 更新本地用户信息
      await userStore.fetchUserInfo();

      uni.showToast({ title: '保存成功', icon: 'success' });

      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error(res.message || '保存失败');
    }
  } catch (error: any) {
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
}
</script>

<style lang="scss" scoped>
@import '@/static/styles/design-tokens.scss';

.page-profile {
  min-height: 100vh;
  background: $bg-page;
}

/* ========== 头像区域 ========== */
.avatar-section {
  padding: 60rpx 0;
  background: #fff;
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}

.avatar-wrapper {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
}

.avatar-mask {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60rpx;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  font-size: 24rpx;
  color: #fff;
}

/* ========== 表单区域 ========== */
.form-section {
  background: #fff;
  margin-bottom: 40rpx;
  position: relative;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 32rpx 32rpx;
  border-bottom: 1rpx solid $border-base;

  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  width: 160rpx;
  font-size: 30rpx;
  color: $text-primary;
}

.form-input {
  flex: 1;
  font-size: 30rpx;
  color: $text-primary;
  text-align: right;

  &:disabled {
    color: $text-disabled;
  }
}

.form-value {
  flex: 1;
  font-size: 30rpx;
  color: $text-primary;
  text-align: right;

  &.disabled {
    color: $text-disabled;
  }
}

.verified-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 24rpx;
  background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
  border-top: 1rpx solid #a5d6a7;
}

.verified-icon {
  width: 32rpx;
  height: 32rpx;
  background: #4caf50;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  font-weight: bold;
}

.verified-text {
  font-size: 28rpx;
  color: #2e7d32;
  font-weight: 500;
}

/* ========== 按钮区域 ========== */
.button-section {
  padding: 0 32rpx;
}
</style>
