<template>
  <div class="app-page">
    <section class="glass-card section-card">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="模板名称">
          <el-input v-model="filters.name" placeholder="模板名称" clearable style="width:160px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="filters.type" placeholder="全部" clearable style="width:120px">
            <el-option label="邮件" value="邮件" />
            <el-option label="短信" value="短信" />
            <el-option label="站内信" value="站内信" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="全部" clearable style="width:120px">
            <el-option label="启用" value="启用" />
            <el-option label="停用" value="停用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </section>

    <section class="glass-card section-card" style="padding:12px 24px">
      <div class="table-toolbar" style="margin-bottom:0">
        <div class="chip-list">
          <el-button type="primary" @click="openDialog()">新建模板</el-button>
        </div>
        <el-button @click="loadData">刷新</el-button>
      </div>
    </section>

    <section class="glass-card section-card">
      <el-table :data="filteredItems" style="width:100%" v-loading="loading">
        <el-table-column prop="name" label="模板名称" min-width="160" />
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="getMessageTemplateType(row.type).type" size="small">{{ getMessageTemplateType(row.type).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="渠道" width="120" />
        <el-table-column prop="subject" label="主题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="variables" label="变量" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getMessageTemplateStatus(row.status).type" size="small">{{ getMessageTemplateStatus(row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDialog(row)">编辑</el-button>
            <el-button link :type="row.status === '启用' ? 'danger' : 'primary'" @click="toggleStatus(row)">{{ row.status === '启用' ? '停用' : '启用' }}</el-button>
            <el-button link type="primary" @click="doCopy(row)">复制</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
    </section>

    <el-dialog v-model="dialogVisible" :title="editingItem ? '编辑模板' : '新建模板'" width="600px" destroy-on-close>
      <el-form :model="formData" label-width="90px">
        <el-form-item label="模板名称" required>
          <el-input v-model="formData.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="类型" required>
          <el-select v-model="formData.type" placeholder="选择类型" style="width:100%">
            <el-option label="邮件" value="邮件" />
            <el-option label="短信" value="短信" />
            <el-option label="站内信" value="站内信" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用渠道">
          <el-select v-model="formData.channel" placeholder="选择渠道" style="width:100%">
            <el-option label="通用" value="通用" />
            <el-option label="Shopify" value="Shopify" />
            <el-option label="TikTok Shop" value="TikTok Shop" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板主题" v-if="formData.type !== '短信'">
          <el-input v-model="formData.subject" placeholder="邮件主题/站内信标题" />
        </el-form-item>
        <el-form-item label="模板内容" required>
          <el-input v-model="formData.content" type="textarea" :rows="6" placeholder="模板内容，支持变量占位符：{{orderNo}}、{{buyerName}}等" />
        </el-form-item>
        <el-form-item label="可用变量">
          <div style="color:var(--cb-text-soft);font-size:13px">
            {{ variablePlaceholders }}
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTemplate">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getMessageTemplateType, getMessageTemplateStatus } from '@/utils/enumMappings';

interface MessageTemplate {
  id: string;
  name: string;
  type: string;
  channel: string;
  subject: string;
  content: string;
  variables: string;
  status: string;
  updatedAt: string;
  remark?: string;
}

const items = ref<MessageTemplate[]>([
  { id: 'MT001', name: '订单发货通知', type: '邮件', channel: '通用', subject: '您的订单已发货 - {{orderNo}}', content: '亲爱的 {{buyerName}}，\n\n您的订单 {{orderNo}} 已于今日发货，预计3-5个工作日送达。\n\n物流信息：{{trackingNo}}\n\n感谢您的购买！', variables: '{{orderNo}}, {{buyerName}}, {{trackingNo}}', status: '启用', updatedAt: '2026-04-15 10:30:00' },
  { id: 'MT002', name: '发货提醒短信', type: '短信', channel: '通用', subject: '', content: '【CrossBorder】亲爱的{{buyerName}}，您的订单{{orderNo}}已发货，运单号{{trackingNo}}，请注意查收。如有疑问请联系客服。', variables: '{{orderNo}}, {{buyerName}}, {{trackingNo}}', status: '启用', updatedAt: '2026-04-10 14:20:00' },
  { id: 'MT003', name: '退款确认通知', type: '邮件', channel: '通用', subject: '退款已完成 - {{orderNo}}', content: '亲爱的 {{buyerName}}，\n\n您的退款申请已处理完成。\n\n退款单号：{{refundNo}}\n退款金额：{{refundAmount}}\n\n预计1-7个工作日到账，感谢您的理解。', variables: '{{orderNo}}, {{buyerName}}, {{refundNo}}, {{refundAmount}}', status: '启用', updatedAt: '2026-04-08 09:00:00' },
  { id: 'MT004', name: '缺货提醒', type: '站内信', channel: 'Shopify', subject: '库存不足提醒', content: '您好，SKU {{sku}} ({{productName}}) 当前库存不足，请及时补货。', variables: '{{sku}}, {{productName}}', status: '停用', updatedAt: '2026-03-28 16:45:00' }
]);

const loading = ref(false);
const dialogVisible = ref(false);
const editingItem = ref<MessageTemplate | null>(null);

const filters = ref({ name: '', type: '', status: '' });

const formData = reactive({
  name: '',
  type: '',
  channel: '通用',
  subject: '',
  content: '',
  remark: ''
});

const variablePlaceholders = '{{orderNo}} 订单号 | {{buyerName}} 买家姓名 | {{orderAmount}} 订单金额 | {{trackingNo}} 运单号 | {{sku}} SKU | {{productName}} 商品名称';

const filteredItems = computed(() => {
  return items.value.filter(item => {
    if (filters.value.name && !item.name.includes(filters.value.name)) return false;
    if (filters.value.type && item.type !== filters.value.type) return false;
    if (filters.value.status && item.status !== filters.value.status) return false;
    return true;
  });
});

const loadData = () => { loading.value = true; setTimeout(() => { loading.value = false; }, 300); };
const resetFilters = () => { filters.value = { name: '', type: '', status: '' }; };

const openDialog = (item?: MessageTemplate) => {
  editingItem.value = item || null;
  if (item) {
    Object.assign(formData, { name: item.name, type: item.type, channel: item.channel, subject: item.subject, content: item.content, remark: item.remark || '' });
  } else {
    Object.assign(formData, { name: '', type: '', channel: '通用', subject: '', content: '', remark: '' });
  }
  dialogVisible.value = true;
};

const saveTemplate = () => {
  if (!formData.name || !formData.type || !formData.content) {
    ElMessage.warning('请填写必填项');
    return;
  }
  if (editingItem.value) {
    const idx = items.value.findIndex(i => i.id === editingItem.value!.id);
    if (idx !== -1) items.value[idx] = { ...items.value[idx], ...formData, updatedAt: new Date().toLocaleString() };
    ElMessage.success('模板已更新');
  } else {
    items.value.push({ id: `MT${String(items.value.length + 1).padStart(3, '0')}`, ...formData, variables: '{{orderNo}}, {{buyerName}}', status: '启用', updatedAt: new Date().toLocaleString() });
    ElMessage.success('模板已创建');
  }
  dialogVisible.value = false;
};

const toggleStatus = async (row: MessageTemplate) => {
  const action = row.status === '启用' ? '停用' : '启用';
  await ElMessageBox.confirm(`确认${action}「${row.name}」？`);
  const idx = items.value.findIndex(i => i.id === row.id);
  if (idx !== -1) items.value[idx].status = row.status === '启用' ? '停用' : '启用';
  ElMessage.success(`模板已${action}`);
};

const doCopy = (row: MessageTemplate) => {
  ElMessageBox.confirm(`确认复制「${row.name}」模板？`).then(() => {
    items.value.push({ ...row, id: `MT${String(items.value.length + 1).padStart(3, '0')}`, name: `${row.name} (副本)`, status: '停用', updatedAt: new Date().toLocaleString() });
    ElMessage.success('模板已复制');
  }).catch(() => {});
};

onMounted(loadData);
</script>

<style scoped>
.filter-form :deep(.el-form-item) { margin-bottom: 0; }
</style>