<template>
  <div class="page-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">宠物档案</span>
          <div class="header-actions">
            <el-input v-model="searchKey" placeholder="搜索宠物名/主人" style="width: 200px; margin-right: 10px" clearable />
            <el-button type="primary" icon="Plus" @click="handleAdd">新增档案</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredTableData" style="width: 100%">
        <el-table-column label="宠物信息" width="220">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-avatar :size="50" :src="scope.row.avatar" style="margin-right: 10px" />
              <div>
                <div style="font-weight: bold">{{ scope.row.name }}</div>
                <div style="font-size: 12px; color: #999">{{ scope.row.breed }} | {{ scope.row.age }}岁</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.gender === '公' ? '' : 'danger'" effect="plain" size="small">{{ scope.row.gender }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="所属主人" width="180">
          <template #default="scope">
            <div>{{ scope.row.ownerName }}</div>
            <div style="font-size: 12px; color: #666">{{ scope.row.ownerPhone }}</div>
          </template>
        </el-table-column>
        <el-table-column label="标签" min-width="150">
          <template #default="scope">
            <el-tag v-for="tag in scope.row.tags" :key="tag" :type="getTagType(tag)" effect="light" size="small" style="margin-right: 5px">{{
              tag
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="健康状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.healthStatus === '健康' ? 'success' : 'warning'" effect="dark" size="small">{{ scope.row.healthStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="疫苗接种" width="120" align="center">
          <template #default="scope">
            {{ scope.row.vaccine || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleRemark(scope.row)">备注</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" title="宠物档案详情" width="800px">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-form :model="form" label-width="100px">
            <el-row>
              <el-col :span="24" style="display: flex; justify-content: center; margin-bottom: 20px">
                <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false" :on-change="handleUploadFile">
                  <el-avatar v-if="form.avatar" :src="form.avatar" :size="80" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-col>
              <el-col :span="12">
                <el-form-item label="宠物姓名" required><el-input v-model="form.name" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属主人" required>
                  <el-select v-model="form.ownerId" placeholder="选择主人" style="width: 100%" filterable>
                    <el-option v-for="user in userList" :key="user.id" :label="user.name + ' - ' + user.phone" :value="user.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别">
                  <el-radio-group v-model="form.gender">
                    <el-radio label="公">公</el-radio>
                    <el-radio label="母">母</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品种">
                  <el-select v-model="form.breed" placeholder="请选择品种" style="width: 100%" filterable allow-create default-first-option>
                    <el-option v-for="breed in petBreeds" :key="breed" :label="breed" :value="breed" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="体型">
                  <el-select v-model="form.size" style="width: 100%">
                    <el-option label="小型" value="small" />
                    <el-option label="中型" value="medium" />
                    <el-option label="大型" value="large" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="体重(kg)"><el-input-number v-model="form.weight" :min="0" :precision="1" style="width: 100%" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄(岁)"><el-input-number v-model="form.age" :min="0" style="width: 100%" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="性格关键词"><el-input v-model="form.personality" placeholder="如：活泼、粘人" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="萌宠性格"><el-input v-model="form.cutePersonality" type="textarea" placeholder="详细描述" /></el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="宠物标签">
                  <el-select v-model="form.tags" multiple placeholder="选择标签" style="width: 100%">
                    <el-option v-for="tag in allPetTags" :key="tag.name" :label="tag.name" :value="tag.name">
                      <el-tag :type="tag.type" effect="light" size="small">{{ tag.name }}</el-tag>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="家庭信息" name="family">
          <el-form :model="form" label-width="120px">
            <el-form-item label="新来家庭时间">
              <el-date-picker v-model="form.arrivalTime" type="date" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
            <el-form-item label="家庭房屋类型">
              <el-radio-group v-model="form.houseType">
                <el-radio label="stairs">楼梯</el-radio>
                <el-radio label="elevator">电梯</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="入门方式">
              <el-radio-group v-model="form.entryMethod">
                <el-radio label="password">密码开门</el-radio>
                <el-radio label="key">钥匙开门</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="密码" v-if="form.entryMethod === 'password'">
              <el-input v-model="form.entryPassword" placeholder="请输入门锁密码" />
            </el-form-item>
            <el-form-item label="钥匙位置" v-if="form.entryMethod === 'key'">
              <el-input v-model="form.keyLocation" placeholder="请输入钥匙存放位置" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="健康状况" name="health">
          <el-form :model="form" label-width="120px">
            <el-form-item label="健康状态">
              <el-radio-group v-model="form.healthStatus">
                <el-radio label="健康">健康</el-radio>
                <el-radio label="亚健康">亚健康</el-radio>
                <el-radio label="疾病">疾病</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否有攻击倾向">
              <el-switch v-model="form.aggression" active-text="是" inactive-text="否" />
            </el-form-item>
            <el-form-item label="疫苗情况">
              <el-radio-group v-model="form.vaccine">
                <el-radio label="无">无</el-radio>
                <el-radio label="已打1次">已打1次</el-radio>
                <el-radio label="已打2次">已打2次</el-radio>
                <el-radio label="已打3次">已打3次</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="疫苗凭证">
              <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false" :on-change="handleUploadVaccineCert">
                <img v-if="form.vaccineCert" :src="form.vaccineCert" class="avatar" style="width: 100px; height: 100px; object-fit: cover" />
                <el-icon v-else class="avatar-uploader-icon" style="width: 100px; height: 100px; line-height: 100px"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="既往病史">
              <el-input v-model="form.medicalHistory" type="textarea" placeholder="如有病史请记录" />
            </el-form-item>
            <el-form-item label="过敏史">
              <el-input v-model="form.allergies" type="textarea" placeholder="如有过敏源请记录" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveData">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Pet Profile Drawer -->
    <el-drawer v-model="drawerVisible" title="宠物档案详情" size="60%" destroy-on-close>
      <div class="profile-header">
        <el-avatar :size="80" :src="currentPet.avatar" />
        <div class="profile-basic">
          <div class="name-row">
            <span class="name">{{ currentPet.name }}</span>
            <el-tag size="small" :type="currentPet.gender === '公' ? '' : 'danger'" effect="dark" style="margin-left: 10px">
              {{ currentPet.gender }}
            </el-tag>
            <el-tag size="small" effect="plain" type="info" style="margin-left: 5px">{{ currentPet.age }}岁</el-tag>
          </div>
          <div class="tags-row" style="margin-top: 8px">
            <el-tag v-for="tag in currentPet.tags" :key="tag" :type="getTagType(tag)" effect="light" size="small" style="margin-right: 5px">
              {{ tag }}
            </el-tag>
          </div>
        </div>
        <div style="margin-left: auto">
          <el-button type="primary" size="small" plain @click="handleRemark(currentPet)">添加备注</el-button>
        </div>
      </div>

      <el-tabs v-model="detailActiveTab" class="profile-tabs">
        <el-tab-pane label="档案信息" name="info">
          <div class="section-title">基本信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="品种">{{ currentPet.breed }}</el-descriptions-item>
            <el-descriptions-item label="体型">
              {{ currentPet.size === 'small' ? '小型' : currentPet.size === 'medium' ? '中型' : '大型' }}
            </el-descriptions-item>
            <el-descriptions-item label="体重">{{ currentPet.weight }} kg</el-descriptions-item>
            <el-descriptions-item label="所属主人">{{ currentPet.ownerName }} ({{ currentPet.ownerPhone }})</el-descriptions-item>
            <el-descriptions-item label="性格关键词">{{ currentPet.personality || '-' }}</el-descriptions-item>
            <el-descriptions-item label="萌宠性格" :span="2">{{ currentPet.cutePersonality || '-' }}</el-descriptions-item>
          </el-descriptions>

          <div class="section-title" style="margin-top: 20px">家庭信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="到家时间">{{ currentPet.arrivalTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="房屋类型">
              {{ currentPet.houseType === 'stairs' ? '楼梯' : '电梯' }}
            </el-descriptions-item>
            <el-descriptions-item label="入门方式">
              {{ currentPet.entryMethod === 'password' ? '密码开门' : '钥匙开门' }}
            </el-descriptions-item>
            <el-descriptions-item label="开门详情">
              {{ currentPet.entryMethod === 'password' ? currentPet.entryPassword : currentPet.keyLocation }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="section-title" style="margin-top: 20px">健康状况</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="健康状态">
              <el-tag :type="currentPet.healthStatus === '健康' ? 'success' : 'warning'" size="small">{{ currentPet.healthStatus }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="攻击倾向">
              <el-tag :type="currentPet.aggression ? 'danger' : 'success'" size="small">{{ currentPet.aggression ? '有' : '无' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="疫苗情况" :span="2">
              <div>{{ currentPet.vaccine || '-' }}</div>
              <div v-if="currentPet.vaccineCert" style="margin-top: 10px">
                <el-image
                  style="width: 100px; height: 100px; border-radius: 4px"
                  :src="currentPet.vaccineCert"
                  :preview-src-list="[currentPet.vaccineCert]"
                  fit="cover"
                />
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="既往病史" :span="2">{{ currentPet.medicalHistory || '-' }}</el-descriptions-item>
            <el-descriptions-item label="过敏史" :span="2">{{ currentPet.allergies || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="历史订单" name="orders">
          <el-table :data="mockOrders" border style="width: 100%">
            <el-table-column prop="orderNo" label="订单编号" width="180" />
            <el-table-column prop="service" label="服务项目" />
            <el-table-column prop="time" label="服务时间" width="180" />
            <el-table-column prop="amount" label="金额" width="100" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag type="success" size="small">完成</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="备注日志" name="logs">
          <el-timeline style="margin-top: 10px; padding-left: 5px">
            <el-timeline-item v-for="(activity, index) in mockLogs" :key="index" :timestamp="activity.timestamp" :type="activity.type">
              {{ activity.content }}
              <div style="font-size: 12px; color: #999; margin-top: 4px">操作人: {{ activity.operator }}</div>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

    <!-- Remark Dialog -->
    <el-dialog v-model="remarkDialogVisible" title="添加备注" width="400px">
      <el-input v-model="remarkForm.content" type="textarea" :rows="3" placeholder="请输入备注内容..." />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="remarkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRemark">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const searchKey = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
};
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
};

const dialogVisible = ref(false);
const drawerVisible = ref(false);
const remarkDialogVisible = ref(false);
const isEdit = ref(false);
const activeTab = ref('basic');
const detailActiveTab = ref('info');
const currentPet = ref({});

const mockOrders = ref([
  { orderNo: 'DD20231001001', service: '上门喂养 (标准版)', time: '2023-10-01 10:00', amount: '88.00', status: 'completed' },
  { orderNo: 'DD20230915002', service: '深度洗护套餐', time: '2023-09-15 14:00', amount: '158.00', status: 'completed' }
]);

const mockLogs = ref([
  { content: '因宠物胆小，建议安排资深服务师', timestamp: '2023-10-01 09:00', operator: '客服小美', type: 'warning' },
  { content: '更新了疫苗接种记录', timestamp: '2023-09-10 11:30', operator: '管理员', type: 'primary' },
  { content: '创建宠物档案', timestamp: '2023-01-01 10:00', operator: '系统', type: 'info' }
]);

const remarkForm = reactive({ content: '' });

// Mock Users for selection
const userList = [
  { id: 101, name: '张先生', phone: '13800138000' },
  { id: 102, name: '李小姐', phone: '13900139000' }
];

const petBreeds = [
  '金毛',
  '拉布拉多',
  '柴犬',
  '柯基',
  '哈士奇',
  '阿拉斯加',
  '萨摩耶',
  '边境牧羊犬',
  '德国牧羊犬',
  '贵宾犬/泰迪',
  '比熊',
  '博美',
  '雪纳瑞',
  '法斗',
  '中华田园犬',
  '英短',
  '美短',
  '布偶猫',
  '加菲猫',
  '暹罗猫',
  '波斯猫',
  '缅因猫',
  '中华田园猫'
];

const allPetTags = [
  { name: '易过敏', type: 'danger' },
  { name: '胆小', type: 'warning' },
  { name: '攻击性', type: 'info' },
  { name: '粘人', type: 'success' }
];

const getTagType = (name) => {
  const tag = allPetTags.find((t) => t.name === name);
  return tag ? tag.type : 'info';
};

const tableData = ref([
  {
    id: 1,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    name: '旺财',
    gender: '公',
    breed: '金毛',
    age: 3,
    size: 'large',
    weight: 30,
    ownerId: 101,
    ownerName: '张先生',
    ownerPhone: '13800138000',
    tags: ['易过敏', '胆小'],
    healthStatus: '健康',
    personality: '活泼',
    cutePersonality: '超级粘人，喜欢玩球',
    arrivalTime: '2023-01-01',
    houseType: 'elevator',
    entryMethod: 'password',
    entryPassword: '456',
    aggression: false,
    vaccine: '已打3次',
    vaccineCert: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
    medicalHistory: '',
    allergies: '海鲜'
  }
]);

const filteredTableData = computed(() => {
  return tableData.value.filter((item) => !searchKey.value || item.name.includes(searchKey.value) || item.ownerName.includes(searchKey.value));
});

const form = reactive({
  id: null,
  avatar: '',
  name: '',
  gender: '公',
  breed: '',
  age: 1,
  size: 'small',
  weight: 5,
  ownerId: null,
  personality: '',
  cutePersonality: '',
  tags: [],

  arrivalTime: '',
  houseType: 'stairs',
  entryMethod: 'key',
  entryPassword: '',
  keyLocation: '',

  healthStatus: '健康',
  aggression: false,
  vaccine: '无',
  vaccineCert: '',
  medicalHistory: '',
  allergies: ''
});

const handleAdd = () => {
  isEdit.value = false;
  activeTab.value = 'basic';
  Object.assign(form, {
    id: null,
    avatar: '',
    name: '',
    gender: '公',
    breed: '',
    age: 1,
    size: 'small',
    weight: 5,
    ownerId: null,
    personality: '',
    cutePersonality: '',
    tags: [],
    arrivalTime: '',
    houseType: 'stairs',
    entryMethod: 'key',
    entryPassword: '',
    keyLocation: '',
    healthStatus: '健康',
    aggression: false,
    vaccine: '无',
    vaccineCert: '',
    medicalHistory: '',
    allergies: ''
  });
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  isEdit.value = true;
  activeTab.value = 'basic';
  Object.assign(form, row);
  dialogVisible.value = true;
};

const handleDetail = (row) => {
  currentPet.value = { ...row };
  drawerVisible.value = true;
};

const handleRemark = (row) => {
  currentPet.value = row;
  remarkForm.content = '';
  remarkDialogVisible.value = true;
};

const saveRemark = () => {
  if (!remarkForm.content) return ElMessage.warning('请输入内容');
  mockLogs.value.unshift({
    content: remarkForm.content,
    timestamp: new Date().toLocaleString(),
    operator: '当前用户',
    type: 'primary'
  });
  ElMessage.success('备注添加成功');
  remarkDialogVisible.value = false;
};

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该宠物档案吗?', '提示', { type: 'warning' }).then(() => {
    tableData.value = tableData.value.filter((item) => item.id !== row.id);
    ElMessage.success('删除成功');
  });
};

const handleUploadFile = (file) => {
  form.avatar = URL.createObjectURL(file.raw);
};

const handleUploadVaccineCert = (file) => {
  form.vaccineCert = URL.createObjectURL(file.raw);
};

const saveData = () => {
  if (!form.name) return ElMessage.warning('请输入宠物姓名');
  if (!form.ownerId) return ElMessage.warning('请选择所属主人');

  const owner = userList.find((u) => u.id === form.ownerId);
  const saveData = {
    ...form,
    ownerName: owner ? owner.name : 'Unknown',
    ownerPhone: owner ? owner.phone : ''
  };

  if (isEdit.value) {
    const idx = tableData.value.findIndex((item) => item.id === form.id);
    if (idx !== -1) Object.assign(tableData.value[idx], saveData);
  } else {
    tableData.value.push({
      id: Date.now(),
      ...saveData
    });
  }
  ElMessage.success('保存成功');
  dialogVisible.value = false;
};
</script>

<script>
// Separate setup logic needed for function declarations not hoisted? No, script setup handles it.
// Additional functions
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title {
  font-weight: bold;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar-uploader-icon:hover {
  border-color: var(--el-color-primary);
}
.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}
.profile-basic {
  margin-left: 20px;
}
.name-row {
  display: flex;
  align-items: center;
}
.name {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
  line-height: 1.2;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
