<template>
	<view class="pet-add-page">
		<nav-bar title="新增宠物档案"></nav-bar>
		
		<!-- 宠物预览/头像上传 @Author: Antigravity -->
		<view class="avatar-section" @click="handleChooseAvatar">
			<image :src="tempAvatarUrl || '/static/images/profile.png'" class="avatar-img" mode="aspectFill"></image>
			<view class="avatar-tip">点击上传宠物头像</view>
		</view>

		<!-- 基础信息 -->
		<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" @click="showCustomerSearch = true">
				<text class="form-label require">所属主人</text>
				<view class="picker-value" :class="{'placeholder': !form.userId}">{{ getCustomerLabel }}</view>
				<!-- CSS 绘制右箭头 @Author: Antigravity -->
				<view class="right-arrow"></view>
			</view>
			<view class="form-item" @click="showBreedPicker = true">
				<text class="form-label require">品种</text>
				<view class="picker-value" :class="{'placeholder': !form.breed}">{{ form.breed || '可选择或自填品种' }}</view>
				<view class="right-arrow"></view>
			</view>
			<view class="form-item" @click="showGenderSelect = true">
				<text class="form-label">性别</text>
				<view class="picker-value">{{ getGenderLabel }}</view>
				<view class="right-arrow"></view>
			</view>
			<view class="form-item" @click="showSizeSelect = true">
				<text class="form-label require">体型</text>
				<view class="picker-value" :class="{'placeholder': !form.size}">{{ getSizeLabel }}</view>
				<view class="right-arrow"></view>
			</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" @click="showHouseTypeSelect = true">
				<text class="form-label require">房屋类型</text>
				<view class="picker-value" :class="{'placeholder': !form.houseType}">{{ getHouseTypeLabel }}</view>
				<view class="right-arrow"></view>
			</view>
			<view class="form-item" @click="showEntryMethodSelect = true">
				<text class="form-label require">入门方式</text>
				<view class="picker-value" :class="{'placeholder': !form.entryMethod}">{{ getEntryMethodLabel }}</view>
				<view class="right-arrow"></view>
			</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" @click="showHealthSelect = true">
				<text class="form-label require">健康状态</text>
				<view class="picker-value">{{ form.healthStatus || '请选择' }}</view>
				<view class="right-arrow"></view>
			</view>
			<view class="form-item" @click="showVaccineSelect = true">
				<text class="form-label require">疫苗接种</text>
				<view class="picker-value">{{ form.vaccineStatus || '请选择' }}</view>
				<view class="right-arrow"></view>
			</view>
			<view class="form-item" @click="showAggressionSelect = true">
				<text class="form-label require">攻击倾向</text>
				<view class="picker-value">{{ getAggressionLabel }}</view>
				<view class="right-arrow"></view>
			</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>

		<!-- 居中重构：主人搜索弹窗 @Author: Antigravity -->
		<view class="center-modal-mask" v-if="showCustomerSearch" @click="showCustomerSearch = false">
			<view class="center-modal-content" @click.stop>
				<view class="modal-header">
					<view class="search-box">
						<view class="search-icon"></view> 
						<input class="search-input" v-model="searchKeyword" placeholder="搜索主人姓名或手机号" focus />
						<view class="clear-icon" v-if="searchKeyword" @click="searchKeyword = ''"></view>
					</view>
				</view>
				<scroll-view scroll-y class="customer-list-scroll">
					<view class="customer-item" v-for="item in filteredCustomers" :key="item.id" @click="selectCustomer(item)">
						<view class="item-info">
							<text class="name">{{ item.name }}</text>
							<text class="phone">{{ item.phone }}</text>
						</view>
						<view class="checkmark" v-if="form.userId === item.id"></view>
					</view>
					<view class="empty-tip" v-if="filteredCustomers.length === 0">未找到匹配的主人</view>
				</scroll-view>
				<view class="modal-footer">
					<button class="modal-close-btn" @click="showCustomerSearch = false">关闭</button>
				</view>
			</view>
		</view>

		<!-- 居中重构：品种选择弹窗 @Author: Antigravity -->
		<view class="center-modal-mask" v-if="showBreedPicker" @click="closeBreedPicker">
			<view class="center-modal-content" @click.stop>
				<view class="modal-header">
					<view class="search-box">
						<view class="search-icon"></view>
						<input class="search-input" v-model="breedSearchKeyword" placeholder="查找品种..." focus />
					</view>
				</view>
				<scroll-view scroll-y class="customer-list-scroll">
					<view class="customer-item" v-for="(item, index) in filteredBreeds" :key="index" @click="selectBreed(item)">
						<text class="name">{{ item }}</text>
						<view class="checkmark" v-if="form.breed === item"></view>
					</view>
				</scroll-view>
				<view class="breed-footer">
					<input class="breed-custom-input" v-model="customBreedText" placeholder="或手动录入新品种" />
					<view class="add-confirm-btn" @click="confirmCustomBreed">添加</view>
				</view>
			</view>
		</view>

		<!-- 各项居中选择器组件实例 @Author: Antigravity -->
		<center-select v-model="showGenderSelect" title="选择性别" :options="genderOptions" :value="form.gender" @select="(item) => form.gender = item.value" />
		<center-select v-model="showSizeSelect" title="选择体型" :options="sizeOptions" :value="form.size" @select="(item) => form.size = item.value" />
		<center-select v-model="showHouseTypeSelect" title="房屋类型" :options="houseTypeOptions" :value="form.houseType" @select="(item) => form.houseType = item.value" />
		<center-select v-model="showEntryMethodSelect" title="入门方式" :options="entryMethodOptions" :value="form.entryMethod" @select="(item) => form.entryMethod = item.value" />
		<center-select v-model="showHealthSelect" title="当前健康状态" :options="healthStatusOptions" :value="form.healthStatus" @select="(item) => form.healthStatus = item" />
		<center-select v-model="showVaccineSelect" title="疫苗接种状态" :options="vaccineOptions" :value="form.vaccineStatus" @select="(item) => form.vaccineStatus = item" />
		<center-select v-model="showAggressionSelect" title="是否有攻击倾向" :options="aggressionOptions" :value="form.aggression" @select="(item) => form.aggression = item.value" />

	</view>
