<template>
  <div class="sms-edit">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="sms-form"
    >
      <el-form-item label="短信网关地址" prop="backendUrl">
        <el-input
          v-model="form.backendUrl"
          placeholder="例如：https://yzsms.yunzer.cn"
          clearable
        />
      </el-form-item>

      <el-form-item label="短信API KEY" prop="apiKey">
        <el-input v-model="form.apiKey" placeholder="请输入 API_KEY" clearable />
      </el-form-item>

      <el-form-item label="测试收件手机号">
        <el-input
          v-model="testPhone"
          placeholder="国际格式号码，例如 +8613712345678"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">
          保存配置
        </el-button>
        <el-button @click="handleTest" :loading="testLoading">发送测试短信</el-button>
        <el-button @click="handleReset" :disabled="saveLoading || testLoading">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { editSmsInfo, sendTestSms } from "../../../../api/sms";

const props = defineProps<{
  config: {
    backendUrl?: string;
    apiKey?: string;
  };
}>();

const emit = defineEmits<{
  (e: "saved"): void;
  (e: "tested"): void;
}>();

const formRef = ref<FormInstance>();
const form = reactive({
  backendUrl: "",
  apiKey: "",
});

const rules: FormRules = {
  backendUrl: [{ required: true, message: "请输入短信网关地址", trigger: "blur" }],
  apiKey: [{ required: true, message: "请输入API KEY", trigger: "blur" }],
};

const testPhone = ref("");
const saveLoading = ref(false);
const testLoading = ref(false);

watch(
  () => props.config,
  (v) => {
    form.backendUrl = v?.backendUrl ?? "";
    form.apiKey = v?.apiKey ?? "";
  },
  { deep: true, immediate: true }
);

const handleSave = async () => {
  if (!formRef.value) return;
  try {
    saveLoading.value = true;
    await formRef.value.validate();
    const res = await editSmsInfo(form);
    if (res.code === 200) {
      ElMessage.success(res.msg || "短信配置保存成功");
      emit("saved");
    } else {
      ElMessage.error(res.msg || "保存失败，请稍后重试");
    }
  } catch (e: any) {
    ElMessage.error(e?.message || "保存失败，请稍后重试");
  } finally {
    saveLoading.value = false;
  }
};

const handleTest = async () => {
  const phone = (testPhone.value || "").trim();
  if (!phone) {
    ElMessage.warning("请先输入测试收件手机号");
    return;
  }
  // Android 网关要求国际格式：以 + 开头，后面为数字
  if (!/^\+\d{6,15}$/.test(phone)) {
    ElMessage.warning("请使用国际格式号码（以 + 开头，后面为数字）");
    return;
  }

  if (!formRef.value) return;
  try {
    testLoading.value = true;
    await formRef.value.validate();
    const res = await sendTestSms({ ...form, phone });
    if (res.code === 200) {
      ElMessage.success(res.msg || "短信测试任务入队成功");
      emit("tested");
    } else {
      ElMessage.error(res.msg || "短信测试失败，请稍后重试");
    }
  } catch (e: any) {
    ElMessage.error(e?.message || "短信测试失败，请稍后重试");
  } finally {
    testLoading.value = false;
  }
};

const handleReset = () => {
  form.backendUrl = "";
  form.apiKey = "";
  testPhone.value = "";
  formRef.value?.clearValidate();
};
</script>

<style scoped lang="less">
.sms-edit {
  max-width: 700px;
}

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