<template>
  <t-card :bordered="false">
    <div class="table-container">
      <t-form class="search-form" :data="searchForm" layout="inline" @submit="handleSearch">
        <t-form-item name="keyword" label="关键词">
          <t-input v-model="searchForm.keyword" placeholder="请输入关键词" />
        </t-form-item>
        <t-form-item>
          <t-button theme="primary" type="submit">查询</t-button>
          <t-button theme="default" variant="base" @click="handleReset">重置</t-button>
          <t-button v-if="canSave" class="search-action-btn" @click="openAdd">新增</t-button>
        </t-form-item>
      </t-form>

      <t-table :data="tableData" :columns="columns" row-key="id" :loading="dataLoading"
        :pagination="pagination" hover @page-change="handlePageChange">
        <template #status="{ row }">
          <t-switch :value="row.status === 1" @change="(v: boolean) => handleToggleStatus(row, v)" />
        </template>
        <template #op="{ row }">
          <t-space>
            <t-link theme="primary" hover="color" @click="openEdit(row)">编辑</t-link>
            <t-popconfirm content="确认删除？" @confirm="handleDelete(row)">
              <t-link theme="danger" hover="color">删除</t-link>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
    </div>

    <t-dialog v-model:visible="dialogVisible" :header="isEdit ? '编辑' : '新增'" width="600px"
      :confirm-btn="{ content: '保存', theme: 'primary', loading: saving }" @confirm="handleSubmit">
      <t-form ref="formRef" :data="dialogForm" :rules="formRules" label-width="100px">
        <t-form-item label="名称" name="name">
          <t-input v-model="dialogForm.name" placeholder="请输入名称" />
        </t-form-item>
        <t-form-item label="排序" name="sort">
          <t-input-number v-model="dialogForm.sort" :min="0" placeholder="数字越小越靠前" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </t-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { usePermission } from '@/hooks/use-permission';
import { get{{Class}}List, save{{Class}}, delete{{Class}} } from '@/applications/{{code}}/api/{{code}}.ts';

const { canSave } = usePermission();

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'name', title: '名称' },
  { colKey: 'sort', title: '排序', width: 100 },
  { colKey: 'status', title: '状态', width: 100 },
  { colKey: 'create_time', title: '创建时间', width: 180 },
  { colKey: 'op', title: '操作', width: 150 },
];

const searchForm = reactive({ keyword: '' });
const tableData = ref([]);
const dataLoading = ref(false);
const pagination = reactive({ current: 1, pageSize: 15, total: 0 });

const dialogVisible = ref(false);
const saving = ref(false);
const isEdit = ref(false);
const editId = ref(0);
const dialogForm = reactive({ name: '', sort: 0 });

const handleSearch = async () => { await fetchList(); };
const handleReset = () => { searchForm.keyword = ''; fetchList(); };
const handlePageChange = (pageInfo: any) => { pagination.current = pageInfo.current; fetchList(); };

const fetchList = async () => {
  dataLoading.value = true;
  try {
    const res = await get{{Class}}List({ keyword: searchForm.keyword, page: pagination.current, limit: pagination.pageSize });
    if (res.code === 0) { tableData.value = res.data.list; pagination.total = res.data.total; }
  } finally { dataLoading.value = false; }
};

const openAdd = () => { isEdit.value = false; editId.value = 0; dialogForm.name = ''; dialogForm.sort = 0; dialogVisible.value = true; };
const openEdit = (row: any) => { isEdit.value = true; editId.value = row.id; dialogForm.name = row.name; dialogForm.sort = row.sort || 0; dialogVisible.value = true; };

const handleSubmit = async () => {
  saving.value = true;
  try {
    const res = await save{{Class}}({ id: editId.value, name: dialogForm.name, sort: dialogForm.sort });
    if (res.code === 0) { MessagePlugin.success('保存成功'); dialogVisible.value = false; fetchList(); }
    else MessagePlugin.error(res.msg || '保存失败');
  } finally { saving.value = false; }
};

const handleDelete = async (row: any) => {
  const res = await delete{{Class}}({ id: row.id });
  if (res.code === 0) { MessagePlugin.success('删除成功'); fetchList(); }
  else MessagePlugin.error(res.msg || '删除失败');
};

const handleToggleStatus = async (row: any, enabled: boolean) => {
  const res = await save{{Class}}({ id: row.id, status: enabled ? 1 : 0 });
  if (res.code !== 0) MessagePlugin.error(res.msg || '操作失败');
  else fetchList();
};

onMounted(() => { fetchList(); });
</script>