</template>

<script setup>
/**
 * @Author: Antigravity
 */
import { ref, reactive, computed, watch } 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 { uploadFile } from '@/api/system/oss'
import navBar from '@/components/nav-bar/index.vue'
import centerSelect from '@/components/center-select/index.vue'
import customerEnums from '@/json/customer.json'

// 状态控制
const showGenderSelect = ref(false)
const showSizeSelect = ref(false)
const showHouseTypeSelect = ref(false)
const showEntryMethodSelect = ref(false)
const showHealthSelect = ref(false)
const showVaccineSelect = ref(false)
const showAggressionSelect = ref(false)
const showCustomerSearch = ref(false)
const showBreedPicker = ref(false)
const tempAvatarUrl = ref('')

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([])
const searchKeyword = ref('')
const breedSearchKeyword = ref('')
const customBreedText = ref('')

const fetchCustomers = async () => {
	try {
        const res = await listAllCustomer({ status: 0 })
        const records = Array.isArray(res) ? res : (res?.data || [])
        customerOptions.value = records.map(item => ({
            id: item.id || item.userId,
            name: item.name || item.customerName,
            phone: item.phone || item.contactPhoneNumber || item.phone
        }))
    } catch(e) { console.error('获取主人列表失败', e) }
}

onLoad(async () => {
	await fetchCustomers()
	try {
		const dictRes = await getDicts('sys_pet_breed')
		const list = Array.isArray(dictRes) ? dictRes : (dictRes?.data || [])
		breedCandidates.value = list.map(item => item.dictLabel || item.dictValue || item.label || item.value)
	} catch(e) { console.error('获取宠物品种字典失败', e) }
})

