<template>
  <div class="notifications-container">
    <!-- 筛选和操作栏 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filters">
        <el-form-item label="搜索">
          <el-input v-model="filters.search" placeholder="标题/内容" clearable @keyup.enter="handleSearch" style="width: 180px" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="filters.type" placeholder="全部" clearable style="width: 120px">
            <el-option label="系统通知" value="system" />
            <el-option label="活动通知" value="activity" />
            <el-option label="服务通知" value="service" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.isRead" placeholder="全部" clearable style="width: 100px">
            <el-option label="未读" value="false" />
            <el-option label="已读" value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch"><el-icon><Search /></el-icon>搜索</el-button>
          <el-button @click="handleReset"><el-icon><Refresh /></el-icon>重置</el-button>
          <el-button type="success" @click="showSendDialog()"><el-icon><Plus /></el-icon>发送通知</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 通知列表 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="notifications" stripe border>
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)" size="small">{{ getTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="titleZh" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="contentZh" label="内容" min-width="250" show-overflow-tooltip />
        <el-table-column label="接收用户" width="150">
          <template #default="{ row }">
            <span v-if="row.user">{{ row.user.nickname || row.user.phone || '-' }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="isRead" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isRead ? 'success' : 'warning'" size="small">{{ row.isRead ? '已读' : '未读' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发送时间" width="170">
          <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button type="danger" link size="small" @click="handleDelete(row)"><el-icon><Delete /></el-icon>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.limit" :page-sizes="[10, 20, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange" @current-change="handlePageChange" />
      </div>
    </el-card>

    <!-- 发送通知弹窗 -->
    <el-dialog v-model="sendDialog.visible" title="发送通知" width="600px" destroy-on-close>
      <el-form ref="sendFormRef" :model="sendForm" :rules="currentRules" label-width="100px">
        <el-form-item label="发送模式" prop="sendMode">
          <el-radio-group v-model="sendForm.sendMode">
            <el-radio value="single">单发（指定用户）</el-radio>
            <el-radio value="broadcast">群发（所有用户）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="sendForm.sendMode === 'single'" label="用户UID" prop="uid">
          <el-input v-model="sendForm.uid" placeholder="请输入用户UID（6位数字）" maxlength="6" style="width: 100%" />
        </el-form-item>
        <el-form-item label="通知类型" prop="type">
          <el-select v-model="sendForm.type" style="width: 100%">
            <el-option label="系统通知" value="system" />
            <el-option label="活动通知" value="activity" />
            <el-option label="服务通知" value="service" />
          </el-select>
        </el-form-item>
        <el-divider content-position="left">中文内容（必填）</el-divider>
        <el-form-item label="中文标题" prop="titleZh">
          <el-input v-model="sendForm.titleZh" placeholder="请输入中文标题" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="中文内容" prop="contentZh">
          <el-input v-model="sendForm.contentZh" type="textarea" :rows="3" placeholder="请输入中文内容" maxlength="500" show-word-limit />
        </el-form-item>
        <el-divider content-position="left">英文内容（选填）</el-divider>
        <el-form-item label="英文标题">
          <el-input v-model="sendForm.titleEn" placeholder="English title (optional)" maxlength="100" />
        </el-form-item>
        <el-form-item label="英文内容">
          <el-input v-model="sendForm.contentEn" type="textarea" :rows="2" placeholder="English content (optional)" maxlength="500" />
        </el-form-item>
        <el-divider content-position="left">西语内容（选填）</el-divider>
        <el-form-item label="西语标题">
          <el-input v-model="sendForm.titlePt" placeholder="Título en español (opcional)" maxlength="100" />
        </el-form-item>
        <el-form-item label="西语内容">
          <el-input v-model="sendForm.contentPt" type="textarea" :rows="2" placeholder="Contenido en español (opcional)" maxlength="500" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="sendDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="sending" @click="handleSend">{{ sendForm.sendMode === 'broadcast' ? '群发' : '发送' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'

const loading = ref(false)
const sending = ref(false)
const notifications = ref([])
const sendFormRef = ref(null)

const pagination = reactive({ page: 1, limit: 20, total: 0 })
const filters = reactive({ search: '', type: '', isRead: '' })
const sendDialog = reactive({ visible: false })
const sendForm = reactive({ sendMode: 'single', uid: '', type: 'system', titleZh: '', titleEn: '', titlePt: '', contentZh: '', contentEn: '', contentPt: '' })
const sendRules = {
  uid: [
    { required: true, message: '请输入用户UID', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: 'UID必须是6位数字', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  titleZh: [{ required: true, message: '请输入中文标题', trigger: 'blur' }],
  contentZh: [{ required: true, message: '请输入中文内容', trigger: 'blur' }],
}
const broadcastRules = {
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  titleZh: [{ required: true, message: '请输入中文标题', trigger: 'blur' }],
  contentZh: [{ required: true, message: '请输入中文内容', trigger: 'blur' }],
}
const currentRules = computed(() => sendForm.sendMode === 'broadcast' ? broadcastRules : sendRules)

const getTypeTag = (type) => ({ system: 'primary', activity: 'success', service: 'warning' }[type] || 'info')
const getTypeLabel = (type) => ({ system: '系统', activity: '活动', service: '服务' }[type] || type)
const formatDate = (str) => str ? new Date(str).toLocaleString('zh-CN') : '-'

async function fetchNotifications() {
  loading.value = true
  try {
    const params = { page: pagination.page, limit: pagination.limit, ...filters }
    Object.keys(params).forEach(k => { if (!params[k]) delete params[k] })
    const res = await api.get('/api/v1/admin/notifications', { params })
    if (res.data.code === 0) {
      notifications.value = res.data.data
      pagination.total = res.data.pagination?.total || 0
    }
  } catch (e) { ElMessage.error('获取通知列表失败') }
  finally { loading.value = false }
}

function showSendDialog() {
  Object.assign(sendForm, { sendMode: 'single', uid: '', type: 'system', titleZh: '', titleEn: '', titlePt: '', contentZh: '', contentEn: '', contentPt: '' })
  sendDialog.visible = true
}

async function handleSend() {
  if (!sendFormRef.value) return
  try {
    await sendFormRef.value.validate()
  } catch { return }

  if (sendForm.sendMode === 'broadcast') {
    await ElMessageBox.confirm('确定要向所有用户发送此通知吗？', '确认群发', { type: 'warning' })
  }

  sending.value = true
  try {
    const url = sendForm.sendMode === 'broadcast' ? '/api/v1/admin/notifications/broadcast' : '/api/v1/admin/notifications/send'
    // 构建请求数据，单发时将uid作为userId发送
    const data = {
      type: sendForm.type,
      titleZh: sendForm.titleZh,
      titleEn: sendForm.titleEn,
      titlePt: sendForm.titlePt,
      contentZh: sendForm.contentZh,
      contentEn: sendForm.contentEn,
      contentPt: sendForm.contentPt,
    }
    if (sendForm.sendMode === 'single') {
      data.userId = sendForm.uid
    }
    const res = await api.post(url, data)
    if (res.data.code === 0) {
      ElMessage.success(sendForm.sendMode === 'broadcast' ? '群发成功' : '发送成功')
      sendDialog.visible = false
      fetchNotifications()
    }
  } catch (e) { ElMessage.error('发送失败') }
  finally { sending.value = false }
}

async function handleDelete(row) {
  await ElMessageBox.confirm('确定删除此通知？', '提示', { type: 'warning' })
  try {
    const res = await api.delete(`/api/v1/admin/notifications/${row.id}`)
    if (res.data.code === 0) {
      ElMessage.success('删除成功')
      fetchNotifications()
    }
  } catch (e) { ElMessage.error('删除失败') }
}

function handleSearch() { pagination.page = 1; fetchNotifications() }
function handleReset() { Object.assign(filters, { search: '', type: '', isRead: '' }); pagination.page = 1; fetchNotifications() }
function handlePageChange(page) { pagination.page = page; fetchNotifications() }
function handleSizeChange(size) { pagination.limit = size; pagination.page = 1; fetchNotifications() }

onMounted(() => { fetchNotifications() })
</script>

<style lang="scss" scoped>
.notifications-container {
  .filter-card { margin-bottom: 20px; }
  .table-card { .pagination-container { margin-top: 20px; display: flex; justify-content: flex-end; } }
}
</style>
