<template>
  <CommonRoot>
    <FlexCol height="100vh" :padding="30" backgroundColor="#f6f2e7">
      <Form 
        ref="formRef"
        :model="formModel"
        :rules="rules" 
        validateTrigger="submit"
        labelAlign="right"
        :labelWidth="140"
      >
        <!-- 头像 -->
        <view class="avatar-section">
          <button open-type="chooseAvatar" class="remove-button-style" @chooseavatar="handleChooseAvatar">
            <view class="avatar-container">
              <image 
                :src="formModel.avatar || DefaultAvatar" 
                class="avatar-image" 
                mode="aspectFill"
              />
              <text class="avatar-hint">点击可修改头像</text>
            </view>
          </button>
        </view>

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

      <Height :height="40" />

      <NaButton type="primary" :loading="loading" @click="submitForm" >
        保存修改
      </NaButton>
      <Height :height="20" />
      <NaButton type="primary" scheme="plain" @click="back()">
        返回
      </NaButton>
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useAuthStore } from '@/store/auth';
import { back } from '@/components/utils/PageAction';
import type { Rules } from 'async-validator';
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 NaButton from '@/components/basic/Button.vue';
import Height from '@/components/layout/space/Height.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import { toast } from '@/components/dialog/CommonRoot';

const DefaultAvatar = 'https://mncdn.wenlvti.net/app_static/minnan/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 handleChooseAvatar = async (e: { detail: { avatarUrl: string } }) => {
  try {
    uploading.value = true;
    const tempFilePath = e.detail.avatarUrl;
    // 上传图片
    const uploadResult = await CommonContent.uploadFile(tempFilePath, 'image');
    // 更新头像并保存到服务器
    await updateAvatar(uploadResult.fullurl);  
    toast({
      content: '头像更换成功',
      icon: 'success'
    });
  } catch (error: any) {
    console.error(error);
    if (error.errMsg !== 'chooseImage:fail cancel') {
      toast({
        content: '头像更换失败。' + error?.errMsg,
        icon: 'error',
        duration: 2000
      });
    }
  } finally {
    uploading.value = false;
  }
};
const updateAvatar = async (avatarUrl: string) => {
  try {
    await UserApi.updateUserInfo({
      avatar: avatarUrl
    });
    formModel.value.avatar = avatarUrl;
    if (authStore.userInfo) {
      authStore.userInfo.avatar = avatarUrl;
      authStore.saveLoginState();
    }
    toast({
      content: '头像更新成功',
      icon: 'success',
    });
    
  } catch (error: any) {
    throw new Error(error?.message || '头像更新失败');
  }
};

onMounted(() => {
  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.updateUserInfo({
      nickname: formModel.value.nickname,
      intro: formModel.value.bio
    });
    if (authStore.userInfo) {
      authStore.userInfo.nickname = formModel.value.nickname;
      authStore.userInfo.avatar = formModel.value.avatar;
      authStore.userInfo.intro = formModel.value.bio;
    }
    toast({
      content: '个人信息更新成功',
      icon: 'success',
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 2000);
    
  } catch (error: any) {
    toast({
      content: error?.message || '更新失败，请稍后重试',
      icon: 'error',
    });
  } 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>