<template>
  <el-dialog :model-value="visible" @update:model-value="$emit('update:visible', $event)"
    :title="isEdit ? '编辑宠物' : '新增宠物'" width="880px" destroy-on-close append-to-body class="add-pet-dialog">
    <div class="dialog-body">
      <!-- 头像区 -->
      <div class="avatar-section">
        <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" class="avatar-preview" />
          <div v-else class="avatar-placeholder">
            <el-icon :size="28">
              <Plus />
            </el-icon>
            <span>上传头像</span>
          </div>
        </el-upload>
      </div>

      <el-form :model="form" label-position="top" class="pet-form">
        <!-- 基本信息 -->
        <div class="section-heading">
          <span class="section-line"></span>
          <span class="section-text">基本信息</span>
          <span class="section-line"></span>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="宠物姓名" required><el-input v-model="form.name" placeholder="请输入" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属主人" required>
              <el-select v-model="form.userId" placeholder="选择主人" filterable :disabled="lockedOwner">
                <el-option v-for="user in userOptions" :key="user.id"
                  :label="user.name + ' - ' + (user.phone || user.phoneNumber || '')" :value="user.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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="8">
            <el-form-item label="品种" required><el-input v-model="form.breed" placeholder="请输入" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="体型" required>
              <el-select v-model="form.size">
                <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="4">
            <el-form-item label="体重(kg)" required>
              <el-input-number v-model="form.weight" :min="0" :precision="1" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="年龄" required>
              <el-input-number v-model="form.age" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性格关键词">
              <el-input v-model="form.personality" placeholder="如：活泼、粘人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宠物标签">
              <el-select v-model="form.tagIds" multiple placeholder="选择标签" collapse-tags collapse-tags-tooltip>
                <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-col :span="24">
            <el-form-item label="萌宠性格">
              <el-input v-model="form.cutePersonality" type="textarea" :rows="2" placeholder="详细描述萌宠的性格特点" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 家庭信息 -->
        <div class="section-heading">
          <span class="section-line"></span>
          <span class="section-text">家庭信息</span>
          <span class="section-line"></span>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="新来家庭时间">
              <el-date-picker v-model="form.arrivalTime" type="date" placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家庭房屋类型" required>
              <el-select v-model="form.houseType" placeholder="请选择">
                <el-option v-for="dict in sys_house_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入门方式">
              <el-select v-model="form.entryMethod" placeholder="请选择">
                <el-option v-for="dict in sys_entry_method" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.entryMethod === 'password'">
            <el-form-item label="门锁密码" required>
              <el-input v-model="form.entryPassword" placeholder="请输入门锁密码" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.entryMethod === 'key'">
            <el-form-item label="钥匙位置" required>
              <el-input v-model="form.keyLocation" placeholder="如：地毯下" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 健康状况 -->
        <div class="section-heading">
          <span class="section-line"></span>
          <span class="section-text">健康状况</span>
          <span class="section-line"></span>
        </div>
        <el-row :gutter="20">
          <el-col :span="showVaccineCert ? 6 : 8">
            <el-form-item label="健康状态">
              <el-select v-model="form.healthStatus" placeholder="请选择">
                <el-option value="健康" label="健康" />
                <el-option value="亚健康" label="亚健康" />
                <el-option value="疾病" label="疾病" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="showVaccineCert ? 6 : 8">
            <el-form-item label="攻击倾向">
              <el-switch v-model="form.aggression" active-text="是" inactive-text="否" :active-value="1"
                :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="showVaccineCert ? 6 : 8">
            <el-form-item label="疫苗情况" required>
              <el-select v-model="form.vaccineStatus" placeholder="请选择">
                <el-option value="无" label="无" />
                <el-option value="已打1次" label="已打1次" />
                <el-option value="已打2次" label="已打2次" />
                <el-option value="已打3次" label="已打3次" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="showVaccineCert" :span="6">
            <el-form-item label="疫苗凭证">
              <div class="cert-row">
                <div class="cert-box" :class="{ 'has-image': vaccineCertDisplayUrl }">
                  <el-image v-if="vaccineCertDisplayUrl" :src="vaccineCertDisplayUrl" class="cert-thumb"
                    :preview-src-list="[vaccineCertDisplayUrl]" fit="cover" />
                  <el-icon v-else :size="18" class="cert-plus-icon">
                    <Plus />
                  </el-icon>
                  <div v-if="!vaccineCertDisplayUrl" class="cert-upload-mask" @click="triggerVaccineCertUpload" />
                </div>
                <el-upload ref="vaccineCertUploadRef" style="display:none" action="#" :show-file-list="false"
                  :auto-upload="false" :on-change="handleUploadVaccineCert" />
                <div v-if="vaccineCertDisplayUrl" class="cert-actions">
                  <span class="cert-action-icon cert-action-edit" @click="triggerVaccineCertUpload">
                    <el-icon :size="14">
                      <Edit />
                    </el-icon>
                  </span>
                  <span class="cert-action-icon cert-action-del" @click="removeVaccineCert">
                    <el-icon :size="14">
                      <Delete />
                    </el-icon>
                  </span>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="既往病史">
              <el-input v-model="form.medicalHistory" type="textarea" :rows="2" placeholder="如有病史请记录" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过敏史">
              <el-input v-model="form.allergies" type="textarea" :rows="2" placeholder="如有过敏源请记录" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)" size="large">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="saveData" size="large">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted, getCurrentInstance, toRefs, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { globalHeaders } from '@/utils/request'
