<template>
  <PageContainer title="通知网关配置">
    <QueryToolbar>
      <el-button v-if="canRead" @click="load">刷新配置</el-button>
    </QueryToolbar>

    <el-alert
      v-if="!canRead"
      title="当前账号无查看平台通知网关配置权限"
      type="warning"
      show-icon
      :closable="false"
      class="mb-md"
    />

    <el-tabs v-else v-model="activeTab">
      <el-tab-pane label="邮件网关" name="EMAIL">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <div>
                <div class="card-title">SMTP / 邮件发送配置</div>
                <div class="card-subtitle">配置完成后，通知邮件和租户管理员账号邮件都会优先读取这里的网关参数。</div>
              </div>
              <el-tag :type="emailForm.status === 'ENABLED' ? 'success' : 'info'">{{ emailForm.status === "ENABLED" ? "已启用" : "未启用" }}</el-tag>
            </div>
          </template>

          <div class="autofill-decoy" aria-hidden="true">
            <input type="text" name="username" autocomplete="username" tabindex="-1" />
            <input type="password" name="password" autocomplete="current-password" tabindex="-1" />
          </div>

          <el-form :model="emailForm" label-position="left" :label-width="LABEL_WIDTH.lg" class="gateway-form" autocomplete="off">
            <el-form-item label="网关名称">
              <el-input v-model="emailForm.gatewayName" placeholder="例如 企业邮件网关" />
            </el-form-item>
            <el-form-item label="Provider">
              <el-input v-model="emailForm.providerCode" placeholder="SMTP" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="emailForm.status" class="w-full">
                <el-option label="启用" value="ENABLED" />
                <el-option label="停用" value="DISABLED" />
              </el-select>
            </el-form-item>
            <el-form-item label="SMTP Host">
              <el-input v-model="emailForm.host" placeholder="例如 smtp.qq.com" />
            </el-form-item>
            <el-form-item label="SMTP Port">
              <el-input-number v-model="emailForm.port" :min="1" :max="65535" />
            </el-form-item>
            <el-form-item label="用户名">
              <el-input
                v-model="emailForm.username"
                name="notify-gateway-email-username"
                autocomplete="off"
                spellcheck="false"
                :readonly="emailCredentialReadonly"
                placeholder="通常为邮箱账号"
                @focus="unlockEmailCredentialInputs"
              />
            </el-form-item>
            <el-form-item label="密码 / 授权码">
              <el-input
                v-model="emailForm.password"
                name="notify-gateway-email-password"
                autocomplete="new-password"
                :readonly="emailCredentialReadonly"
                show-password
                placeholder="保存时将加密落库"
                @focus="unlockEmailCredentialInputs"
              />
            </el-form-item>
            <el-form-item label="协议">
              <el-input v-model="emailForm.protocol" placeholder="smtp" />
            </el-form-item>
            <el-form-item label="发件邮箱">
              <el-input v-model="emailForm.fromAddress" placeholder="例如 no-reply@company.com" />
            </el-form-item>
            <el-form-item label="默认主题">
              <el-input v-model="emailForm.defaultSubject" placeholder="系统通知" />
            </el-form-item>
            <el-form-item label="SMTP Auth">
              <el-switch v-model="emailForm.smtpAuth" />
            </el-form-item>
            <el-form-item label="STARTTLS">
              <el-switch v-model="emailForm.starttlsEnable" />
            </el-form-item>
            <el-form-item label="STARTTLS Required">
              <el-switch v-model="emailForm.starttlsRequired" />
            </el-form-item>
            <el-form-item label="SSL">
              <el-switch v-model="emailForm.sslEnable" />
            </el-form-item>
            <el-form-item label="连接超时(ms)">
              <el-input-number v-model="emailForm.connectTimeoutMs" :min="1000" :step="1000" />
            </el-form-item>
            <el-form-item label="读取超时(ms)">
              <el-input-number v-model="emailForm.timeoutMs" :min="1000" :step="1000" />
            </el-form-item>
            <el-form-item label="写入超时(ms)">
              <el-input-number v-model="emailForm.writeTimeoutMs" :min="1000" :step="1000" />
            </el-form-item>
            <el-form-item label="熔断阈值">
              <el-input-number v-model="emailForm.failureThreshold" :min="1" :step="1" />
            </el-form-item>
            <el-form-item label="熔断冷却(s)">
              <el-input-number v-model="emailForm.breakerCooldownSeconds" :min="1" :step="30" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="emailForm.remark" type="textarea" :rows="2" />
            </el-form-item>
          </el-form>

          <div class="action-row">
            <el-button v-if="canManage" type="primary" @click="handleSaveEmail">保存邮件网关</el-button>
          </div>

          <el-divider />

          <div class="test-block">
            <div class="test-title">连通性测试</div>
            <el-form :model="emailForm" label-position="left" :label-width="LABEL_WIDTH.lg">
              <el-form-item label="测试收件人">
                <el-input v-model="emailForm.testReceiverRef" placeholder="例如 test@example.com" />
              </el-form-item>
              <el-form-item label="测试主题">
                <el-input v-model="emailForm.testSubject" placeholder="通知网关测试" />
              </el-form-item>
              <el-form-item label="测试内容">
                <el-input v-model="emailForm.testContent" type="textarea" :rows="3" />
              </el-form-item>
            </el-form>
            <el-button v-if="canManage" @click="handleTestEmail">发送测试邮件</el-button>
          </div>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="短信网关" name="SMS">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <div>
                <div class="card-title">短信网关配置</div>
                <div class="card-subtitle">当前版本支持平台统一保存短信参数，并提供参数校验/模拟受理测试。</div>
              </div>
              <el-tag :type="smsForm.status === 'ENABLED' ? 'success' : 'info'">{{ smsForm.status === "ENABLED" ? "已启用" : "未启用" }}</el-tag>
            </div>
          </template>

          <el-alert
            title="短信供应商回执适配入口：POST /api/notifications/receipts/providers/aliyun-sms，支持单条 JSON、JSON 数组与表单参数回调。"
            type="info"
            show-icon
            :closable="false"
            class="mb-md"
          />

          <div class="autofill-decoy" aria-hidden="true">
            <input type="text" name="username" autocomplete="username" tabindex="-1" />
            <input type="password" name="password" autocomplete="current-password" tabindex="-1" />
          </div>

          <el-form :model="smsForm" label-position="left" :label-width="LABEL_WIDTH.lg" class="gateway-form" autocomplete="off">
            <el-form-item label="网关名称">
              <el-input v-model="smsForm.gatewayName" placeholder="例如 阿里云短信" />
            </el-form-item>
            <el-form-item label="Provider">
              <el-select v-model="smsForm.providerCode" class="w-full">
                <el-option label="MOCK" value="MOCK" />
                <el-option label="ALIYUN_SMS" value="ALIYUN_SMS" />
                <el-option label="CUSTOM_SMS" value="CUSTOM_SMS" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="smsForm.status" class="w-full">
                <el-option label="启用" value="ENABLED" />
                <el-option label="停用" value="DISABLED" />
              </el-select>
            </el-form-item>
            <el-form-item label="模拟模式">
              <el-switch v-model="smsForm.mockEnabled" />
            </el-form-item>
            <el-form-item label="服务地址">
              <el-input v-model="smsForm.endpoint" placeholder="例如 dysmsapi.aliyuncs.com" />
            </el-form-item>
            <el-form-item label="AccessKeyId">
              <el-input
                v-model="smsForm.accessKeyId"
                name="notify-gateway-sms-access-key-id"
                autocomplete="off"
                spellcheck="false"
                :readonly="smsCredentialReadonly"
                placeholder="保存时将加密落库"
                @focus="unlockSmsCredentialInputs"
              />
            </el-form-item>
            <el-form-item label="AccessKeySecret">
              <el-input
                v-model="smsForm.accessKeySecret"
                name="notify-gateway-sms-access-key-secret"
                autocomplete="new-password"
                :readonly="smsCredentialReadonly"
                show-password
                placeholder="保存时将加密落库"
                @focus="unlockSmsCredentialInputs"
              />
            </el-form-item>
            <el-form-item label="RegionId">
              <el-input v-model="smsForm.regionId" placeholder="例如 cn-hangzhou" />
            </el-form-item>
            <el-form-item label="短信签名">
              <el-input v-model="smsForm.signName" placeholder="例如 会议核销系统" />
            </el-form-item>
            <el-form-item label="模板编码">
              <el-input v-model="smsForm.templateCode" placeholder="例如 SMS_0000001" />
            </el-form-item>
            <el-form-item label="静默窗口(s)">
              <el-input-number v-model="smsForm.quietPeriodSeconds" :min="0" :step="5" />
            </el-form-item>
            <el-form-item label="单日上限">
              <el-input-number v-model="smsForm.dailyLimit" :min="1" :step="1" />
            </el-form-item>
            <el-form-item label="熔断阈值">
              <el-input-number v-model="smsForm.failureThreshold" :min="1" :step="1" />
            </el-form-item>
            <el-form-item label="熔断冷却(s)">
              <el-input-number v-model="smsForm.breakerCooldownSeconds" :min="1" :step="30" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="smsForm.remark" type="textarea" :rows="2" />
            </el-form-item>
          </el-form>

          <div class="action-row">
            <el-button v-if="canManage" type="primary" @click="handleSaveSms">保存短信网关</el-button>
          </div>

          <el-divider />

          <div class="test-block">
            <div class="test-title">连通性测试</div>
            <el-form :model="smsForm" label-position="left" :label-width="LABEL_WIDTH.lg">
              <el-form-item label="测试手机号">
                <el-input v-model="smsForm.testReceiverRef" placeholder="例如 13800138000" />
              </el-form-item>
              <el-form-item label="测试主题">
                <el-input v-model="smsForm.testSubject" placeholder="通知网关测试" />
              </el-form-item>
              <el-form-item label="测试内容">
                <el-input v-model="smsForm.testContent" type="textarea" :rows="3" />
              </el-form-item>
            </el-form>
            <el-button v-if="canManage" @click="handleTestSms">发送测试短信</el-button>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import { LABEL_WIDTH } from "../../constants/ui";
