<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:edit']">备注</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>

    <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="avatarDisplayUrl" :src="avatarDisplayUrl" :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.userId" 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-select v-model="form.gender" placeholder="请选择">
                    <el-option v-for="dict in sys_pet_gender" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                  </el-select>
                </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="dict in sys_pet_breed" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </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 v-for="dict in sys_pet_size" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </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.tagIds" multiple placeholder="选择标签" style="width: 100%">
                    <el-option v-for="tag in allPetTags" :key="tag.id" :label="tag.name" :value="tag.id">
                      <el-tag :type="tag.colorType || 'info'" 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 v-for="dict in sys_house_type" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="入门方式">
              <el-radio-group v-model="form.entryMethod">
                <el-radio v-for="dict in sys_entry_method" :key="dict.value" :value="dict.value">{{ dict.label }}</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.vaccineStatus">
                <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="vaccineCertDisplayUrl" :src="vaccineCertDisplayUrl" 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" :loading="submitLoading" @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.avatarUrl" />
        <div class="profile-basic">
          <div class="name-row">
            <span class="name">{{ currentPet.name }}</span>
            <dict-tag :options="sys_pet_gender" :value="currentPet.gender" />
            <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.id" :type="tag.colorType || 'info'" effect="light" size="small" style="margin-right: 5px">
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
        <div style="margin-left: auto">
          <el-button type="primary" size="small" plain @click="handleRemark(currentPet)" v-hasPermi="['archieves:pet:edit']">添加备注</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="体型">
              <dict-tag :options="sys_pet_size" :value="currentPet.size" />
            </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="房屋类型">
              <dict-tag :options="sys_house_type" :value="currentPet.houseType" />
            </el-descriptions-item>
            <el-descriptions-item label="入门方式">
              <dict-tag :options="sys_entry_method" :value="currentPet.entryMethod" />
            </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.vaccineStatus || '-' }}</div>
              <div v-if="currentPet.vaccineCertUrl" style="margin-top: 10px">
                <el-image
                  style="width: 100px; height: 100px; border-radius: 4px"
                  :src="currentPet.vaccineCertUrl"
                  :preview-src-list="[currentPet.vaccineCertUrl]"
                  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="(log, index) in changeLogs" :key="index" :timestamp="log.createTime" type="primary">
              [{{ log.changeType }}] {{ log.content }}
              <div style="font-size: 12px; color: #999; margin-top: 4px">操作人: {{ log.operatorName }}</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, onMounted, getCurrentInstance, toRefs } from 'vue';
import { globalHeaders } from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listPet, getPet, addPet, updatePet, delPet } from '@/api/archieves/pet';
import { listAllTag } from '@/api/archieves/tag';
import { listAllCustomer } from '@/api/archieves/customer';
import { listAllChangeLog } from '@/api/archieves/changeLog';

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

const loading = ref(false);
const submitLoading = 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 remarkDialogVisible = ref(false);
const isEdit = ref(false);
const activeTab = ref('basic');
const detailActiveTab = ref('info');
const currentPet = ref({});

const allPetTags = ref([]);
const userList = ref([]);
const changeLogs = 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 remarkForm = reactive({ content: '' });
const avatarDisplayUrl = ref('');
const vaccineCertDisplayUrl = ref('');


