<template>
  <div class="message-push-container">
    <vab-card title="消息推送配置">
      <el-tabs v-model="activeTab">
        <!-- Gateway Config -->
        <el-tab-pane label="推送通道配置" name="gateway">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="短信网关配置 (SMS)" name="sms">
              <el-form :model="smsForm" label-width="140px" class="mt-20">
                <el-form-item label="服务提供商">
                  <el-radio-group v-model="smsForm.provider">
                    <el-radio label="aliyun">阿里云</el-radio>
                    <el-radio label="tencent">腾讯云</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="AccessKey ID">
                  <el-input v-model="smsForm.accessKeyId" style="width: 400px" />
                </el-form-item>
                <el-form-item label="AccessKey Secret">
                  <el-input v-model="smsForm.accessKeySecret" type="password" show-password style="width: 400px" />
                </el-form-item>
                <el-form-item label="短信签名">
                  <el-input v-model="smsForm.signName" style="width: 400px" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSaveGateway">保存配置</el-button>
                  <el-button @click="handleTestSMS">发送测试短信</el-button>
                </el-form-item>
              </el-form>
            </el-collapse-item>
            
            <el-collapse-item title="邮件服务配置 (SMTP)" name="email">
              <el-form :model="emailForm" label-width="140px" class="mt-20">
                <el-form-item label="SMTP服务器">
                  <el-input v-model="emailForm.host" placeholder="smtp.exmail.qq.com" style="width: 400px" />
                </el-form-item>
                <el-form-item label="端口">
                  <el-input-number v-model="emailForm.port" :min="1" :max="65535" />
                </el-form-item>
                <el-form-item label="发件人邮箱">
                  <el-input v-model="emailForm.username" style="width: 400px" />
                </el-form-item>
                <el-form-item label="授权码/密码">
                  <el-input v-model="emailForm.password" type="password" show-password style="width: 400px" />
                </el-form-item>
                 <el-form-item>
                  <el-button type="primary" @click="handleSaveGateway">保存配置</el-button>
                  <el-button @click="handleTestEmail">发送测试邮件</el-button>
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>

        <!-- Template Config -->
        <el-tab-pane label="消息模板管理" name="template">
          <div class="mb-10">
            <el-button type="primary" @click="handleAddTemplate">
              <vab-icon icon="add-line" /> 新增模板
            </el-button>
          </div>
          <el-table :data="templateList" border stripe>
            <el-table-column prop="code" label="模板编码" width="150" />
            <el-table-column prop="name" label="模板名称" width="200" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getTypeTag(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="content" label="模板内容" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                 <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEditTemplate(row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDeleteTemplate(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </vab-card>

    <template-dialog ref="templateDialogRef" @success="handleTemplateSuccess" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TemplateDialog from './components/TemplateDialog.vue'

defineOptions({
  name: 'MessagePush',
})

const activeTab = ref('gateway')
const activeNames = ref(['sms', 'email'])
const templateDialogRef = ref()

const smsForm = reactive({
  provider: 'aliyun',
  accessKeyId: '',
  accessKeySecret: '',
  signName: '浙大公寓'
})

const emailForm = reactive({
  host: 'smtp.exmail.qq.com',
  port: 465,
  username: 'admin@zju.edu.cn',
  password: ''
})

const templateList = ref([
  { id: 1, code: 'CHECK_IN_SUCCESS', name: '入住办理成功通知', type: 'sms', content: '同学您好，您已成功办理入住，房间号为${room}，祝您生活愉快！', status: 1 },
  { id: 2, code: 'PAYMENT_REMINDER', name: '缴费提醒', type: 'sms', content: '同学您好，您的住宿费即将到期，请及时缴纳，以免影响住宿。', status: 1 },
  { id: 3, code: 'REPAIR_COMPLETE', name: '报修完成通知', type: 'site', content: '您的报修单${orderNo}已处理完成，请进行评价。', status: 1 },
])

const getTypeLabel = (type: string) => {
  const map: Record<string, string> = { sms: '短信', email: '邮件', site: '站内信' }
  return map[type] || type
}

const getTypeTag = (type: string) => {
  const map: Record<string, string> = { sms: 'success', email: 'warning', site: 'info' }
  return map[type]
}

const handleSaveGateway = () => {
  setTimeout(() => {
    ElMessage.success('配置保存成功')
  }, 500)
}

const handleTestSMS = () => {
  ElMessageBox.prompt('请输入测试手机号', '发送测试短信', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputPattern: /^1[3-9]\d{9}$/,
    inputErrorMessage: '手机号格式不正确',
  }).then(({ value }) => {
    ElMessage.success(`测试短信已发送至 ${value}`)
  })
}

const handleTestEmail = () => {
  ElMessageBox.prompt('请输入测试邮箱', '发送测试邮件', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    inputErrorMessage: '邮箱格式不正确',
  }).then(({ value }) => {
    ElMessage.success(`测试邮件已发送至 ${value}`)
  })
}

const handleAddTemplate = () => {
  templateDialogRef.value.open()
}

const handleEditTemplate = (row: any) => {
  templateDialogRef.value.open(row)
}

const handleDeleteTemplate = (row: any) => {
  ElMessageBox.confirm('确认删除该模板吗？', '提示', {
    type: 'warning',
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const handleStatusChange = (row: any) => {
  ElMessage.success('状态已更新')
}

const handleTemplateSuccess = () => {
  // Reload list
}
</script>

<style scoped>
.mt-20 { margin-top: 20px; }
.mb-10 { margin-bottom: 10px; }
</style>
