
<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>邮箱管理</h2>
    </div>

    <el-divider />

    <div class="content-box">
      <el-form
        ref="emailFormRef"
        :model="emailForm"
        :rules="emailRules"
        label-width="120px"
        class="email-form"
      >
        <el-form-item label="发件人邮箱" prop="fromAddress">
          <el-input
            v-model="emailForm.fromAddress"
            placeholder="如：noreply@example.com"
            clearable
          />
        </el-form-item>

        <el-form-item label="发件人名称" prop="fromName">
          <el-input
            v-model="emailForm.fromName"
            placeholder="如：官方网站"
            clearable
          />
        </el-form-item>

        <el-form-item label="SMTP 主机" prop="host">
          <el-input
            v-model="emailForm.host"
            placeholder="如：smtp.qq.com"
            clearable
          />
        </el-form-item>

        <el-form-item label="SMTP 端口" prop="port">
          <el-input
            v-model="emailForm.port"
            placeholder="如：465 或 587"
            clearable
          />
        </el-form-item>

        <!-- 用户名去掉，直接使用发件人邮箱作为登录账号 -->

        <el-form-item label="授权码/密码" prop="password">
          <el-input
            v-model="emailForm.password"
            type="password"
            show-password
            placeholder="邮箱授权码或登录密码"
            clearable
          />
        </el-form-item>

        <el-form-item label="加密方式" prop="encryption">
          <el-radio-group v-model="emailForm.encryption">
            <el-radio label="ssl">SSL</el-radio>
            <el-radio label="tls">TLS</el-radio>
            <el-radio label="none">不加密</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="超时时间(秒)" prop="timeout">
          <el-input
            v-model="emailForm.timeout"
            placeholder="默认 30 秒"
            clearable
          />
        </el-form-item>

        <el-form-item label="测试收件邮箱">
          <el-input
            v-model="testEmail"
            placeholder="输入一个邮箱地址用于测试发送"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSave">
            保存配置
          </el-button>
          <el-button @click="handleTest">
            发送测试邮件
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { getEmailInfo, editEmailInfo, sendTestEmail } from "@/api/email";

const emailFormRef = ref<FormInstance>();

/** 是否已有数据库中的配置（允许保存时不重复填写密码） */
const hasSavedConfig = ref(false);

const emailForm = reactive({
  fromAddress: "",
  fromName: "",
  host: "",
  port: "",
  password: "",
  encryption: "ssl",
  timeout: 30
});

const validatePassword = (
  _rule: unknown,
  value: string,
  callback: (e?: Error) => void
) => {
  if (!hasSavedConfig.value && !String(value || "").trim()) {
    callback(new Error("请输入授权码/密码"));
    return;
  }
  callback();
};

const emailRules: FormRules = {
  fromAddress: [
    { required: true, message: "请输入发件人邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
  ],
  host: [{ required: true, message: "请输入 SMTP 主机", trigger: "blur" }],
  port: [{ required: true, message: "请输入 SMTP 端口", trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }]
};

const testEmail = ref("");

const loadEmailConfig = async () => {
  const res = await getEmailInfo();
  if (res.code === 200 && Array.isArray(res.data) && res.data.length > 0) {
    hasSavedConfig.value = true;
    const item = res.data[0];
    emailForm.fromAddress = item.from_address || "";
    emailForm.fromName = item.from_name || "";
    emailForm.host = item.host || "";
    emailForm.port = item.port != null ? String(item.port) : "";
    emailForm.password = item.password || "";
    emailForm.encryption = item.encryption || "ssl";
    emailForm.timeout = item.timeout != null ? item.timeout : 30;
  } else {
    hasSavedConfig.value = false;
  }
};

const handleSave = async () => {
  if (!emailFormRef.value) return;
  try {
    await emailFormRef.value.validate();
  } catch {
    return;
  }
  try {
    const res = await editEmailInfo(emailForm);
    if (res.code === 200) {
      ElMessage.success("邮箱配置保存成功");
    } else {
      ElMessage.error(res.msg || "保存失败，请稍后重试");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "保存失败，请稍后重试");
  }
};

const handleTest = async () => {
  if (!testEmail.value) {
    ElMessage.warning("请先输入测试收件邮箱");
    return;
  }

  if (!emailFormRef.value) return;
  try {
    await emailFormRef.value.validate();
  } catch {
    return;
  }

  try {
    const res = await sendTestEmail({ ...emailForm, testEmail: testEmail.value });
    if (res.code === 200) {
      ElMessage.success("测试邮件发送成功");
    } else {
      ElMessage.error(res.msg || "测试邮件发送失败，请稍后重试");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "测试邮件发送失败，请稍后重试");
  }
};

const handleReset = () => {
  emailForm.fromAddress = "";
  emailForm.fromName = "";
  emailForm.host = "";
  emailForm.port = "";
  emailForm.password = "";
  emailForm.encryption = "ssl";
  emailForm.timeout = 30;
  testEmail.value = "";
  emailFormRef.value?.clearValidate();
};


onMounted(async () => {
  await loadEmailConfig();
});
</script>

<style scoped lang="less">
.container-box {
  padding: 20px;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }
}

.content-box {
  margin-top: 20px;
}

.email-form {
  max-width: 700px;
}
</style>