<template>
  <FlexCol :padding="30">
    <Form 
      ref="formRef"
      :model="formModel"
      :rules="rules" 
      validateTrigger="submit"
      labelAlign="right"
      :labelWidth="140"
    >
      <!-- 头像 -->
      <view class="avatar-section">
        <view class="avatar-container" @click="handleAvatarClick">
          <image 
            :src="formModel.avatar || DefaultAvatar" 
            class="avatar-image" 
            mode="aspectFill"
          ></image>
          <text class="avatar-hint">点击可修改头像</text>
        </view>
      </view>

      <Field name="nickname" label="昵称" placeholder="请输入昵称" required />
      <Field name="bio" multiline label="个人简介" placeholder="输入个人简介" :inputStyle="{width: '240px'}" />
    </Form>

    <Height :height="40" />

    <Button type="primary" :loading="loading" @click="submitForm" >
      保存修改
    </Button>
    <Height :height="20" />
    <Button :plain="true" @click="navTo('/pages/user/update/password')">
      修改密码
    </Button>
  </FlexCol>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useAuthStore } from '@/store/auth';
import UserApi from '@/api/auth/UserApi';
import CommonContent from '@/api/CommonContent';
import Form from '@/components/form/Form.vue';
import Field from '@/components/form/Field.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import Button from '@/components/basic/Button.vue';
import Height from '@/components/layout/space/Height.vue';
import type { Rules } from 'async-validator';
import { navTo } from '@/components/utils/PageAction';

const DefaultAvatar = 'https://mncdn.wenlvti.net/app_static/xiangyuan/images/home/UserHead.png';

const authStore = useAuthStore();
const formRef = ref<any>(null);
const loading = ref(false);
const uploading = ref(false);

const formModel = ref({
  avatar: '',
  nickname: '',
  bio: '',
});
const rules : Rules = {
  nickname: [
    { required: true, message: '请输入昵称' },
    { min: 2, message: '昵称长度至少2个字符' },
    { max: 20, message: '昵称长度最多20个字符' }
  ],
  bio: [
    { max: 100, message: '个人简介最多100个字符' }
  ],
};

// 处理头像点击事件
const handleAvatarClick = async () => {
  try {
    // 选择图片
    const chooseResult = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
    });
    
    const tempFilePath = chooseResult.tempFilePaths[0];
    
    // 上传图片
    uploading.value = true;
    const uploadResult = await CommonContent.uploadFile(tempFilePath, 'image');
    
    // 更新头像并保存到服务器
    await updateAvatar(uploadResult.fullurl);
    
  } catch (error: any) {
    if (error.errMsg !== 'chooseImage:fail cancel') {
      uni.showToast({
        title: '头像更换失败',
        icon: 'none',
        duration: 2000
      });
    }
  } finally {
    uploading.value = false;
  }
};
// 更新头像到服务器
const updateAvatar = async (avatarUrl: string) => {
  try {
    await UserApi.updateSystemUserInfo({
      avatar: avatarUrl
    });
    formModel.value.avatar = avatarUrl;
    if (authStore.userInfo) {
      authStore.userInfo.avatar = avatarUrl;
      authStore.saveLoginState();
    }
    uni.showToast({
      title: '头像更新成功',
      icon: 'success',
      duration: 2000
    });
    
  } catch (error: any) {
    throw new Error(error?.message || '头像更新失败');
  }
};

onMounted(() => {
  console.log(authStore.userInfo);
  if (authStore.userInfo) {
    formModel.value.avatar = authStore.userInfo.avatar || '';
    formModel.value.nickname = authStore.userInfo.nickname || '';
    formModel.value.bio = (authStore.userInfo.intro || authStore.userInfo.bio || '') as string;
  }
});

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value?.validate();
  } catch {
    return;
  }
  
  loading.value = true;
  
  try {
    await UserApi.updateSystemUserInfo({
      nickname: formModel.value.nickname,
      bio: formModel.value.bio
    });
    if (authStore.userInfo) {
      authStore.userInfo.nickname = formModel.value.nickname;
      authStore.userInfo.avatar = formModel.value.avatar;
      authStore.userInfo.intro = formModel.value.bio;
    }
    uni.showToast({
      title: '个人信息更新成功',
      icon: 'success',
      duration: 2000
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 2000);
    
  } catch (error: any) {
    uni.showToast({
      title: error?.message || '更新失败，请稍后重试',
      icon: 'none',
      duration: 2000
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.avatar-section {
  text-align: center;
}

.avatar-label {
  font-size: 14px;
  color: #333333;
  margin-bottom: 12px;
  font-weight: 500;
  text-align: left;
}

.avatar-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 18px;
}

.avatar-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid #e0e0e0;
  background-color: #f5f5f5;
}
.avatar-hint {
  font-size: 12px;
  color: #007aff;
  margin-top: 4px;
}

/* 上传中遮罩 */
.uploading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
.uploading-content {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}
.uploading-content uni-loading {
  margin-bottom: 10px;
}
</style>