import { fetchPlatformNotifyGateways, savePlatformNotifyGateway, testPlatformNotifyGateway } from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";

type GatewayRow = {
  channelCode: "EMAIL" | "SMS";
  gatewayName: string;
  providerCode: string;
  status: "ENABLED" | "DISABLED";
  remark?: string;
  config?: Record<string, any>;
};

const authStore = useAuthStore();
const canRead = computed(() => authStore.hasPermission(PERMS.platform.notifyGatewayRead));
const canManage = computed(() => authStore.hasPermission(PERMS.platform.notifyGatewayManage));
const activeTab = ref<"EMAIL" | "SMS">("EMAIL");
const emailCredentialReadonly = ref(true);
const smsCredentialReadonly = ref(true);

const unlockEmailCredentialInputs = () => {
  emailCredentialReadonly.value = false;
};

const unlockSmsCredentialInputs = () => {
  smsCredentialReadonly.value = false;
};

const emailForm = ref({
  gatewayName: "邮件网关",
  providerCode: "SMTP",
  status: "DISABLED" as "ENABLED" | "DISABLED",
  host: "",
  port: 587,
  username: "",
  password: "",
  protocol: "smtp",
  fromAddress: "",
  defaultSubject: "系统通知",
  smtpAuth: true,
  starttlsEnable: true,
  starttlsRequired: false,
  sslEnable: false,
  connectTimeoutMs: 5000,
  timeoutMs: 5000,
  writeTimeoutMs: 5000,
  failureThreshold: 3,
  breakerCooldownSeconds: 300,
  remark: "",
  testReceiverRef: "",
  testSubject: "通知网关测试",
  testContent: "这是一封来自平台通知网关配置中心的测试邮件。",
});

