<template>
  <div class="page">
    <h2 class="page-title">留言板</h2>
    <div class="panel">
      <div class="inline-form">
        <t-select v-model="query.status" :options="statusOptions" placeholder="状态" style="width: 160px" />
        <t-button theme="primary" @click="load">查询</t-button>
      </div>
      <t-table :data="list" :columns="columns" row-key="id">
        <template #status="{ row }">
          {{ getStatusText(row.status) }}
        </template>
        <template #op="{ row }">
          <t-button size="small" variant="text" @click="openReply(row)">回复</t-button>
        </template>
      </t-table>
    </div>

    <t-dialog v-model:visible="dialogVisible" header="回复留言" :on-confirm="submitReply">
      <t-form :data="form">
        <t-form-item label="回复内容">
          <t-textarea v-model="form.reply" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { api } from '../api';

const list = ref([] as any[]);
const query = reactive({ status: '' });
const dialogVisible = ref(false);
const currentId = ref<number | null>(null);
const form = reactive({ reply: '' });

const statusOptions = [
  { label: '待处理', value: 'PENDING' },
  { label: '已处理', value: 'PROCESSED' },
];

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    PENDING: '待处理',
    PROCESSED: '已处理',
  };
  return map[status] || status || '-';
};

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'title', title: '标题' },
  { colKey: 'userName', title: '用户' },
  { colKey: 'status', title: '状态' },
  { colKey: 'reply', title: '回复' },
  { colKey: 'op', title: '操作', width: 100 },
];

const load = async () => {
  const params: any = { page: 1, size: 20 };
  if (query.status) params.status = query.status;
  const res = await api.messages(params);
  if (res.code === 0) list.value = res.data.records || [];
};

const openReply = (row: any) => {
  currentId.value = row.id;
  form.reply = row.reply || '';
  dialogVisible.value = true;
};

const submitReply = async () => {
  if (!currentId.value) return;
  const res = await api.replyMessage(currentId.value, { reply: form.reply });
  if (res.code === 0) {
    MessagePlugin.success('回复成功');
    dialogVisible.value = false;
    load();
  } else {
    MessagePlugin.error(res.message || '回复失败');
  }
};

onMounted(load);
</script>
