<template>
  <div class="notif-page">
    <el-card shadow="never" class="tabs-card">
      <div class="n-tabs">
        <div v-for="t in tabs" :key="t.key" class="n-tab" :class="{active:aT===t.key}" @click="switchTab(t.key)"><span>{{ t.icon }}</span>{{ t.label }}</div>
      </div>
    </el-card>

    <!-- 模板管理 -->
    <div v-show="aT==='templates'">
      <el-card shadow="never">
        <el-table :data="tmplList" border v-loading="tmplLoad" style="width:100%">
          <el-table-column label="模板代码" width="160"><template #default="{row}"><code>{{ row.code }}</code></template></el-table-column>
          <el-table-column label="标题" min-width="160"><template #default="{row}"><el-input v-if="row._edit" v-model="row.title" size="small" /><span v-else>{{ row.title }}</span></template></el-table-column>
          <el-table-column label="类型" width="80" align="center"><template #default="{row}"><el-tag size="small">{{ {sms:'短信',email:'邮件',subscribe:'订阅消息'}[row.type]||row.type }}</el-tag></template></el-table-column>
          <el-table-column label="内容" min-width="280"><template #default="{row}"><el-input v-if="row._edit" v-model="row.content" type="textarea" :rows="2" size="small" /><span v-else class="content-preview">{{ row.content }}</span></template></el-table-column>
          <el-table-column label="渠道" width="120" align="center">
            <template #default="{row}">
              <template v-if="row._edit">
                <el-checkbox v-model="row.channels" label="sms" />短信
                <el-checkbox v-model="row.channels" label="email" />邮件
                <el-checkbox v-model="row.channels" label="wechat" />微信
              </template>
              <span v-else>{{ (row.channels||[]).join(', ')||'-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="启用" width="70" align="center"><template #default="{row}"><el-switch v-model="row.status" :active-value="1" :inactive-value="0" size="small" @change="saveTmpl(row)" /></template></el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="{row}">
              <el-button v-if="!row._edit" size="small" @click="row._edit=true">编辑</el-button>
              <el-button v-if="row._edit" size="small" type="primary" @click="saveTmpl(row)">保存</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 发送日志 -->
    <div v-show="aT==='logs'">
      <el-card shadow="never">
        <el-table :data="logList" border v-loading="logLoad" style="width:100%">
          <el-table-column label="用户" width="140"><template #default="{row}">{{ row.nickname||'用户'+row.user_id }}</template></el-table-column>
          <el-table-column label="模板" width="150"><template #default="{row}"><code>{{ row.template_code }}</code></template></el-table-column>
          <el-table-column label="渠道" width="80" align="center"><template #default="{row}"><el-tag size="small">{{ row.channel }}</el-tag></template></el-table-column>
          <el-table-column label="接收方" width="160"><template #default="{row}">{{ row.receiver||'-' }}</template></el-table-column>
          <el-table-column label="内容" min-width="200"><template #default="{row}"><span class="content-preview">{{ row.content }}</span></template></el-table-column>
          <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="row.status==='sent'?'success':'danger'" size="small">{{ {sent:'已发送',pending:'待发送',failed:'失败'}[row.status]||row.status }}</el-tag></template></el-table-column>
          <el-table-column prop="created_at" label="时间" width="160" align="center" />
        </el-table>
        <div class="pagination-wrap"><el-pagination v-model:page-size="logPS" v-model:current-page="logP" :total="logTotal" layout="total,prev,pager,next" @current-change="fetchLogs" /></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
const API = axios.create({baseURL:'/api/admin'})
API.interceptors.request.use(c=>{c.headers.Authorization='Bearer '+localStorage.getItem('admin_token');return c})
const tabs = [{key:'templates',icon:'📋',label:'模板管理'},{key:'logs',icon:'📜',label:'发送记录'}]
const aT = ref('templates')
function switchTab(k){aT.value=k;if(k==='templates')fetchTmpls();else fetchLogs()}

// 模板
const tmplList=ref([]);const tmplLoad=ref(false)
async function fetchTmpls(){
  tmplLoad.value=true
  try{const r=await API.get('/notification-templates');tmplList.value=(r.data.data||[]).map(t=>({...t,channels:JSON.parse(t.channels||'[]'),_edit:false}))}
  catch{tmplList.value=[]}finally{tmplLoad.value=false}
}
async function saveTmpl(row){
  try{await API.put('/notification-templates/'+row.id,{title:row.title,content:row.content,channels:row.channels,status:row.status});row._edit=false;ElMessage.success('已保存')}
  catch{ElMessage.error('保存失败')}
}

// 日志
const logList=ref([]);const logLoad=ref(false);const logP=ref(1);const logPS=ref(15);const logTotal=ref(0)
async function fetchLogs(){
  logLoad.value=true
  try{const r=await API.get('/notification-logs',{params:{page:logP.value,pageSize:logPS.value}});logList.value=r.data.data?.list||[];logTotal.value=r.data.data?.total||0}
  catch{logList.value=[];logTotal.value=0}finally{logLoad.value=false}
}
onMounted(()=>{fetchTmpls()})
</script>

<style scoped>
.notif-page{max-width:1400px}
.tabs-card{margin-bottom:16px;padding:4px 0}
.n-tabs{display:flex;gap:4px}
.n-tab{display:flex;align-items:center;gap:6px;padding:10px 18px;border-radius:8px;cursor:pointer;font-size:14px;transition:all .2s}
.n-tab:hover{background:#f5f7fa}
.n-tab.active{background:#ecf5ff;color:#409eff;font-weight:600}
.content-preview{display:block;max-height:40px;overflow:hidden;text-overflow:ellipsis;font-size:12px;color:#666}
.pagination-wrap{display:flex;justify-content:flex-end;padding:16px 0 0}
code{font-size:12px;background:#f5f5f5;padding:2px 6px;border-radius:3px}
</style>