const smsForm = ref({
  gatewayName: "短信网关",
  providerCode: "MOCK",
  status: "DISABLED" as "ENABLED" | "DISABLED",
  endpoint: "",
  accessKeyId: "",
  accessKeySecret: "",
  signName: "",
  templateCode: "",
  regionId: "cn-hangzhou",
  mockEnabled: true,
  quietPeriodSeconds: 30,
  dailyLimit: 10,
  failureThreshold: 3,
  breakerCooldownSeconds: 300,
  remark: "",
  testReceiverRef: "",
  testSubject: "通知网关测试",
  testContent: "这是一条来自平台通知网关配置中心的测试短信。",
});

const applyGatewayRows = (rows: GatewayRow[]) => {
  const email = rows.find((item) => item.channelCode === "EMAIL");
  const sms = rows.find((item) => item.channelCode === "SMS");
  if (email) {
    emailForm.value = {
      ...emailForm.value,
      gatewayName: email.gatewayName || "邮件网关",
      providerCode: email.providerCode || "SMTP",
      status: email.status || "DISABLED",
      host: String(email.config?.host || ""),
      port: Number(email.config?.port || 587),
      username: String(email.config?.username || ""),
      password: String(email.config?.password || ""),
      protocol: String(email.config?.protocol || "smtp"),
      fromAddress: String(email.config?.fromAddress || ""),
      defaultSubject: String(email.config?.defaultSubject || "系统通知"),
      smtpAuth: !!email.config?.smtpAuth,
      starttlsEnable: email.config?.starttlsEnable !== false,
      starttlsRequired: !!email.config?.starttlsRequired,
      sslEnable: !!email.config?.sslEnable,
      connectTimeoutMs: Number(email.config?.connectTimeoutMs || 5000),
      timeoutMs: Number(email.config?.timeoutMs || 5000),
      writeTimeoutMs: Number(email.config?.writeTimeoutMs || 5000),
      failureThreshold: Number(email.config?.failureThreshold || 3),
      breakerCooldownSeconds: Number(email.config?.breakerCooldownSeconds || 300),
      remark: String(email.remark || ""),
    };
  }
  if (sms) {
    smsForm.value = {
      ...smsForm.value,
      gatewayName: sms.gatewayName || "短信网关",
      providerCode: sms.providerCode || "MOCK",
      status: sms.status || "DISABLED",
      endpoint: String(sms.config?.endpoint || ""),
      accessKeyId: String(sms.config?.accessKeyId || ""),
      accessKeySecret: String(sms.config?.accessKeySecret || ""),
      signName: String(sms.config?.signName || ""),
      templateCode: String(sms.config?.templateCode || ""),
      regionId: String(sms.config?.regionId || "cn-hangzhou"),
      mockEnabled: sms.config?.mockEnabled !== false,
      quietPeriodSeconds: Number(sms.config?.quietPeriodSeconds || 30),
      dailyLimit: Number(sms.config?.dailyLimit || 10),
      failureThreshold: Number(sms.config?.failureThreshold || 3),
      breakerCooldownSeconds: Number(sms.config?.breakerCooldownSeconds || 300),
      remark: String(sms.remark || ""),
    };
  }
};

