<template>
	<view class="pet-edit-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 v-if="loading" class="loading-state">
			<!-- CSS 原生 Loading @Author: Antigravity -->
			<view class="spinner"></view>
			<text class="loading-txt">加载中...</text>
		</view>

		<block v-else>
			<!-- 基础信息 -->
			<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="showTypeSelect = true">
					<text class="form-label require">宠物类型</text>
					<view class="picker-value">{{ getTypeLabel }}</view>
					<view class="right-arrow"></view>
				</view>
				<view class="form-item" @click="showCustomerSelect = true">
					<text class="form-label require">所属主人</text>
					<view class="picker-value" :class="{'placeholder': !form.userId}">{{ getCustomerLabel }}</view>
					<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="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="showTypeSelect" title="宠物类型" :options="typeOptions" :value="form.type" @select="(item) => form.type = item.value" />
			<center-select v-model="showCustomerSelect" title="所属主人" :options="customerOptions" labelKey="name" valueKey="id" :value="form.userId" @select="(item) => form.userId = item.id" />
			<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" />

		</block>
	</view>
</template>

<script setup>
/**
 * @Author: Antigravity
 */
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getPet, updatePet } 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 loading = ref(true)

// 弹窗状态控制
const showTypeSelect = ref(false)
const showCustomerSelect = ref(false)
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 showBreedPicker = ref(false)
const tempAvatarUrl = ref('')

const typeOptions = [{ label: '猫', value: 1 }, { label: '狗', value: 2 }, { label: '其他', value: 3 }]
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 petId = ref(null)
const breedSearchKeyword = ref('')
const customBreedText = ref('')

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

onLoad(async (options) => {
	if (options.id) {
		petId.value = options.id
		await initData()
		await fetchDetail()
	} else {
		uni.showToast({ title: '参数错误', icon: 'none' })
		setTimeout(() => uni.navigateBack(), 1500)
	}
})

const initData = async () => {
	try {
		const [custRes, dictRes] = await Promise.all([
			listAllCustomer({ status: 0 }),
			getDicts('sys_pet_breed')
		])
		const records = Array.isArray(custRes) ? custRes : (custRes?.data || [])
		customerOptions.value = records.map(item => ({
            id: item.id || item.userId,
            name: item.name || item.customerName
        }))
		const dictList = Array.isArray(dictRes) ? dictRes : (dictRes?.data || [])
		breedCandidates.value = dictList.map(item => item.dictLabel || item.dictValue || item.label || item.value)
	} catch(e) { console.error('初始化数据失败', e); uni.showToast({ title: typeof e === 'string' ? e : '初始化数据失败', icon: 'none' }) }
}

const fetchDetail = async () => {
	try {
		loading.value = true
		const res = await getPet(petId.value)
		if (res) { 
			const data = res.data || res
			Object.assign(form, data) 
			tempAvatarUrl.value = data.avatarUrl || '' // 回显全路径 URL
		}
	} catch (e) {
		console.error('获取宠物详情失败', e)
		uni.showToast({ title: typeof e === 'string' ? e : '获取宠物详情失败', icon: 'none' })
	} finally {
		loading.value = false
	}
}

const getTypeLabel = computed(() => typeOptions.find(o => o.value === form.type)?.label || '请选择')
const getCustomerLabel = computed(() => {
	const opt = customerOptions.value.find(o => String(o.id) === String(form.userId))
	return opt ? opt.name : '请选择主人'
})
const getGenderLabel = computed(() => genderOptions.find(o => o.value === form.gender)?.label || '未知')
const getSizeLabel = computed(() => sizeOptions.find(o => o.value === form.size)?.label || '请选择')
const getHouseTypeLabel = computed(() => houseTypeOptions.find(o => o.value === form.houseType)?.label || '请选择')
const getEntryMethodLabel = computed(() => entryMethodOptions.find(o => o.value === form.entryMethod)?.label || '请选择')
const getAggressionLabel = computed(() => aggressionOptions.find(o => o.value === form.aggression)?.label || '否')

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 = ''
}

// 选择并上传/修改宠物头像
// @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);
                uni.showToast({ title: typeof e === 'string' ? e : '上传头像失败', icon: 'none' });
            }
        }
    });
}

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 = ''
}

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.age) return uni.showToast({ title: '请输入年龄', icon: 'none' })

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

<style lang="scss" scoped>
.pet-edit-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;
    }
}

/* CSS 原生 Loading 方案 @Author: Antigravity */
.loading-state {
	padding-top: 15vh; display: flex; flex-direction: column; align-items: center; justify-content: center;
	.loading-txt { font-size: 24rpx; color: #999; margin-top: 20rpx; }
}
.spinner {
	width: 40rpx; height: 40rpx; border: 4rpx solid #f3f3f3; border-top: 4rpx solid #ff9500;
	border-radius: 50%; animation: spin 1s linear infinite;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

.section-title { font-size: 30rpx; font-weight: bold; color: #333; padding: 32rpx 32rpx 16rpx; }
.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: stretch; border-bottom: none; gap: 0; }
.form-item.vertical .form-textarea { width: 100%; height: 160rpx; margin-top: 16rpx; background: #f9f9f9; padding: 20rpx; box-sizing: border-box; border-radius: 12rpx; font-size: 28rpx; color: #333; line-height: 1.6; }
.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; min-height: 40rpx; }
.picker-value.placeholder { color: #ccc; }

/* CSS 绘制图标群 @Author: Antigravity */
.right-arrow {
	width: 14rpx; height: 14rpx; border-right: 3rpx solid #ccc; border-top: 3rpx solid #ccc; transform: rotate(45deg);
}
.checkmark {
	width: 12rpx; height: 24rpx; border-right: 4rpx solid #ff9500; border-bottom: 4rpx solid #ff9500; transform: rotate(45deg); margin-right: 10rpx;
}
.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); }
}

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

/* 居中弹窗样式 @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;
}
.search-input { flex: 1; font-size: 28rpx; color: #333; }

.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; }
.name { font-size: 32rpx; color: #333; font-weight: bold; }

.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>