import { addPet, updatePet } from '@/api/archieves/pet'
import { getCustomer } from '@/api/archieves/customer'
import { listAllTag } from '@/api/archieves/tag'

const props = defineProps({
  visible: { type: Boolean, default: false },
  userId: { type: [String, Number], default: undefined },
  userOptions: { type: Array, default: () => [] },
  lockedOwner: { type: Boolean, default: false },
  petData: { type: Object, default: null }
})

const emit = defineEmits(['update:visible', 'success'])

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 submitLoading = ref(false)
const allPetTags = ref([])
const avatarDisplayUrl = ref('')
const vaccineCertDisplayUrl = ref('')
const isEdit = ref(false)

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

const defaultForm = () => ({
  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 form = reactive(defaultForm())

watch(() => props.visible, (val) => {
  if (val) {
    submitLoading.value = false
    avatarDisplayUrl.value = ''
    vaccineCertDisplayUrl.value = ''
    if (props.petData) {
      isEdit.value = true
      const d = props.petData
      Object.assign(form, {
        id: d.id, userId: d.userId, avatar: d.avatar,
        name: d.name, type: d.type, gender: d.gender,
        breed: d.breed, birthday: d.birthday || '',
        age: d.age, weight: d.weight, size: d.size,
        isSterilized: d.isSterilized, arrivalTime: d.arrivalTime || '',
        houseType: d.houseType || '', entryMethod: d.entryMethod || '',
        entryPassword: d.entryPassword || '', keyLocation: d.keyLocation || '',
        personality: d.personality || '', cutePersonality: d.cutePersonality || '',
        healthStatus: d.healthStatus || '健康', aggression: d.aggression ?? 0,
        vaccineStatus: d.vaccineStatus || '无', vaccineCert: d.vaccineCert,
        medicalHistory: d.medicalHistory || '', allergies: d.allergies || '',
        remark: d.remark || '',
        tagIds: d.tags ? d.tags.map(t => t.id) : (d.tagIds || [])
      })
      avatarDisplayUrl.value = d.avatarUrl || ''
      vaccineCertDisplayUrl.value = d.vaccineCertUrl || ''
    } else {
      isEdit.value = false
      Object.assign(form, defaultForm())
      form.userId = props.userId || undefined
      if (props.userId) fetchAndFillOwnerInfo(props.userId)
    }
  }
})

watch(() => form.userId, (newUserId) => {
  if (!newUserId || isEdit.value) return
  fetchAndFillOwnerInfo(newUserId)
})

const fetchAndFillOwnerInfo = (userId) => {
  getCustomer(userId).then((res) => {
    const data = res.data
    if (data) {
      if (!form.houseType) form.houseType = data.houseType || ''
      if (!form.entryMethod) form.entryMethod = data.entryMethod || ''
      if (!form.entryPassword) form.entryPassword = data.entryPassword || ''
      if (!form.keyLocation) form.keyLocation = data.keyLocation || ''
    }
  }).catch(() => { })
}

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

const handleUploadFile = async (file) => {
  const fd = new FormData(); fd.append('file', file.raw)
  try {
    const headers = globalHeaders()
    const res = await fetch(uploadUrl, { method: 'POST', headers: { 'Authorization': headers.Authorization, 'clientid': headers.clientid }, body: fd })
    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 vaccineCertUploadRef = ref(null)

const showVaccineCert = computed(() => form.vaccineStatus && form.vaccineStatus !== '无')

const handleUploadVaccineCert = async (file) => {
  const fd = new FormData(); fd.append('file', file.raw)
  try {
    const headers = globalHeaders()
    const res = await fetch(uploadUrl, { method: 'POST', headers: { 'Authorization': headers.Authorization, 'clientid': headers.clientid }, body: fd })
    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 triggerVaccineCertUpload = () => {
  const el = vaccineCertUploadRef.value?.$el || vaccineCertUploadRef.value
  const input = el?.querySelector?.('input[type="file"]')
  if (input) input.click()
}

const removeVaccineCert = () => {
  form.vaccineCert = undefined
  vaccineCertDisplayUrl.value = ''
}

const saveData = () => {
  if (!form.name) return ElMessage.warning('请输入宠物姓名')
  if (!form.userId) return ElMessage.warning('请选择所属主人')
  if (!form.breed) return ElMessage.warning('请输入品种')
  if (!form.size) return ElMessage.warning('请选择体型')
  if (form.weight === undefined || form.weight === null) return ElMessage.warning('请输入体重(kg)')
  if (form.age === undefined || form.age === null) return ElMessage.warning('请输入年龄(岁)')
  if (!form.houseType) return ElMessage.warning('请选择家庭房屋类型')
  if (form.entryMethod === 'password' && !form.entryPassword) return ElMessage.warning('请输入门锁密码')
  if (form.entryMethod === 'key' && !form.keyLocation) return ElMessage.warning('请输入钥匙存放位置')
  if (!form.vaccineStatus) return ElMessage.warning('请选择疫苗情况')
  submitLoading.value = true
  const data = { ...form, aggression: Number(form.aggression) || 0 }
  const api = isEdit.value ? updatePet(data) : addPet(data)
  api.then((res) => {
    ElMessage.success(isEdit.value ? '宠物档案更新成功' : '宠物档案保存成功')
    emit('success', res.data || data)
    emit('update:visible', false)
  }).finally(() => { submitLoading.value = false })
}

onMounted(() => { loadTags() })
</script>

<style scoped>
.add-pet-dialog :deep(.el-dialog__body) {
  padding: 0 36px 0;
  max-height: 62vh;
  overflow-y: auto;
}

.dialog-body {
  padding-top: 12px;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.avatar-uploader {
  cursor: pointer;
}

.avatar-preview {
  box-shadow: 0 2px 12px rgba(0, 0, 0, .1);
  border: 3px solid #fff;
  outline: 1px solid #e8e8e8;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px dashed #dcdfe6;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #a8abb2;
  font-size: 12px;
  gap: 2px;
  transition: all .3s;
}

.avatar-placeholder:hover {
  border-color: #409eff;
  color: #409eff;
}

.pet-form {
  padding-bottom: 12px;
}

.section-heading {
  display: flex;
  align-items: center;
  margin: 32px 0 20px;
}

.section-heading:first-of-type {
  margin-top: 0;
}

.section-line {
  flex: 1;
  height: 1px;
  background: #e8e8e8;
}

.section-text {
  padding: 0 20px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.cert-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cert-box {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  border: 1.5px dashed #d0d5dd;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  transition: border-color .25s, box-shadow .25s;
  cursor: pointer;
  flex-shrink: 0;
}

.cert-box:hover {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, .08);
}

.cert-plus-icon {
  color: #a0a5b0;
  transition: color .25s;
}

.cert-box:hover .cert-plus-icon {
  color: #409eff;
}

.cert-upload-mask {
  position: absolute;
  inset: 0;
  z-index: 1;
}

.cert-box.has-image {
  border-style: solid;
  border-color: #e4e7ed;
  cursor: default;
  box-shadow: 0 1px 4px rgba(0, 0, 0, .06);
}

.cert-box.has-image:hover {
  border-color: #e4e7ed;
  box-shadow: 0 1px 4px rgba(0, 0, 0, .06);
}

.cert-thumb {
  width: 100%;
  height: 100%;
}

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

.cert-action-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all .2s;
  color: #606266;
  background: #f5f6f8;
}

.cert-action-icon:hover {
  background: #ecf5ff;
  color: #409eff;
}

.cert-action-del:hover {
  background: #fef0f0;
  color: #f56c6c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 12px;
}
</style>
