<template>
  <PageContainer title="通知文案模板">
    <QueryToolbar>
      <el-button v-if="canManage" type="primary" @click="openCreate">新增文案模板</el-button>
      <el-button v-if="canRead" @click="load">刷新</el-button>
    </QueryToolbar>

    <el-table :data="rows">
      <el-table-column prop="templateName" label="模板名称" min-width="180" />
      <el-table-column prop="subjectTemplate" label="邮件主题模板" min-width="180" show-overflow-tooltip />
      <el-table-column prop="titleTemplate" label="站内标题模板" min-width="180" show-overflow-tooltip />
      <el-table-column prop="contentTemplate" label="正文模板" min-width="260" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
      <el-table-column label="操作" width="260">
        <template #default="{ row }">
          <el-button v-if="canManage" size="small" @click="openEdit(row)">编辑</el-button>
          <el-button v-if="canManage && row.status !== 'ENABLED'" size="small" type="success" @click="handleEnable(row.id)">启用</el-button>
          <el-button v-else-if="canManage" size="small" type="warning" @click="handleDisable(row.id)">停用</el-button>
          <el-button
            v-if="canManage && row.status === 'DISABLED'"
            size="small"
            type="danger"
            @click="handleDeleteTemplate(row.id, row.templateName)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex-end mt-md">
      <el-pagination
        :current-page="pageNo"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handlePageChange"
        @size-change="handlePageSizeChange"
      />
    </div>

    <el-dialog v-model="visible" :title="editingId ? '编辑通知文案模板' : '新增通知文案模板'" :width="DIALOG_WIDTH.lg">
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.lg" :rules="formRules">
        <el-form-item label="模板名称" prop="templateName"><el-input v-model="form.templateName" /></el-form-item>
        <el-form-item label="邮件主题模板" prop="subjectTemplate"><el-input v-model="form.subjectTemplate" placeholder="支持占位符，如：审核通知-${meetingTopic}" /></el-form-item>
        <el-form-item label="站内标题模板"><el-input v-model="form.titleTemplate" placeholder="支持占位符，如：审核结果通知" /></el-form-item>
        <el-form-item label="正文模板">
          <el-input v-model="form.contentTemplate" type="textarea" :rows="4" placeholder="支持占位符，如：会议《${meetingTopic}》状态：${result}" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="启用" value="ENABLED" />
            <el-option label="停用" value="DISABLED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import { DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  createNotificationTextTemplate,
  deleteNotificationTextTemplate,
  disableNotificationTextTemplate,
  enableNotificationTextTemplate,
  fetchNotificationTextTemplates,
  updateNotificationTextTemplate,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const canRead = computed(() =>
  authStore.hasPermission(PERMS.notification.textTemplateRead)
  || authStore.hasPermission(PERMS.notification.policyRead)
  || authStore.hasPermission(PERMS.notification.policyManage),
);
const canManage = computed(() =>
  authStore.hasPermission(PERMS.notification.textTemplateManage) || authStore.hasPermission(PERMS.notification.policyManage),
);
const rows = ref<any[]>([]);
const pageNo = ref(1);
const pageSize = ref(20);
const total = ref(0);
const visible = ref(false);
const editingId = ref<number | null>(null);
const form = ref({
  templateName: "",
  subjectTemplate: "",
  titleTemplate: "",
  contentTemplate: "",
  status: "ENABLED" as "ENABLED" | "DISABLED",
});

const formRef = ref<FormInstance>();
const formRules = ref<FormRules>({
  templateName: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
});

const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);

const load = async () => {
  if (!canRead.value) {
    rows.value = [];
    total.value = 0;
    return;
  }
  const resp = await fetchNotificationTextTemplates({ pageNo: pageNo.value, pageSize: pageSize.value });
  rows.value = resp?.data?.list || [];
  total.value = Number(resp?.data?.total || 0);
};

const handlePageChange = (page: number) => {
  pageNo.value = page;
  load();
};

const handlePageSizeChange = (size: number) => {
  pageSize.value = size;
  pageNo.value = 1;
  load();
};

const openCreate = () => {
  editingId.value = null;
  form.value = {
    templateName: "审核通知模板",
    subjectTemplate: "审核通知-${meetingTopic}",
    titleTemplate: "审核通知",
    contentTemplate: "会议《${meetingTopic}》状态：${result}",
    status: "ENABLED",
  };
  visible.value = true;
};

const openEdit = (row: any) => {
  editingId.value = Number(row.id);
  form.value = {
    templateName: String(row.templateName || ""),
    subjectTemplate: String(row.subjectTemplate || ""),
    titleTemplate: String(row.titleTemplate || ""),
    contentTemplate: String(row.contentTemplate || ""),
    status: (row.status || "ENABLED") as "ENABLED" | "DISABLED",
  };
  visible.value = true;
};

const handleSave = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;

  const payload = {
    templateName: form.value.templateName,
    subjectTemplate: form.value.subjectTemplate,
    titleTemplate: form.value.titleTemplate,
    contentTemplate: form.value.contentTemplate,
    status: form.value.status,
  };
  if (editingId.value) {
    await updateNotificationTextTemplate(editingId.value, payload);
    ElMessage.success("通知文案模板更新成功");
  } else {
    await createNotificationTextTemplate(payload);
    ElMessage.success("通知文案模板创建成功");
  }
  visible.value = false;
  await load();
};

const handleEnable = async (id: number) => {
  await enableNotificationTextTemplate(id);
  ElMessage.success("文案模板已启用");
  await load();
};

const handleDisable = async (id: number) => {
  await disableNotificationTextTemplate(id);
  ElMessage.success("文案模板已停用");
  await load();
};

const handleDeleteTemplate = async (id: number, name: string) => {
  await ElMessageBox.confirm(`确认删除文案模板「${name}」？删除后不可恢复。`, "删除模板", {
    type: "warning",
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
  });
  await deleteNotificationTextTemplate(id);
  ElMessage.success("文案模板已删除");
  await load();
};

onMounted(async () => {
  await load();
});
</script>
