<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="模板代码" prop="templateCode">
        <el-input v-model="queryParams.templateCode" placeholder="请输入模板代码" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:mail:template:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:mail:template:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:mail:template:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板ID" align="center" prop="templateId" width="80" />
      <el-table-column label="模板名称" align="center" prop="templateName" :show-overflow-tooltip="true" />
      <el-table-column label="模板代码" align="center" prop="templateCode" :show-overflow-tooltip="true" />
      <el-table-column label="邮件主题" align="center" prop="subject" :show-overflow-tooltip="true" />
      <el-table-column label="内容类型" align="center" prop="contentType" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.contentType === 'html' ? 'primary' : 'info'">{{ scope.row.contentType === 'html' ? 'HTML' : '纯文本' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">{{ scope.row.status === '0' ? '正常' : '停用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:mail:template:edit']">修改</el-button>
          <el-button link type="primary" icon="View" @click="handlePreview(scope.row)" v-hasPermi="['system:mail:template:preview']">预览</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:mail:template:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改邮件模板对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="templateRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板代码" prop="templateCode">
              <el-input v-model="form.templateCode" placeholder="请输入模板代码" :disabled="form.templateId != null" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮件主题" prop="subject">
              <el-input v-model="form.subject" placeholder="请输入邮件主题，支持变量${xxx}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内容类型" prop="contentType">
              <el-radio-group v-model="form.contentType">
                <el-radio value="html">HTML</el-radio>
                <el-radio value="text">纯文本</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="变量列表" prop="variables">
              <el-input v-model="form.variables" placeholder='JSON数组，如：["name","code"]' />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="模板内容" prop="content">
              <el-input v-model="form.content" type="textarea" :rows="12" placeholder="请输入模板内容，支持变量${xxx}" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览模板对话框 -->
    <el-dialog title="模板预览" v-model="previewOpen" width="800px" append-to-body>
      <div class="preview-container" v-html="previewContent"></div>
    </el-dialog>
  </div>
</template>

<script setup name="MailTemplate">
import { listMailTemplate, getMailTemplate, addMailTemplate, updateMailTemplate, delMailTemplate, previewMailTemplate } from "@/api/system/mail"

const { proxy } = getCurrentInstance()

const templateList = ref([])
const open = ref(false)
const previewOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const previewContent = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateName: null,
    templateCode: null,
    status: null
  },
  rules: {
    templateName: [{ required: true, message: "模板名称不能为空", trigger: "blur" }],
    templateCode: [{ required: true, message: "模板代码不能为空", trigger: "blur" }],
    subject: [{ required: true, message: "邮件主题不能为空", trigger: "blur" }],
    content: [{ required: true, message: "模板内容不能为空", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询邮件模板列表 */
function getList() {
  loading.value = true
  listMailTemplate(queryParams.value).then(response => {
    templateList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    templateId: null,
    templateName: null,
    templateCode: null,
    subject: null,
    content: null,
    contentType: 'html',
    variables: null,
    status: '0',
    remark: null
  }
  proxy.resetForm("templateRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.templateId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加邮件模板"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const templateId = row.templateId || ids.value
  getMailTemplate(templateId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改邮件模板"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["templateRef"].validate(valid => {
    if (valid) {
      if (form.value.templateId != null) {
        updateMailTemplate(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMailTemplate(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const templateIds = row.templateId || ids.value
  proxy.$modal.confirm('是否确认删除邮件模板编号为"' + templateIds + '"的数据项？').then(function() {
    return delMailTemplate(templateIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 预览按钮操作 */
function handlePreview(row) {
  // 解析变量并生成预览数据
  let variables = {}
  if (row.variables) {
    try {
      const varList = JSON.parse(row.variables)
      varList.forEach(v => {
        variables[v] = '示例' + v
      })
    } catch (e) {
      console.error('解析变量失败', e)
    }
  }
  
  previewMailTemplate({
    templateId: row.templateId,
    variables: variables
  }).then(response => {
    previewContent.value = response.msg || response.data
    previewOpen.value = true
  })
}

getList()
</script>

<style scoped>
.preview-container {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
  min-height: 300px;
}
</style>