const form = reactive({
  id: undefined,
  userId: undefined,
  avatar: undefined,
  name: '',
  type: 0,
  gender: undefined,
  breed: '',
  birthday: '',
  age: 1,
  weight: 5,
  size: 'small',
  isSterilized: 0,
  arrivalTime: '',
  houseType: '',
  entryMethod: '',
  entryPassword: '',
  keyLocation: '',
  personality: '',
  cutePersonality: '',
  healthStatus: '健康',
  aggression: 0,
  vaccineStatus: '无',
  vaccineCert: undefined,
  medicalHistory: '',
  allergies: '',
  remark: '',
  tagIds: []
});

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 = () => {
  isEdit.value = false;
  activeTab.value = 'basic';
  Object.assign(form, {
    id: undefined, userId: undefined, avatar: undefined, name: '', type: 0, gender: undefined,
    breed: '', birthday: '', age: 1, weight: 5, size: 'small', isSterilized: 0,
    arrivalTime: '', houseType: '', entryMethod: '', entryPassword: '', keyLocation: '',
    personality: '', cutePersonality: '', healthStatus: '健康', aggression: 0,
    vaccineStatus: '无', vaccineCert: undefined, medicalHistory: '', allergies: '', remark: '', tagIds: []
  });
  avatarDisplayUrl.value = '';
  vaccineCertDisplayUrl.value = '';
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  isEdit.value = true;
  activeTab.value = 'basic';
  getPet(row.id).then((res) => {
    const data = res.data;
    Object.assign(form, {
      id: data.id, userId: data.userId, avatar: data.avatar, name: data.name, type: data.type,
      gender: data.gender, breed: data.breed, birthday: data.birthday, age: data.age,
      weight: data.weight, size: data.size, isSterilized: data.isSterilized,
      arrivalTime: data.arrivalTime, houseType: data.houseType, entryMethod: data.entryMethod,
      entryPassword: data.entryPassword, keyLocation: data.keyLocation,
      personality: data.personality, cutePersonality: data.cutePersonality,
      healthStatus: data.healthStatus, aggression: data.aggression,
      vaccineStatus: data.vaccineStatus, vaccineCert: data.vaccineCert,
      medicalHistory: data.medicalHistory, allergies: data.allergies, remark: data.remark,
      tagIds: data.tags ? data.tags.map(t => t.id) : []
    });
    avatarDisplayUrl.value = data.avatarUrl || '';
    vaccineCertDisplayUrl.value = data.vaccineCertUrl || '';
    dialogVisible.value = true;
  });
};

const handleDetail = (row) => {
  getPet(row.id).then((res) => {
    currentPet.value = res.data;
    detailActiveTab.value = 'info';
    listAllChangeLog(row.id, 'pet').then((logRes) => {
      changeLogs.value = logRes.data || [];
    });
    drawerVisible.value = true;
  });
};

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

const saveRemark = () => {
  if (!remarkForm.content) return ElMessage.warning('请输入内容');
  const data = { id: currentPet.value.id, remark: remarkForm.content };
  updatePet(data).then(() => {
    ElMessage.success('备注添加成功');
    remarkDialogVisible.value = false;
    getList();
  });
};

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

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadUrl = baseUrl + '/resource/oss/upload';

const handleUploadFile = async (file) => {
  const formData = new FormData();
  formData.append('file', file.raw);
  try {
    const headers = globalHeaders();
    const res = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Authorization': headers.Authorization,
        'clientid': headers.clientid
      },
      body: formData
    });
    const result = await res.json();
    if (result.code === 200) {
      form.avatar = result.data.ossId;
      avatarDisplayUrl.value = result.data.url;
    } else {
      ElMessage.error(result.msg || '头像上传失败');
    }
  } catch (e) {
    ElMessage.error('头像上传失败');
  }
};

const handleUploadVaccineCert = async (file) => {
  const formData = new FormData();
  formData.append('file', file.raw);
  try {
    const headers = globalHeaders();
    const res = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Authorization': headers.Authorization,
        'clientid': headers.clientid
      },
      body: formData
    });
    const result = await res.json();
    if (result.code === 200) {
      form.vaccineCert = result.data.ossId;
      vaccineCertDisplayUrl.value = result.data.url;
    } else {
      ElMessage.error(result.msg || '疫苗凭证上传失败');
    }
  } catch (e) {
    ElMessage.error('疫苗凭证上传失败');
  }
};

const saveData = () => {
  if (!form.name) return ElMessage.warning('请输入宠物姓名');
  if (!form.userId) return ElMessage.warning('请选择所属主人');
  submitLoading.value = true;
  const api = isEdit.value ? updatePet(form) : addPet(form);
  api.then(() => {
    ElMessage.success('保存成功');
    dialogVisible.value = false;
    getList();
  }).finally(() => {
    submitLoading.value = false;
  });
};

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