<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import type { UserProfile } from '@/api/profile/types';

import { ElMessage } from 'element-plus';
import { userProfileUpdate } from '@/api/profile';
import { useUserStore } from '@/stores';

const props = defineProps<{ profile?: UserProfile }>();
const emit = defineEmits<{ update: [] }>();

const userStore = useUserStore();
const formRef = ref<FormInstance>();
const loading = ref(false);

const formData = reactive({
  userId: 0,
  nickName: '',
  email: '',
  phonenumber: '',
  sex: '0',
});

const rules: FormRules = {
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phonenumber: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
};

// 监听profile变化，更新表单数据
watch(() => props.profile, (newProfile) => {
  if (newProfile?.user) {
    formData.userId = newProfile.user.userId;
    formData.nickName = newProfile.user.nickName;
    formData.email = newProfile.user.email || '';
    formData.phonenumber = newProfile.user.phonenumber || '';
    formData.sex = newProfile.user.sex || '0';
  }
}, { immediate: true });

async function handleSubmit() {
  if (!formRef.value)
    return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const res = await userProfileUpdate(formData);
        if (res instanceof Error)
          return;
        ElMessage.success('修改成功');
        emit('update');
      }
      catch {
        // 拦截器已显示错误信息
      }
      finally {
        loading.value = false;
      }
    }
  });
}

function resetForm() {
  if (props.profile?.user) {
    formData.userId = props.profile.user.userId;
    formData.nickName = props.profile.user.nickName;
    formData.email = props.profile.user.email || '';
    formData.phonenumber = props.profile.user.phonenumber || '';
    formData.sex = props.profile.user.sex || '0';
  }
}
</script>

<template>
  <div class="basic-setting">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
      class="setting-form"
    >
      <el-form-item v-show="false" label="用户ID" prop="userId">
        <el-input v-model="formData.userId" />
      </el-form-item>

      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="formData.nickName" placeholder="请输入昵称" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formData.sex">
          <el-radio value="0">
            男
          </el-radio>
          <el-radio value="1">
            女
          </el-radio>
          <el-radio value="2">
            保密
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model="formData.phonenumber" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          保存修改
        </el-button>
        <el-button @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.basic-setting {
  padding: 16px 0;
}

.setting-form {
  max-width: 600px;
}
</style>
