<template>
  <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 v-if="editable" style="margin-left: auto">
        <el-button type="primary" size="small" plain @click="handleRemark">添加备注</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 ? proxy.parseTime(currentPet.arrivalTime, '{y}-{m}-{d}') : '-' }}</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="historyOrders" border style="width: 100%">
          <el-table-column prop="code" label="订单编号" width="180" />
          <el-table-column label="服务项目">
            <template #default="scope">
              {{ getServiceName(scope.row.service) }}
            </template>
          </el-table-column>
          <el-table-column prop="serviceTime" label="服务时间" width="180" />
          <el-table-column prop="price" label="金额" width="100">
            <template #default="scope">
              {{ scope.row.price ? (scope.row.price / 100).toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getOrderStatusType(scope.row.status)" size="small">
                {{ getOrderStatusName(scope.row.status) }}
              </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">
            [{{ changeLogType[log.logType] || log.logType }}] {{ 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>

    <!-- Remark Dialog (Internal) -->
    <el-dialog v-model="remarkDialogVisible" title="添加备注" width="400px" append-to-body>
      <el-input v-model="remarkContent" 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>
  </el-drawer>
</template>

<script setup name="PetDetailDrawer">
import { ref, computed, watch, onMounted, getCurrentInstance, toRefs } from 'vue'
import { getPet, updatePet, updatePetRemark } from '@/api/archieves/pet'
import { listAllChangeLog } from '@/api/archieves/changeLog'
import { listSubOrderOnPet } from '@/api/order/subOrder/index'
import { ElMessage } from 'element-plus'
import archievesEnum from '@/json/archieves.json'

const { changeLogType } = archievesEnum

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  petId: {
    type: [String, Number],
    default: null
  },
  editable: {
    type: Boolean,
    default: false
  },
  // 父组件传入的服务列表，避免重复请求接口
  serviceList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'remark-saved'])

const drawerVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

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

const currentPet = ref({})
const changeLogs = ref([])
const historyOrders = ref([])
const detailActiveTab = ref('info')
const remarkDialogVisible = ref(false)
const remarkContent = ref('')
const internalServiceList = ref([])

// 优先使用父组件传入的服务列表数据，若无则使用内部加载的数据
const serviceOptions = computed(() => (props.serviceList && props.serviceList.length > 0) ? props.serviceList : internalServiceList.value)

const getServiceList = () => {
  if (props.serviceList && props.serviceList.length > 0) return;
  import('@/api/service/list/index').then(api => {
    api.listAllService().then((res) => {
      internalServiceList.value = res.data || [];
    });
  });
};

const getServiceName = (serviceId) => {
  const item = serviceOptions.value.find((i) => i.id === serviceId)
  return item ? item.name : '未知服务'
}

const getOrderStatusName = (status) => {
  const map = { 0: '待派单', 1: '待接单', 2: '待服务', 3: '服务中', 4: '已完成', 5: '已取消' }
  return map[status] || '未知'
}

const getOrderStatusType = (status) => {
  const map = { 0: 'info', 1: 'warning', 2: 'primary', 3: 'success', 4: 'success', 5: 'danger' }
  return map[status] || 'info'
}

const loadData = async (id) => {
  if (!id) return
  currentPet.value = {}
  changeLogs.value = []
  historyOrders.value = []

  getPet(id).then((res) => {
    currentPet.value = res.data || {}
  })

  listAllChangeLog(id, 'pet').then((res) => {
    changeLogs.value = res.data || []
  })

  listSubOrderOnPet(id).then((res) => {
    historyOrders.value = res.data || []
  })

  getServiceList()
}

const handleRemark = () => {
  remarkContent.value = ''
  remarkDialogVisible.value = true
}

const saveRemark = () => {
  if (!remarkContent.value) return ElMessage.warning('请输入内容')
  const data = { petId: props.petId, content: remarkContent.value }
  updatePetRemark(data).then(() => {
    ElMessage.success('备注添加成功')
    remarkDialogVisible.value = false
    loadData(props.petId)
    emit('remark-saved')
  })
}

// 暴露刷新方法
defineExpose({ refresh: () => loadData(props.petId) })

watch(() => props.visible, (val) => {
  if (val && props.petId) {
    detailActiveTab.value = 'info'
    loadData(props.petId)
  }
})

onMounted(() => {
  if (props.visible && props.petId) {
    getServiceList()
  }
})
</script>

<style scoped>
.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;
  margin-right: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
  line-height: 1.2;
}
</style>
