<template>
  <el-dialog
    v-model="visible"
    :title="userInfo?.email ? '更换邮箱' : '绑定邮箱'"
    width="450px"
    @close="handleDialogClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="90px"
    >
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { bindEmail } from "@/api/user";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  userInfo: {
    type: Object,
    default: null
  },
  userId: {
    type: [Number, String],
    default: ""
  }
});

const emit = defineEmits(["update:modelValue", "saved"]);

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value)
});

const loading = ref(false);
const formRef = ref(null);

const form = reactive({
  email: ""
});

const formRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ]
};

const syncForm = () => {
  form.email = props.userInfo?.email || "";
};

const handleSave = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    const res = await bindEmail(props.userId, form.email);

    if (res.code === 200) {
      ElMessage.success(props.userInfo?.email ? "邮箱更换成功" : "邮箱绑定成功");
      visible.value = false;
      emit("saved");
    }
  } catch (error) {
    console.error("保存邮箱失败", error);
    if (error !== false) {
      ElMessage.error("保存邮箱失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleDialogClose = () => {
  formRef.value?.resetFields();
};

watch(
  () => props.modelValue,
  (value) => {
    if (value) {
      syncForm();
    }
  }
);
</script>
