<template>
  <el-dialog :model-value="visible" @update:model-value="$emit('update:visible', $event)"
    :title="isEdit ? '编辑宠物' : '新增宠物'" width="780px" 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="88" class="avatar-preview" />
          <div v-else class="avatar-placeholder">
            <el-icon :size="32">
              <Plus />
            </el-icon>
            <span>上传头像</span>
          </div>
        </el-upload>
      </div>

      <el-form :model="form" label-width="90px" label-position="top" class="pet-form">
        <!-- 基本信息 -->
        <div class="section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="24">
            <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-row>
          <el-row :gutter="24">
            <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-row>
          <el-form-item label="萌宠性格">
            <el-input v-model="form.cutePersonality" type="textarea" :rows="2" placeholder="详细描述萌宠的性格特点" />
          </el-form-item>
        </div>

        <!-- 家庭信息 -->
        <div class="section">
          <div class="section-title">家庭信息</div>
          <el-row :gutter="24">
            <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="入门方式" required>
                <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>

        <!-- 健康状况 -->
        <div class="section">
          <div class="section-title">健康状况</div>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="健康状态" required>
                <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="6">
              <el-form-item label="攻击倾向" required>
                <el-switch v-model="form.aggression" active-text="是" inactive-text="否" :active-value="1"
                  :inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <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 :span="6">
              <el-form-item label="疫苗凭证">
                <el-upload class="cert-uploader" action="#" :show-file-list="false" :auto-upload="false"
                  :on-change="handleUploadVaccineCert">
                  <img v-if="vaccineCertDisplayUrl" :src="vaccineCertDisplayUrl" class="cert-preview" />
                  <div v-else class="cert-placeholder">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    <span>上传</span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="既往病史" required>
                <el-input v-model="form.medicalHistory" type="textarea" :rows="2" placeholder="如有病史请记录" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="过敏史" required>
                <el-input v-model="form.allergies" type="textarea" :rows="2" placeholder="如有过敏源请记录" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </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 } 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 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 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) return ElMessage.warning('请选择入门方式')
  if (form.entryMethod === 'password' && !form.entryPassword) return ElMessage.warning('请输入门锁密码')
  if (form.entryMethod === 'key' && !form.keyLocation) return ElMessage.warning('请输入钥匙存放位置')
  if (!form.healthStatus) return ElMessage.warning('请选择健康状态')
  if (form.aggression === undefined || form.aggression === null) return ElMessage.warning('请选择是否有攻击倾向')
  if (!form.vaccineStatus) return ElMessage.warning('请选择疫苗情况')
  if (!form.medicalHistory) return ElMessage.warning('请输入既往病史')
  if (!form.allergies) 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 24px 0;
  max-height: 62vh;
  overflow-y: auto;
}

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

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

.avatar-uploader {
  cursor: pointer;
}

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

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

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

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

.section {
  margin-bottom: 8px;
  padding: 16px 20px 4px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 14px;
  padding-left: 10px;
  border-left: 3px solid #409eff;
}

.cert-uploader {
  cursor: pointer;
}

.cert-preview {
  width: 72px;
  height: 72px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.cert-placeholder {
  width: 72px;
  height: 72px;
  border-radius: 6px;
  border: 2px dashed #dcdfe6;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #a8abb2;
  font-size: 12px;
  gap: 2px;
  transition: all 0.3s;
}

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

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