<template>
	<view class="pet-add-page">
		<nav-bar title="新增宠物档案"></nav-bar>
		
		<!-- 基础信息 -->
		<view class="section-title">基础信息</view>
		<view class="form-card">
			<view class="form-item">
				<text class="form-label require">宠物名称</text>
				<input class="form-input" v-model="form.name" placeholder="请输入宠物名称" />
			</view>
			<view class="form-item">
				<text class="form-label require">所属主人</text>
				<picker :range="customerOptions" range-key="name" @change="onCustomerChange">
					<view class="picker-value" :class="{'placeholder': !form.userId}">{{ getCustomerLabel }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="form-label require">品种</text>
				<view class="form-combox-wrapper">
					<uni-combox :candidates="breedCandidates" v-model="form.breed" placeholder="可选择也可自填品种" emptyTips="未找到对应品种，可直接输入"></uni-combox>
				</view>
			</view>
			<view class="form-item">
				<text class="form-label">性别</text>
				<picker :range="genderOptions" range-key="label" @change="onGenderChange">
					<view class="picker-value">{{ getGenderLabel }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="form-label require">体型</text>
				<picker :range="sizeOptions" range-key="label" @change="onSizeChange">
					<view class="picker-value" :class="{'placeholder': !form.size}">{{ getSizeLabel }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="form-label require">年龄(岁)</text>
				<input class="form-input" v-model="form.age" type="number" placeholder="请输入年龄" />
			</view>
			<view class="form-item">
				<text class="form-label require">体重(kg)</text>
				<input class="form-input" v-model="form.weight" type="digit" placeholder="请输入体重" />
			</view>
		</view>

		<!-- 性格特征 -->
		<view class="section-title">性格特征</view>
		<view class="form-card">
			<view class="form-item">
				<text class="form-label">性格关键词</text>
				<input class="form-input" v-model="form.personality" placeholder="例如活泼、粘人" />
			</view>
			<view class="form-item vertical">
				<text class="form-label">萌宠性格描述</text>
				<textarea class="form-textarea" v-model="form.cutePersonality" placeholder="详细描述宠物的性格"></textarea>
			</view>
		</view>

		<!-- 家庭信息 -->
		<view class="section-title">家庭信息</view>
		<view class="form-card">
			<view class="form-item">
				<text class="form-label require">房屋类型</text>
				<picker :range="houseTypeOptions" range-key="label" @change="onHouseTypeChange">
					<view class="picker-value" :class="{'placeholder': !form.houseType}">{{ getHouseTypeLabel }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="form-label require">入门方式</text>
				<picker :range="entryMethodOptions" range-key="label" @change="onEntryMethodChange">
					<view class="picker-value" :class="{'placeholder': !form.entryMethod}">{{ getEntryMethodLabel }}</view>
				</picker>
			</view>
			<view class="form-item" v-if="form.entryMethod === 'password'">
				<text class="form-label require">门锁密码</text>
				<input class="form-input" v-model="form.entryPassword" placeholder="请输入门锁密码" />
			</view>
			<view class="form-item" v-if="form.entryMethod === 'key'">
				<text class="form-label require">钥匙存放处</text>
				<input class="form-input" v-model="form.keyLocation" placeholder="请输入取钥匙位置" />
			</view>
		</view>

		<!-- 健康状况 -->
		<view class="section-title">健康状况</view>
		<view class="form-card">
			<view class="form-item">
				<text class="form-label require">健康状态</text>
				<picker :range="healthStatusOptions" @change="onHealthChange">
					<view class="picker-value">{{ form.healthStatus || '请选择' }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="form-label require">疫苗接种</text>
				<picker :range="vaccineOptions" @change="onVaccineChange">
					<view class="picker-value">{{ form.vaccineStatus || '请选择' }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="form-label require">攻击倾向</text>
				<picker :range="aggressionOptions" range-key="label" @change="onAggressionChange">
					<view class="picker-value">{{ getAggressionLabel }}</view>
				</picker>
			</view>
			<view class="form-item vertical">
				<text class="form-label require">既往病史</text>
				<textarea class="form-textarea" v-model="form.medicalHistory" placeholder="如有病史请务必记录"></textarea>
			</view>
			<view class="form-item vertical">
				<text class="form-label require">过敏史</text>
				<textarea class="form-textarea" v-model="form.allergies" placeholder="如有过敏源请务必记录"></textarea>
			</view>
			<view class="form-item vertical">
				<text class="form-label">补充备注</text>
				<textarea class="form-textarea" v-model="form.remark" placeholder="请输入其他备注信息"></textarea>
			</view>
		</view>

		<!-- 底部固定操作栏 -->
		<view class="footer-bar">
			<button class="save-btn" @click="onSave">保存档案</button>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { addPet } from '@/api/archieves/pet'
import { listAllCustomer } from '@/api/archieves/customer'
import { getDicts } from '@/api/system/dict/data'
import navBar from '@/components/nav-bar/index.vue'
import customerEnums from '@/json/customer.json'

const genderOptions = [{ label: '未知', value: 0 }, { label: '公', value: 1 }, { label: '母', value: 2 }]
const sizeOptions = [{ label: '小型(0-10kg)', value: 'small' }, { label: '中型(10-25kg)', value: 'medium' }, { label: '大型(25kg+)', value: 'large' }]
const { houseTypeOptions, entryMethodOptions } = customerEnums
const healthStatusOptions = ['健康', '亚健康', '疾病']
const vaccineOptions = ['无', '已打1次', '已打2次', '已打3次']
const aggressionOptions = [{ label: '否', value: 0 }, { label: '是', value: 1 }]

const customerOptions = ref([])
const breedCandidates = ref([])

onLoad(async () => {
	try {
        const res = await listAllCustomer({ status: 0 })
        customerOptions.value = Array.isArray(res) ? res : (res?.data || [])
    } catch(e) {
		console.error('获取主人列表失败', e)
	}

	try {
		const dictRes = await getDicts('sys_pet_breed')
		const list = Array.isArray(dictRes) ? dictRes : (dictRes?.data || [])
		// 提取中文名给 combox，RuoYi 系统对应的字段可能是 dictLabel/dictValue
		breedCandidates.value = list.map(item => item.dictLabel || item.dictValue || item.label || item.value)
	} catch(e) {
		console.error('获取宠物品种字典失败', e)
	}
})

const form = reactive({
	name: '', userId: '', breed: '', gender: 0, age: '', weight: '', size: '',
	houseType: '', entryMethod: '', entryPassword: '', keyLocation: '',
	personality: '', cutePersonality: '', healthStatus: '健康', aggression: 0,
	vaccineStatus: '无', medicalHistory: '', allergies: '', remark: ''
})

const getCustomerLabel = computed(() => {
    const c = customerOptions.value.find(i => i.id === form.userId)
    return c ? `${c.name} - ${c.phone}` : '请选择主人'
})

const getGenderLabel = computed(() => genderOptions.find(i => i.value === form.gender)?.label || '请选择')
const getSizeLabel = computed(() => sizeOptions.find(i => i.value === form.size)?.label || '请选择')
const getHouseTypeLabel = computed(() => houseTypeOptions.find(i => i.value === form.houseType)?.label || '请选择')
const getEntryMethodLabel = computed(() => entryMethodOptions.find(i => i.value === form.entryMethod)?.label || '请选择')
const getAggressionLabel = computed(() => aggressionOptions.find(i => i.value === form.aggression)?.label || '请选择')

const onCustomerChange = (e) => { form.userId = customerOptions.value[e.detail.value]?.id }
const onGenderChange = (e) => { form.gender = genderOptions[e.detail.value].value }
const onSizeChange = (e) => { form.size = sizeOptions[e.detail.value].value }
const onHouseTypeChange = (e) => { form.houseType = houseTypeOptions[e.detail.value].value }
const onEntryMethodChange = (e) => { form.entryMethod = entryMethodOptions[e.detail.value].value }
const onHealthChange = (e) => { form.healthStatus = healthStatusOptions[e.detail.value] }
const onVaccineChange = (e) => { form.vaccineStatus = vaccineOptions[e.detail.value] }
const onAggressionChange = (e) => { form.aggression = aggressionOptions[e.detail.value].value }

const onSave = async () => {
  if (!form.name) return uni.showToast({ title: '请输入宠物名称', icon: 'none' })
  if (!form.userId) return uni.showToast({ title: '请选择所属主人', icon: 'none' })
  if (!form.breed) return uni.showToast({ title: '请输入品种', icon: 'none' })
  if (!form.size) return uni.showToast({ title: '请选择体型', icon: 'none' })
  if (!form.weight) return uni.showToast({ title: '请输入体重', icon: 'none' })
  if (!form.age) return uni.showToast({ title: '请输入年龄', icon: 'none' })
  if (!form.houseType) return uni.showToast({ title: '请选择家庭房屋类型', icon: 'none' })
  if (!form.entryMethod) return uni.showToast({ title: '请选择入门方式', icon: 'none' })
  if (form.entryMethod === 'password' && !form.entryPassword) return uni.showToast({ title: '请输入门锁密码', icon: 'none' })
  if (form.entryMethod === 'key' && !form.keyLocation) return uni.showToast({ title: '请输入钥匙存放位置', icon: 'none' })
  if (!form.healthStatus) return uni.showToast({ title: '请选择健康状态', icon: 'none' })
  if (!form.vaccineStatus) return uni.showToast({ title: '请选择疫苗情况', icon: 'none' })
  if (!form.medicalHistory) return uni.showToast({ title: '请输入既往病史', icon: 'none' })
  if (!form.allergies) return uni.showToast({ title: '请输入过敏史', icon: 'none' })

  try {
      uni.showLoading({ title: '保存中' })
      await addPet(form)
      uni.hideLoading()
      uni.showToast({ title: '新增成功', icon: 'success' })
      setTimeout(() => uni.navigateBack(), 1000)
  } catch (error) {
      uni.hideLoading()
      uni.showToast({ title: '保存失败', icon: 'none' })
  }
}
</script>

<style lang="scss" scoped>
.pet-add-page { min-height: 100vh; background: #f7f8fa; padding-bottom: calc(140rpx + env(safe-area-inset-bottom)); }
.section-title { font-size: 28rpx; font-weight: bold; color: #666; padding: 24rpx 32rpx 12rpx; }
.form-card { background: #fff; border-radius: 24rpx; padding: 8rpx 32rpx; margin: 0 24rpx; }
.form-item { display: flex; align-items: center; padding: 28rpx 0; border-bottom: 1rpx solid #f5f5f5; }
.form-item:last-child { border-bottom: none; }
.form-item.vertical { flex-direction: column; align-items: flex-start; border-bottom: none; }
.form-item.vertical .form-textarea { width: 100%; height: 160rpx; margin-top: 16rpx; background: #f9f9f9; padding: 16rpx; box-sizing: border-box; border-radius: 12rpx; }
.form-label { width: 220rpx; font-size: 28rpx; color: #333; flex-shrink: 0; }
.form-label.require::before { content: '*'; color: #f56c6c; margin-right: 4rpx; }
.form-input { flex: 1; font-size: 28rpx; color: #333; text-align: right; }
.form-combox-wrapper { flex: 1; min-width: 0; }
.picker-value { flex: 1; font-size: 28rpx; color: #333; text-align: right; min-height: 40rpx; }
.picker-value.placeholder { color: #ccc; }
.footer-bar { position: fixed; bottom: 0; left: 0; right: 0; background: #fff; padding: 20rpx 32rpx calc(20rpx + env(safe-area-inset-bottom)); box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05); z-index: 100; }
.save-btn { width: 100%; height: 88rpx; background: linear-gradient(90deg, #ffd53f, #ff9500); color: #333; border: none; border-radius: 44rpx; font-size: 32rpx; font-weight: bold; line-height: 88rpx; }

:deep(.uni-combox) { border: none !important; }
:deep(.uni-combox__input-box) { display: flex; justify-content: flex-end; padding-right: 0; }
:deep(.uni-combox__input) { text-align: right; font-size: 28rpx; padding-right: 0;}
:deep(.uni-combox__input-plholder) { color: #ccc; text-align: right; font-size: 28rpx; padding-right: 0;}
</style>