const load = async () => {
  if (!canRead.value) {
    return;
  }
  const resp = await fetchPlatformNotifyGateways();
  applyGatewayRows(Array.isArray(resp?.data) ? resp.data : []);
  emailCredentialReadonly.value = true;
  smsCredentialReadonly.value = true;
};

const handleSaveEmail = async () => {
  await savePlatformNotifyGateway("EMAIL", {
    gatewayName: emailForm.value.gatewayName.trim(),
    providerCode: emailForm.value.providerCode.trim() || "SMTP",
    status: emailForm.value.status,
    remark: emailForm.value.remark.trim() || undefined,
    config: {
      host: emailForm.value.host.trim(),
      port: emailForm.value.port,
      username: emailForm.value.username.trim(),
      password: emailForm.value.password,
      protocol: emailForm.value.protocol.trim() || "smtp",
      fromAddress: emailForm.value.fromAddress.trim(),
      defaultSubject: emailForm.value.defaultSubject.trim() || "系统通知",
      smtpAuth: emailForm.value.smtpAuth,
      starttlsEnable: emailForm.value.starttlsEnable,
      starttlsRequired: emailForm.value.starttlsRequired,
      sslEnable: emailForm.value.sslEnable,
      connectTimeoutMs: emailForm.value.connectTimeoutMs,
      timeoutMs: emailForm.value.timeoutMs,
      writeTimeoutMs: emailForm.value.writeTimeoutMs,
      failureThreshold: emailForm.value.failureThreshold,
      breakerCooldownSeconds: emailForm.value.breakerCooldownSeconds,
    },
  });
  ElMessage.success("邮件网关配置已保存");
  await load();
};

const handleSaveSms = async () => {
  await savePlatformNotifyGateway("SMS", {
    gatewayName: smsForm.value.gatewayName.trim(),
    providerCode: smsForm.value.providerCode.trim() || "MOCK",
    status: smsForm.value.status,
    remark: smsForm.value.remark.trim() || undefined,
    config: {
      endpoint: smsForm.value.endpoint.trim(),
      accessKeyId: smsForm.value.accessKeyId.trim(),
      accessKeySecret: smsForm.value.accessKeySecret,
      signName: smsForm.value.signName.trim(),
      templateCode: smsForm.value.templateCode.trim(),
      regionId: smsForm.value.regionId.trim() || "cn-hangzhou",
      mockEnabled: smsForm.value.mockEnabled,
      quietPeriodSeconds: smsForm.value.quietPeriodSeconds,
      dailyLimit: smsForm.value.dailyLimit,
      failureThreshold: smsForm.value.failureThreshold,
      breakerCooldownSeconds: smsForm.value.breakerCooldownSeconds,
    },
  });
  ElMessage.success("短信网关配置已保存");
  await load();
};

const handleTestEmail = async () => {
  await testPlatformNotifyGateway("EMAIL", {
    receiverRef: emailForm.value.testReceiverRef.trim(),
    subject: emailForm.value.testSubject.trim(),
    content: emailForm.value.testContent.trim(),
  });
  ElMessage.success("测试邮件已发送");
};

const handleTestSms = async () => {
  const resp = await testPlatformNotifyGateway("SMS", {
    receiverRef: smsForm.value.testReceiverRef.trim(),
    subject: smsForm.value.testSubject.trim(),
    content: smsForm.value.testContent.trim(),
  });
  ElMessage.success(String(resp?.data?.message || "测试短信已受理"));
};

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

<style scoped>
.card-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #111827;
}

.card-subtitle {
  margin-top: 6px;
  color: #6b7280;
  font-size: 13px;
  line-height: 1.5;
}

.gateway-form {
  max-width: 760px;
}

.autofill-decoy {
  position: absolute;
  left: -9999px;
  width: 1px;
  height: 1px;
  overflow: hidden;
  opacity: 0;
  pointer-events: none;
}

.autofill-decoy input {
  width: 1px;
  height: 1px;
  padding: 0;
  border: 0;
}

.action-row {
  margin-top: 8px;
}

.test-block {
  max-width: 760px;
}

.test-title {
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #111827;
}
</style>
