<template>
  <div class="page">
    <h2 class="page-title">宠物档案</h2>
    <div class="panel">
      <div class="inline-form">
        <t-input v-if="!isCustomer" v-model="query.ownerId" placeholder="主人ID" style="width: 160px" />
        <t-button theme="primary" @click="load">查询</t-button>
        <t-button variant="outline" @click="openCreate">新增宠物</t-button>
      </div>
      <t-table :data="list" :columns="columns" row-key="id">
        <template #gender="{ row }">
          {{ getGenderText(row.gender) }}
        </template>
        <template #op="{ row }">
          <div class="table-actions">
            <t-button size="small" variant="text" @click="openEdit(row)">编辑</t-button>
            <t-popconfirm content="确认删除？" @confirm="remove(row.id)">
              <t-button size="small" theme="danger" variant="text">删除</t-button>
            </t-popconfirm>
          </div>
        </template>
      </t-table>
    </div>

    <t-dialog v-model:visible="dialogVisible" :header="dialogTitle" :on-confirm="submit">
      <t-form :data="form">
        <t-form-item v-if="!isCustomer" label="主人" required>
          <t-select v-model="form.ownerId" :options="customerOptions" placeholder="请选择主人" clearable />
        </t-form-item>
        <t-form-item label="名称"><t-input v-model="form.name" /></t-form-item>
        <t-form-item label="品种"><t-input v-model="form.breed" /></t-form-item>
        <t-form-item label="性别"><t-select v-model="form.gender" :options="genderOptions" /></t-form-item>
        <t-form-item label="体重"><t-input v-model="form.weight" /></t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

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

const query = reactive({ ownerId: '' });
const list = ref([] as any[]);
const customers = ref([] as any[]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增宠物');
const editingId = ref<number | null>(null);
const form = reactive({ ownerId: '', name: '', breed: '', gender: 'MALE', weight: '' });
const auth = useAuthStore();

const isCustomer = computed(() => auth.user?.role === 'CUSTOMER');

const customerOptions = computed(() => {
  return customers.value.map((customer: any) => ({
    label: customer.username || `顾客${customer.id}`,
    value: customer.id,
  }));
});

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'name', title: '名称' },
  { colKey: 'breed', title: '品种' },
  { colKey: 'gender', title: '性别' },
  { colKey: 'weight', title: '体重' },
  { colKey: 'op', title: '操作', width: 140 },
];

const genderOptions = [
  { label: '雄性', value: 'MALE' },
  { label: '雌性', value: 'FEMALE' },
];

const getGenderText = (gender: string) => {
  const map: Record<string, string> = {
    MALE: '雄性',
    FEMALE: '雌性',
  };
  return map[gender] || gender || '-';
};

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

const openCreate = () => {
  dialogTitle.value = '新增宠物';
  editingId.value = null;
  form.ownerId = isCustomer.value
    ? auth.user?.userId || ''
    : query.ownerId ? Number(query.ownerId) : '';
  form.name = '';
  form.breed = '';
  form.gender = 'MALE';
  form.weight = '';
  dialogVisible.value = true;
};

const openEdit = (row: any) => {
  dialogTitle.value = '编辑宠物';
  editingId.value = row.id;
  form.ownerId = row.ownerId || '';
  form.name = row.name || '';
  form.breed = row.breed || '';
  form.gender = row.gender || 'MALE';
  form.weight = row.weight || '';
  dialogVisible.value = true;
};

const loadCustomers = async () => {
  const res = await api.users({ page: 1, size: 100, role: 'CUSTOMER' });
  if (res.code === 0) {
    customers.value = res.data?.records || [];
  }
};

const submit = async () => {
  const payload = { ...form } as any;
  if (isCustomer.value) {
    payload.ownerId = auth.user?.userId || payload.ownerId;
  }
  const res = editingId.value
    ? await api.updatePet(editingId.value, payload)
    : await api.createPet(payload);
  if (res.code === 0) {
    MessagePlugin.success('保存成功');
    dialogVisible.value = false;
    load();
  } else {
    MessagePlugin.error(res.message || '保存失败');
  }
};

const remove = async (id: number) => {
  const res = await api.deletePet(id);
  if (res.code === 0) {
    MessagePlugin.success('删除成功');
    load();
  } else {
    MessagePlugin.error(res.message || '删除失败');
  }
};

onMounted(() => {
  load();
  if (!isCustomer.value) {
    loadCustomers();
  }
});
</script>
