<template>
  <div class="customer-pets">
    <div class="page-header">
      <h1>我的宠物</h1>
      <t-button theme="primary" @click="openCreate">
        <template #icon><t-icon name="add" /></template>
        添加宠物
      </t-button>
    </div>
    
    <!-- 宠物卡片列表 -->
    <div v-if="pets.length > 0" class="pet-grid">
      <div v-for="pet in pets" :key="pet.id" class="pet-card">
        <div class="pet-header">
          <div class="pet-avatar">{{ pet.name?.[0] || '🐾' }}</div>
          <div class="pet-actions">
            <t-button size="small" variant="text" @click="openEdit(pet)">
              <t-icon name="edit" />
            </t-button>
            <t-button size="small" variant="text" theme="danger" @click="confirmDelete(pet)">
              <t-icon name="delete" />
            </t-button>
          </div>
        </div>
        <div class="pet-body">
          <h3>{{ pet.name }}</h3>
          <div class="pet-tags">
            <span class="tag">{{ pet.breed }}</span>
            <span class="tag">{{ pet.age }}岁</span>
            <span class="tag" :class="pet.gender">{{ pet.gender === 'MALE' ? '公' : '母' }}</span>
          </div>
          <div class="pet-info">
            <p><span>体重：</span>{{ pet.weight || '--' }} kg</p>
            <p><span>颜色：</span>{{ pet.color || '--' }}</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <div class="empty-icon">🐾</div>
      <p>还没有添加宠物</p>
      <t-button theme="primary" @click="openCreate">添加第一个宠物</t-button>
    </div>
    
    <!-- 添加/编辑弹窗 -->
    <t-dialog v-model:visible="dialogVisible" :header="dialogTitle" width="500" :on-confirm="submit">
      <t-form :data="form" layout="vertical">
        <t-form-item label="宠物名称" required>
          <t-input v-model="form.name" placeholder="请输入宠物名称" />
        </t-form-item>
        <t-form-item label="品种" required>
          <t-input v-model="form.breed" placeholder="如：金毛、英短等" />
        </t-form-item>
        <t-row :gutter="16">
          <t-col :span="12">
            <t-form-item label="年龄">
              <t-input-number v-model="form.age" placeholder="岁" />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="体重(kg)">
              <t-input-number v-model="form.weight" placeholder="kg" />
            </t-form-item>
          </t-col>
        </t-row>
        <t-row :gutter="16">
          <t-col :span="12">
            <t-form-item label="性别">
              <t-select v-model="form.gender" :options="genderOptions" />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="毛色">
              <t-input v-model="form.color" placeholder="如：黄色、白色" />
            </t-form-item>
          </t-col>
        </t-row>
        <t-form-item label="备注">
          <t-textarea v-model="form.remark" placeholder="其他信息..." :maxlength="200" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

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

const auth = useAuthStore();
const pets = ref<any[]>([]);
const dialogVisible = ref(false);
const dialogTitle = ref('添加宠物');
const editingId = ref<number | null>(null);

const form = reactive({
  name: '',
  breed: '',
  age: undefined as number | undefined,
  weight: undefined as number | undefined,
  gender: 'MALE',
  color: '',
  remark: ''
});

const genderOptions = [
  { label: '公', value: 'MALE' },
  { label: '母', value: 'FEMALE' }
];

const loadPets = async () => {
  try {
    const res = await api.pets({ page: 1, size: 100 });
    if (res.code === 0) {
      pets.value = res.data?.records || [];
    }
  } catch (error) {
    console.error('加载宠物失败:', error);
    MessagePlugin.error('加载失败');
  }
};

const openCreate = () => {
  dialogTitle.value = '添加宠物';
  editingId.value = null;
  form.name = '';
  form.breed = '';
  form.age = undefined;
  form.weight = undefined;
  form.gender = 'MALE';
  form.color = '';
  form.remark = '';
  dialogVisible.value = true;
};

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

const confirmDelete = (pet: any) => {
  MessagePlugin.confirm(`确定要删除 ${pet.name} 吗？`, '确认删除', {
    onConfirm: () => remove(pet.id)
  });
};

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

const submit = async () => {
  if (!form.name || !form.breed) {
    MessagePlugin.warning('请填写完整信息');
    return;
  }
  
  const payload = { ...form };
  if (auth.user?.userId) {
    (payload as any).ownerId = auth.user.userId;
  }
  
  try {
    const res = editingId.value
      ? await api.updatePet(editingId.value, payload)
      : await api.createPet(payload);
      
    if (res.code === 0) {
      MessagePlugin.success(editingId.value ? '修改成功' : '添加成功');
      dialogVisible.value = false;
      loadPets();
    } else {
      MessagePlugin.error(res.message || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    MessagePlugin.error('保存失败');
  }
};

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

<style scoped>
.customer-pets {
  padding-bottom: 40px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
}

/* 宠物卡片网格 */
.pet-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.pet-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
}

.pet-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.pet-header {
  background: linear-gradient(135deg, #0d9488 0%, #14b8a6 100%);
  padding: 24px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.pet-avatar {
  width: 64px;
  height: 64px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  font-weight: 600;
  color: white;
  backdrop-filter: blur(10px);
}

.pet-actions {
  display: flex;
  gap: 4px;
}

.pet-actions :deep(.t-button) {
  color: rgba(255, 255, 255, 0.8);
}

.pet-actions :deep(.t-button:hover) {
  color: white;
  background: rgba(255, 255, 255, 0.2);
}

.pet-body {
  padding: 20px;
}

.pet-body h3 {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 12px;
}

.pet-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.tag {
  padding: 4px 12px;
  background: #f3f4f6;
  border-radius: 20px;
  font-size: 13px;
  color: #4b5563;
}

.tag.MALE {
  background: #dbeafe;
  color: #1e40af;
}

.tag.FEMALE {
  background: #fce7f3;
  color: #be185d;
}

.pet-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.pet-info p {
  font-size: 14px;
  color: #6b7280;
}

.pet-info span {
  color: #9ca3af;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 16px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 16px;
  color: #6b7280;
  margin-bottom: 24px;
}

/* 响应式 */
@media (max-width: 640px) {
  .pet-grid {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style>
