<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { Modal, Form, Input, Upload, message } from 'ant-design-vue';
import { useAppConfig } from '@vben/hooks';
import { getProfileInfoApi, updateProfileApi, type ProfileApi } from '#/api/admin/profile';
import { useUserStore } from '@vben/stores';

const props = defineProps<{
  open: boolean;
}>();

const emit = defineEmits<{
  'update:open': [value: boolean];
}>();

const formRef = ref();
const loading = ref(false);
const userStore = useUserStore();
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

const formData = ref<{
  nickname: string;
  email: string;
  avatar?: string;
  avatarFile?: File;
}>({
  nickname: '',
  email: '',
  avatar: '',
});

const fileList = ref<any[]>([]);

// 获取完整的头像URL
const getAvatarUrl = (avatarPath?: string | null): string => {
  if (!avatarPath) return '';
  // 如果已经是完整URL，直接返回
  if (avatarPath.startsWith('http://') || avatarPath.startsWith('https://')) {
    return avatarPath;
  }
  // 拼接完整的URL
  // apiURL 是字符串，不是 ref，所以不需要 .value
  if (!apiURL) {
    console.warn('apiURL is not configured');
    return avatarPath;
  }
  const baseUrl = apiURL.replace(/\/$/, '');
  const path = avatarPath.startsWith('/') ? avatarPath : `/${avatarPath}`;
  return `${baseUrl}${path}`;
};

// 获取个人信息
async function loadProfileInfo() {
  try {
    loading.value = true;
    const res = await getProfileInfoApi();

    // 检查返回的数据
    if (!res) {
      throw new Error('返回数据为空');
    }

    formData.value = {
      nickname: res.nickname || '',
      email: res.email || '',
      avatar: res.avatar || '',
    };
    if (res.avatar) {
      const avatarUrl = getAvatarUrl(res.avatar);
      fileList.value = [
        {
          uid: '-1',
          name: 'avatar',
          status: 'done',
          url: avatarUrl,
        },
      ];
    } else {
      fileList.value = [];
    }
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取个人信息失败';
    message.error(errorMessage);
  } finally {
    loading.value = false;
  }
}

// 监听对话框打开
watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      loadProfileInfo();
    } else {
      // 关闭时重置表单
      formRef.value?.resetFields();
      fileList.value = [];
    }
  },
);

// 处理头像上传前
function beforeUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件！');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！');
    return false;
  }
  formData.value.avatarFile = file;

  // 生成预览
  const reader = new FileReader();
  reader.onload = (e) => {
    const previewUrl = e.target?.result as string;
    fileList.value = [
      {
        uid: Date.now().toString(),
        name: file.name,
        status: 'done',
        url: previewUrl,
        originFileObj: file,
      },
    ];
  };
  reader.readAsDataURL(file);

  return false; // 阻止自动上传
}

// 处理头像上传变化
function handleAvatarChange(info: any) {
  if (info.file.status === 'removed') {
    fileList.value = [];
    formData.value.avatarFile = undefined;
    formData.value.avatar = '';
  }
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value?.validate();
    loading.value = true;

    const params: ProfileApi.UpdateProfileParams = {
      nickname: formData.value.nickname,
      email: formData.value.email || undefined, // 如果为空字符串，传 undefined
    };

    // 只有选择了新文件才上传
    if (formData.value.avatarFile) {
      params.avatar = formData.value.avatarFile;
    }

    const res = await updateProfileApi(params);
    message.success('个人信息更新成功');

    // 更新用户信息
    if (userStore.userInfo) {
      userStore.userInfo.nickname = formData.value.nickname;
      userStore.userInfo.email = formData.value.email || null;
      // 更新后重新获取数据以获取最新的头像路径
      if (res?.avatar) {
        userStore.userInfo.avatar = res.avatar;
        // 更新文件列表中的头像URL
        const avatarUrl = getAvatarUrl(res.avatar);
        if (fileList.value.length > 0) {
          fileList.value[0].url = avatarUrl;
        }
      }
    }

    emit('update:open', false);
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return;
    }
    message.error(error?.message || '更新个人信息失败');
  } finally {
    loading.value = false;
  }
}

function handleCancel() {
  emit('update:open', false);
}
</script>

<template>
  <Modal
    :open="open"
    title="个人信息"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="600px"
  >
    <Form
      ref="formRef"
      :model="formData"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <Form.Item
        label="昵称"
        name="nickname"
        :rules="[{ required: true, message: '请输入昵称' }]"
      >
        <Input
          v-model:value="formData.nickname"
          placeholder="请输入昵称"
        />
      </Form.Item>
      <Form.Item
        label="邮箱"
        name="email"
        :rules="[
          { type: 'email', message: '请输入正确的邮箱格式' },
        ]"
      >
        <Input
          v-model:value="formData.email"
          placeholder="请输入邮箱（可选）"
        />
      </Form.Item>
      <Form.Item label="头像" name="avatar">
        <Upload
          v-model:file-list="fileList"
          list-type="picture-card"
          :max-count="1"
          :before-upload="beforeUpload"
          @change="handleAvatarChange"
          accept="image/*"
        >
          <div v-if="fileList.length < 1">
            <div style="margin-top: 8px">
              <span>上传</span>
            </div>
          </div>
        </Upload>
      </Form.Item>
    </Form>
  </Modal>
</template>

