<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
              @keyup.enter="handleSearch" @clear="handleSearch" />
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['archieves:pet:add']">新增档案</el-button>
          </div>
        </div>
      </template>

      <el-table :data="tableData" v-loading="loading" 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.avatarUrl" 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">
            <dict-tag :options="sys_pet_gender" :value="scope.row.gender" />
          </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.id" :type="tag.colorType || 'info'" effect="light"
              size="small" style="margin-right: 5px">{{
                tag.name
              }}</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.vaccineStatus || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)"
              v-hasPermi="['archieves:pet:query']">详情</el-button>
            <el-button link type="primary" @click="handleEdit(scope.row)"
              v-hasPermi="['archieves:pet:edit']">编辑</el-button>
            <el-button link type="primary" @click="handleRemark(scope.row)"
              v-hasPermi="['archieves:pet:remark']">备注</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)"
              v-hasPermi="['archieves:pet:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="getList" @current-change="getList" />
      </div>
    </el-card>

    <AddPetDialog v-model:visible="dialogVisible" :user-options="userList" :pet-data="petEditData"
      @success="onPetSaved" />

    <!-- Pet Profile Drawer -->
    <PetDetailDrawer v-model:visible="drawerVisible" :pet-id="currentPet.id" :service-list="serviceList" editable
      @remark-saved="getList" />

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listPet, getPet, delPet } from '@/api/archieves/pet'
import { listAllTag } from '@/api/archieves/tag'
import { listAllCustomer } from '@/api/archieves/customer'
import { listAllService } from '@/api/service/list/index'
import PetDetailDrawer from '@/components/PetDetailDrawer/index.vue'
import AddPetDialog from '@/components/AddPetDialog/index.vue'

const { proxy } = getCurrentInstance();
const { sys_pet_gender, sys_pet_type, sys_pet_size } = toRefs(
  proxy?.useDict('sys_pet_gender', 'sys_pet_type', 'sys_pet_size')
);

const loading = ref(false);
const total = ref(0);
const tableData = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
});

const searchKey = ref('');

const dialogVisible = ref(false);
const drawerVisible = ref(false);
const currentPet = ref({});

const allPetTags = ref([]);
const userList = ref([]);
const petEditData = ref(null);
const serviceList = ref([]);

const getServiceList = () => {
  listAllService().then((res) => {
    serviceList.value = res.data || []
  })
}

const getList = () => {
  loading.value = true;
  queryParams.keyword = searchKey.value;
  listPet(queryParams).then((res) => {
    tableData.value = res.rows;
    total.value = res.total;
  }).finally(() => {
    loading.value = false;
  });
};

const handleSearch = () => {
  queryParams.pageNum = 1;
  getList();
};

const loadTags = () => {
  listAllTag({ category: 'pet', status: 0 }).then((res) => {
    allPetTags.value = res.data || [];
  });
};

const loadUsers = () => {
  listAllCustomer({ status: 0 }).then((res) => {
    userList.value = res.data || [];
  });
};

const handleAdd = () => {
  petEditData.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  getPet(row.id).then((res) => {
    petEditData.value = res.data
    dialogVisible.value = true
  })
}

const onPetSaved = () => {
  dialogVisible.value = false
  getList()
}

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

const handleRemark = (row) => {
  currentPet.value = row
  drawerVisible.value = true
  // 由于备注功能已集成在详情抽屉中，直接打开抽屉即可，后期可以根据需要调整是否直接弹出备注对话框
}

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

onMounted(() => {
  getList();
  loadTags();
  loadUsers();
  getServiceList();
});
</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>