const form = reactive({
	avatar: '',
	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 filteredCustomers = computed(() => {
	if (!searchKeyword.value) return customerOptions.value
	const kw = searchKeyword.value.toLowerCase().trim()
	return customerOptions.value.filter(item => 
		(item.name && item.name.toLowerCase().includes(kw)) || 
		(item.phone && item.phone.includes(kw))
	)
})

const selectCustomer = (customer) => {
	form.userId = customer.id
	showCustomerSearch.value = false
	searchKeyword.value = ''
}

const filteredBreeds = computed(() => {
	if (!breedSearchKeyword.value.trim()) return breedCandidates.value
	const kw = breedSearchKeyword.value.toLowerCase().trim()
	return breedCandidates.value.filter(item => item.toLowerCase().includes(kw))
})

const selectBreed = (breed) => {
	form.breed = breed
	showBreedPicker.value = false
	breedSearchKeyword.value = ''
}

const closeBreedPicker = () => {
	showBreedPicker.value = false
	breedSearchKeyword.value = ''
	customBreedText.value = ''
}

const confirmCustomBreed = () => {
	const val = customBreedText.value.trim()
	if (!val) return
	form.breed = val
	if (!breedCandidates.value.includes(val)) {
		breedCandidates.value.push(val)
	}
	showBreedPicker.value = false
	breedSearchKeyword.value = ''
	customBreedText.value = ''
}

// 选择并上传宠物头像
// @Author: Antigravity
const handleChooseAvatar = () => {
    uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
            try {
                uni.showLoading({ title: '上传中...' });
                const uploadRes = await uploadFile(res.tempFilePaths[0]);
                form.avatar = uploadRes.ossId; // 提交给后端的 ID
                tempAvatarUrl.value = uploadRes.url; // 用于预览的 URL
                uni.hideLoading();
                uni.showToast({ title: '头像上传成功', icon: 'success' });
            } catch (e) {
                uni.hideLoading();
                console.error('上传头像失败', e);
            }
        }
    });
}

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.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)); }

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40rpx 0;
    background-color: #fff;
    margin-bottom: 20rpx;
    border-bottom: 2rpx solid #f0f0f0;
    .avatar-img {
        width: 160rpx;
        height: 160rpx;
        border-radius: 80rpx;
        background-color: #f7f8fa;
        border: 4rpx solid #fff;
        box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.06);
    }
    .avatar-tip {
        margin-top: 16rpx;
        font-size: 24rpx;
        color: #ff9500;
        font-weight: 500;
    }
}
.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: 2rpx solid #EEEEEE; position: relative; }
.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; font-size: 28rpx; }
.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; }
.picker-value { flex: 1; font-size: 28rpx; color: #333; text-align: right; margin-right: 16rpx; }
.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: #fff; border: none; border-radius: 44rpx; font-size: 32rpx; font-weight: bold; line-height: 88rpx; &::after { border: none; } }

/* CSS 绘制右箭头 @Author: Antigravity */
.right-arrow {
	width: 14rpx;
	height: 14rpx;
	border-right: 3rpx solid #ccc;
	border-top: 3rpx solid #ccc;
	transform: rotate(45deg);
	flex-shrink: 0;
}

/* 居中弹窗通用样式 @Author: Antigravity */
.center-modal-mask {
	position: fixed;
	top: 0; left: 0; right: 0; bottom: 0;
	background: rgba(0,0,0,0.6);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
	backdrop-filter: blur(2px);
}
.center-modal-content {
	width: 620rpx;
	max-height: 80vh;
	background: #fff;
	border-radius: 32rpx;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	animation: popIn 0.3s ease-out;
}
@keyframes popIn {
	from { transform: scale(0.8); opacity: 0; }
	to { transform: scale(1); opacity: 1; }
}

.modal-header { padding: 32rpx; border-bottom: 2rpx solid #f2f2f2; }
.search-box {
	height: 72rpx; background: #f5f5f5; border-radius: 36rpx;
	display: flex; align-items: center; padding: 0 24rpx; gap: 12rpx;
}
/* CSS 搜索图标 @Author: Antigravity */
.search-icon {
	width: 24rpx; height: 24rpx; border: 3rpx solid #999; border-radius: 50%;
	position: relative;
	&::after {
		content: ''; position: absolute; right: -8rpx; bottom: -8rpx;
		width: 12rpx; height: 3rpx; background: #999; transform: rotate(45deg);
	}
}
.search-input { flex: 1; font-size: 28rpx; color: #333; }
/* CSS 清除图标 @Author: Antigravity */
.clear-icon {
	width: 32rpx; height: 32rpx; background: #ccc; border-radius: 50%;
	position: relative;
	&::before, &::after {
		content: ''; position: absolute; top: 14rpx; left: 6rpx; width: 20rpx; height: 3rpx;
		background: #fff; transform: rotate(45deg);
	}
	&::after { transform: rotate(-45deg); }
}

.customer-list-scroll { flex: 1; padding: 0 32rpx; max-height: 50vh; }
.customer-item {
	display: flex; align-items: center; justify-content: space-between;
	padding: 30rpx 0; border-bottom: 2rpx solid #f9f9f9;
}
.customer-item:last-child { border-bottom: none; }
.name { font-size: 32rpx; color: #333; font-weight: bold; }
.phone { font-size: 24rpx; color: #999; margin-top: 4rpx; }

/* CSS 对勾 @Author: Antigravity */
.checkmark {
	width: 12rpx; height: 24rpx; border-right: 4rpx solid #ff9500; border-bottom: 4rpx solid #ff9500;
	transform: rotate(45deg); margin-right: 10rpx;
}

.modal-footer { padding: 24rpx 32rpx; border-top: 2rpx solid #f2f2f2; }
.modal-close-btn {
	width: 100%; height: 72rpx; line-height: 72rpx; background: #f5f5f5;
	border-radius: 36rpx; font-size: 28rpx; color: #666; border: none;
	&::after { border: none; }
}

/* 品种录入底部 */
.breed-footer {
	padding: 24rpx 32rpx; background: #fafafa; border-top: 2rpx solid #f2f2f2;
	display: flex; gap: 16rpx; align-items: center;
}
.breed-custom-input {
	flex: 1; height: 72rpx; background: #eee; border-radius: 12rpx;
	padding: 0 20rpx; font-size: 26rpx;
}
.add-confirm-btn {
	padding: 0 30rpx; height: 72rpx; line-height: 72rpx;
	background: #ff9500; color: #fff; border-radius: 12rpx; font-size: 26rpx; font-weight: bold;
}
</style>
