<template>
	<view class="personal-pet-cat container">
		<view class="personal-pet-img">
			<view class="personal-pet-info-title">
				宠物头像
			</view>
			<view style="display: flex;justify-content: center;">
				<u-upload accept="image" :capture="['album','camera']" :fileList="fileList" @afterRead="afterRead"
					@delete="deletePic" :max-count="1" name="pet" width="60" height="60" :custom-style="{flex:0}">
					<image src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/index/cat_new.png"
						style="width: 60px;height: 60px;"></image>
				</u-upload>
			</view>
		</view>

		<!-- 宠物基本信息 -->
		<view class="personal-pet-basic-info">
			<view class="personal-pet-info-title border-bottom">
				宠物基本信息
			</view>
			<u--form labelPosition="left" :model="petBaseInfo" ref="uForm">
				<u-form-item required label="昵称" :prop="`petBaseInfo.nickName`" labelWidth="80" borderBottom>
					<u--input v-model="petBaseInfo.nickName" placeholder="请输入宠物昵称"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item label="性别" :prop="`petBaseInfo.sex`" labelWidth="80" borderBottom @click="showSex = true">
					<u--input v-model="sexText" disabled disabledColor="#ffffff" placeholder="请选择"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
				<u-form-item required label="品种" :prop="`petBaseInfo.type`" labelWidth="80" borderBottom>
					<u--input v-model="petBaseInfo.type" placeholder="请输入"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
				<u-form-item required label="体重" :prop="`petBaseInfo.weight`" labelWidth="80" borderBottom ref="item1">
					<u--input v-model="petBaseInfo.weight" placeholder="请输入(单位kg)"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right" type="number"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
				<u-form-item label="出生年月" :prop="`petBaseInfo.birthday`" labelWidth="80" borderBottom
					@click="yearMonthOpen">
					<u--input v-model="petBaseInfo.birthday" disabled disabledColor="#ffffff" placeholder="请选择"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
				<u-form-item required label="性格" :prop="`petBaseInfo.personality`" labelWidth="80" borderBottom
					@click="dispositionSelectOpen">
					<u--input v-model="personalityText" disabled disabledColor="#ffffff" placeholder="请选择"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
			</u--form>
		</view>

		<!-- 性格选择弹窗 -->
		<view style="background-color: #fffcf2;padding: 10px 20px;" v-show="showDisposition">
			<view style="height: 85%;">
				<u-checkbox-group v-model="tempPersonality" @change="personalityCheckboxChange" iconPlacement="left"
					placement="row" style="flex-wrap: wrap;" activeColor="#ffbf60">
					<u-checkbox :customStyle="{margin: '8px'}" v-for="(item, index) in dispositionActions" :key="item"
						:label="item" :name="item">
					</u-checkbox>
				</u-checkbox-group>
				<view class="personal-pet-disposition-btns">
					<view class="personal-pet-disposition-btn">
						<u-button color="#FFF4E4" @click="dispositionSelectClose">
							<view style="color: #A9A9A9;">
								取消
							</view>
						</u-button>
					</view>
					<view class="personal-pet-disposition-btn" @click="dispositionSelectConfirm">
						<u-button color="#FFBF60">
							<view style="color: #fff;">
								确定
							</view>
						</u-button>
					</view>
				</view>
			</view>
		</view>

		<!-- 宠物健康信息 -->
		<view class="personal-pet-health-info">
			<view class="personal-pet-info-title border-bottom">
				宠物健康情况
			</view>
			<u--form labelPosition="left" :model="petHealthInfo" ref="uHealthForm">
				<u-form-item required label="疫苗" :prop="`petHealthInfo.vaccine`" labelWidth="80" borderBottom
					@click="showVaccine = true">
					<u--input v-model="vaccineText" disabled disabledColor="#ffffff" placeholder="请选择"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
				<u-form-item required label="驱虫" :prop="`petHealthInfo.deworm`" labelWidth="80" borderBottom
					@click="showExpelling = true">
					<u--input v-model="dewormText" disabled disabledColor="#ffffff" placeholder="请选择"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
				<u-form-item label="绝育" :prop="`petHealthInfo.neutered`" labelWidth="80" borderBottom
					@click="showSterilization = true">
					<u--input v-model="neuteredText" disabled disabledColor="#ffffff" placeholder="请选择"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
				<u-form-item v-if="petType === '1' || petType === '狗狗' " label="狗证" :prop="`petHealthInfo.petCard`"
					labelWidth="80" borderBottom @click="showDog = true">
					<u--input v-model="petCartText" disabled disabledColor="#ffffff" placeholder="请选择"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
				</u-form-item>
				<view class="dog-tips" v-if="petType === 'dog' || petType === '狗狗'">
					<u-icon name="info-circle" color="#A94F20" size="12"></u-icon>
					<view style="margin-left: 3px;">
						未办理养犬许可证且需要外出遛狗, 犬只存在被相关单位收缴
						甚至捕杀的可能，请您遵守当地养犬规范，合法文明养犬。具体
						请您查看当地养犬条例
					</view>
				</view>
				<u-form-item required label="健康" :prop="`petHealthInfo.health`" labelWidth="80" @click="healthsSelect">
					<u--input v-model="healthText" disabled disabledColor="#ffffff" placeholder="请选择"
						placeholderStyle="text-align:right;color:#AAA" border="none" inputAlign="right"></u--input>
					<view slot="right">
						<u-icon v-if="showHealths" name="arrow-down" color="#AAA"></u-icon>
						<u-icon v-else name="arrow-right" color="#AAA"></u-icon>
					</view>
				</u-form-item>
			</u--form>
		</view>

		<!-- 健康选择弹窗 -->
		<view class="health-select" v-show="showHealths">
			<view style="padding: 10px;height: 85%;">
				<u-checkbox-group v-model="tempHealthStatus" @change="healthCheckboxChange" placement="column"
					activeColor="#ffbf60">
					<u-checkbox :customStyle="{marginBottom: '8px'}" v-for="(item, index) in healthData" :key="index"
						:label="item" :name="item">
					</u-checkbox>
				</u-checkbox-group>
				
				<!-- 只有选择了"其他"才显示输入框 -->
				<view v-if="tempHealthStatus && tempHealthStatus.includes('其他')" style="margin-top: 10px;">
					<u--input placeholder="请输入其他健康特征"
						border="surround" maxlength='20' 
						:customStyle="{backgroundColor: '#fff', borderColor: '#ffbf60'}"
						v-model="tempRemark"></u--input>
				</view>
				<view class="health-select-btns">
					<view class="health-select-btn">
						<u-button color="#FFF4E4" @click="healthSelectClose">
							<view style="color: #A9A9A9;">
								取消
							</view>
						</u-button>
					</view>
					<view class="health-select-btn" @click="healthSelectConfirm">
						<u-button color="#FFBF60">
							<view style="color: #fff;">
								确定
							</view>
						</u-button>
					</view>
				</view>
			</view>
		</view>

		<!-- 各种选择器 -->
		<u-picker :show="showSex" :columns="sexActions" @cancel="showSex = false" @confirm="sexSelect"></u-picker>
		<u-picker :show="showVaccine" :columns="vaccineActions" @cancel="showVaccine = false"
			:immediateChange="true" @confirm="vaccineSelect"></u-picker>
		<u-picker :show="showExpelling" :columns="expellingActions" @cancel="showExpelling = false"
			:immediateChange="true" @confirm="expellingSelect"></u-picker>
		<u-picker :show="showSterilization" :columns="sterilizationActions"
			@cancel="showSterilization = false" :immediateChange="true" @confirm="sterilizationSelect"></u-picker>
		<u-picker :show="showDog" :columns="dogActions" @cancel="showDog = false"
			:immediateChange="true" @confirm="dogSelect"></u-picker>
		<u-datetime-picker :maxDate='getMaxDate()' :minDate="getMinDate()" :show="showBirthday" v-model="tempBirthday"
			mode="year-month" @confirm="yearMonthConfirm" @cancel="yearMonthClose"></u-datetime-picker>

		<view class="personal-pet-info-btns">
			<view class="personal-pet-btns">
				<view class="personal-pet-btn">
					<u-button color="#FFF4E4" @click="cancelPet">
						<view style="color: #A9A9A9;">
							取消
						</view>
					</u-button>
				</view>
				<view class="personal-pet-btn" @click="save">
					<u-button color="#FFBF60" :loading="loading">
						<view style="color: #fff;">
							保存
						</view>
					</u-button>
				</view>
			</view>
		</view>
		<u-modal :show="showDel" @confirm="confirmDel" @cancel="showDel = false" ref="uModal" showCancelButton
			:asyncClose="true" :content="delContent">
		</u-modal>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		addPet,
		getPetDetails,
		updatePet,
		delByPetId
	} from '@/api/pet/index.js';
	import {
		useRoute,
		useRouter
	} from 'vue-router';
	import {
		onLoad
	} from '@dcloudio/uni-app'

	const route = useRoute();
	const router = useRouter();

	const loading = ref(false);
	const fileList = ref([]);
	const petId = ref('');
	const userId = ref('');
	const petType = ref('dog');
	const optionType = ref('add');
	const isNewOrder = ref(false);
	const delContent = ref('');
	const headImage = ref('');
	
	// 宠物基本信息
	const petBaseInfo = ref({
		nickName: '',
		sex: '',
		type: '',
		weight: '',
		birthday: '',
		personality: ''
	});
	
	// 宠物健康信息
	const petHealthInfo = ref({
		vaccine: '',
		deworm: '',
		neutered: '',
		petCard: '',
		health: '',
		remark: ''
	});
	
	const showDel = ref(false);
	const uModal = ref(null);
	
	// 基本信息相关的响应式数据
	const showSex = ref(false);
	const showBirthday = ref(false);
	const showDisposition = ref(false);
	const sexActions = ref([
		['男生', '女生']
	]);
	const dispositionActions = ref([
		'友善热情', '害羞胆怯', '比较顽皮', '粘人乖巧', '顽皮捣蛋', '内向胆小', '有攻击性'
	]);
	const tempBirthday = ref('');
	const tempPersonality = ref([]);
	const uForm = ref(null);
	const item1 = ref(null);
	
	// 健康信息相关的响应式数据
	const showVaccine = ref(false);
	const showExpelling = ref(false);
	const showSterilization = ref(false);
	const showDog = ref(false);
	const showHealths = ref(false);
	const vaccineActions = ref([
		['每年都免疫', '有免疫史', '未免疫']
	]);
	const expellingActions = ref([
		['未驱虫', '定期驱虫', '有驱虫史']
	]);
	const sterilizationActions = ref([
		['已绝育', '未绝育']
	]);
	const dogActions = ref([
		['是', '否']
	]);
	const healthData = ref([
		'身体健康，无异常',
		'近3个月有做过手术', 
		'有过往病史、过敏史',
		'宠物食欲及肠胃不佳',
		'宠物部分身体部位有受伤',
		'宠物皮肤敏感或正患有皮肤疾病',
		'其他'
	]);
	const tempHealthStatus = ref([]);
	const tempRemark = ref('');
	const uHealthForm = ref(null);

	// 计算属性
	const sexText = computed(() => {
	    const sexMap = {
	        0: '男生',
	        1: '女生'
	    };
	    return sexMap[petBaseInfo.value.sex] || '';
	});
	
	const personalityText = computed(() => {
		if (petBaseInfo.value.personality) {
			// 如果是字符串，直接返回
			if (typeof petBaseInfo.value.personality === 'string') {
				return petBaseInfo.value.personality;
			}
			// 如果是数组，转换为逗号分隔的字符串
			if (Array.isArray(petBaseInfo.value.personality) && petBaseInfo.value.personality.length > 0) {
				return petBaseInfo.value.personality.join('，');
			}
		}
		return '';
	});

	const vaccineText = computed(() => {
		const vaccineMap = {
			0: '每年都免疫',
			1: '有免疫史',
			2: '未免疫'
		};
		return vaccineMap[petHealthInfo.value.vaccine] || ''
	});
	
	const dewormText = computed(() => {
		const dewormMap = {
			0: '未驱虫',
			1: '定期驱虫',
			2: '有驱虫史'
		};
		return dewormMap[petHealthInfo.value.deworm] || ''
	});
	
	const neuteredText = computed(() => {
		const neuteredMap = {
			0: '已绝育',
			1: '未绝育'
		};
		return neuteredMap[petHealthInfo.value.neutered] || ''
	});
	
	const petCartText = computed(() => {
		const petCartMap = {
			0: '是',
			1: '否'
		};
		return petCartMap[petHealthInfo.value.petCard] || ''
	});
	
	const healthText = computed(() => {
		if (petHealthInfo.value.health) {
			let healthDisplay = '';
			// 如果是字符串，直接使用
			if (typeof petHealthInfo.value.health === 'string') {
				healthDisplay = petHealthInfo.value.health;
			}
			// 如果是数组，转换为逗号分隔的字符串
			else if (Array.isArray(petHealthInfo.value.health) && petHealthInfo.value.health.length > 0) {
				healthDisplay = petHealthInfo.value.health.join('，');
			}
			
			// 处理"其他"选项的显示
			if (healthDisplay.includes('其他') && petHealthInfo.value.remark) {
				healthDisplay = healthDisplay.replace('其他', `其他：${petHealthInfo.value.remark}`);
			}
			return healthDisplay;
		}
		return '';
	});

	onLoad((option) => {
		petType.value = option.petType;
		userId.value = option.userId
		optionType.value = option.optionType;
		if (optionType.value === 'edit') {
			petId.value = option.petId;
			getPetDetailsFunc(option.petId);
		}
		if (option.isNewOrder) {
			isNewOrder.value = true;
		}
	});

	const deletePic = (event) => {
		fileList.value.splice(event.index, 1);
	};

	const afterRead = async (event) => {
		let lists = [].concat(event.file);
		let fileListLen = fileList.value.length;
		lists.map((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',
				message: '上传中'
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			let item = fileList.value[fileListLen];
			fileList.value.splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: result
			}));
			fileListLen++;
		}
	};
	
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'https://store-test.catmdogd.com/test-api/h5/oss/upload',
				filePath: url,
				name: 'file',
				formData: {
					user: 'test'
				},
				success: (res) => {
					setTimeout(() => {
						if (res && res.data) {
							let resData = JSON.parse(res.data);
							resolve(resData.url);
						}
						reject("上传失败");
					}, 1000);
				}
			});
		});
	};

	const getPetDetailsFunc = (petId) => {
		getPetDetails({
			id: petId
		}).then((res) => {
			if (res.code == 200) {
				const {
					headImage,
					nickName,
					sex,
					type,
					weight,
					birthday,
					personality,
					vaccine,
					deworm,
					neutered,
					petCard,
					health,
					remark
				} = res.data;
				
				console.log('=== 后端返回的原始数据 ===');
				console.log('birthday:', birthday);
				console.log('personality:', personality);
				console.log('health:', health);
				console.log('remark:', remark);
				
				// 处理日期格式：从 "yyyy-MM-dd HH:mm:ss" 转换为 "yyyy-MM"
				let processedBirthday = '';
				if (birthday) {
					if (typeof birthday === 'string' && birthday.length >= 7) {
						processedBirthday = birthday.substring(0, 7); // 取前7位 "yyyy-MM"
					} else {
						processedBirthday = birthday;
					}
				}
				
				// 处理性格数据：从逗号分隔字符串转换为原始格式（保持字符串，在打开时转换为数组）
				let processedPersonality = '';
				if (personality) {
					// 统一逗号格式，将英文逗号转换为中文逗号用于显示
					processedPersonality = personality.replace(/,/g, '，');
				}
				
				// 处理健康数据：从逗号分隔字符串转换为原始格式（保持字符串，在打开时转换为数组）
				let processedHealth = '';
				if (health) {
					// 统一逗号格式，将英文逗号转换为中文逗号用于显示
					processedHealth = health.replace(/,/g, '，');
				}
				
				console.log('=== 处理后的数据 ===');
				console.log('processedBirthday:', processedBirthday);
				console.log('processedPersonality:', processedPersonality);
				console.log('processedHealth:', processedHealth);
				
				petBaseInfo.value = {
					nickName,
					sex,
					type,
					weight,
					birthday: processedBirthday,
					personality: processedPersonality
				};
				petHealthInfo.value = {
					vaccine,
					deworm,
					neutered,
					petCard,
					health: processedHealth,
					remark
				};
				fileList.value = [{
					url: headImage
				}];
				
				console.log('=== 最终设置的数据 ===');
				console.log('petBaseInfo:', petBaseInfo.value);
				console.log('petHealthInfo:', petHealthInfo.value);
			} else {
				uni.showToast({
					title: '获取pet失败',
					duration: 3000,
					icon: "none"
				});
			}
		});
	};

	// 基本信息相关方法
	const sexSelect = (e) => {
		petBaseInfo.value.sex = e.indexs[0];
		showSex.value = false;
		console.log('性别选择:', petBaseInfo.value.sex);
	};

	const yearMonthOpen = () => {
		if (petBaseInfo.value.birthday) {
			tempBirthday.value = Number(new Date(petBaseInfo.value.birthday));
		} else {
			tempBirthday.value = Number(new Date());
		}
		showBirthday.value = true;
	};

	const yearMonthClose = () => {
		showBirthday.value = false;
	};

	const yearMonthConfirm = (e) => {
		const timeFormat = uni.$u.timeFormat;
		petBaseInfo.value.birthday = timeFormat(e.value, 'yyyy-mm');
		showBirthday.value = false;
		console.log('生日选择:', petBaseInfo.value.birthday);
	};

	const dispositionSelectOpen = () => {
		// 将字符串转换为数组，或者如果已经是数组就直接使用
		console.log('=== 打开性格选择弹窗 ===');
		console.log('当前性格数据:', petBaseInfo.value.personality, '类型:', typeof petBaseInfo.value.personality);
		
		if (typeof petBaseInfo.value.personality === 'string' && petBaseInfo.value.personality.trim() !== '') {
			// 同时支持中文逗号和英文逗号分隔
			let personalityArray = petBaseInfo.value.personality.split(/[，,]/).map(item => item.trim()).filter(item => item !== '');
			tempPersonality.value = personalityArray;
			console.log('从字符串解析的性格数组:', personalityArray);
		} else if (Array.isArray(petBaseInfo.value.personality)) {
			tempPersonality.value = petBaseInfo.value.personality || [];
			console.log('直接使用数组:', petBaseInfo.value.personality);
		} else {
			tempPersonality.value = [];
			console.log('设置为空数组');
		}
		
		console.log('最终tempPersonality.value:', tempPersonality.value);
		console.log('=== 性格弹窗准备完成 ===');
		showDisposition.value = true;
	};

	const dispositionSelectClose = () => {
		// 恢复到原来的状态，而不是清空
		if (typeof petBaseInfo.value.personality === 'string' && petBaseInfo.value.personality.trim() !== '') {
			let personalityArray = petBaseInfo.value.personality.split(/[，,]/).map(item => item.trim()).filter(item => item !== '');
			tempPersonality.value = personalityArray;
		} else {
			tempPersonality.value = [];
		}
		showDisposition.value = false;
	};

	const dispositionSelectConfirm = () => {
		// 将数组转换为逗号分隔的字符串保存到后端
		console.log('=== 性格选择确认开始 ===');
		console.log('tempPersonality.value:', tempPersonality.value);
		console.log('tempPersonality类型:', typeof tempPersonality.value);
		console.log('tempPersonality长度:', tempPersonality.value?.length);
		
		// 检查是否至少选择了一个性格
		if (!tempPersonality.value || tempPersonality.value.length === 0) {
			uni.showToast({
				title: '请至少选择一个性格特征!',
				duration: 2000,
				icon: "none"
			});
			return;
		}
		
		const personalityString = tempPersonality.value.join('，');
		console.log('转换后的personalityString:', personalityString);
		console.log('personalityString长度:', personalityString.length);
		
		petBaseInfo.value.personality = personalityString;
		// 保持tempPersonality和petBaseInfo.personality的同步，确保提交时使用正确的数据
		console.log('保存后petBaseInfo.value.personality:', petBaseInfo.value.personality);
		console.log('保存后personalityText.value:', personalityText.value);
		console.log('=== 性格选择确认完成 ===');
		
		showDisposition.value = false;
	};

	const personalityCheckboxChange = (n) => {
		console.log('性格checkbox变化:', n, tempPersonality.value);
	};

	const getMaxDate = () => {
		return Date.now();
	};

	const getMinDate = () => {
		let dt = new Date();
		dt.setFullYear(dt.getFullYear() - 30);
		return Date.parse(dt);
	};

	// 健康信息相关方法
	const vaccineSelect = (e) => {
		petHealthInfo.value.vaccine = e.indexs[0];
		showVaccine.value = false;
		console.log('疫苗选择:', petHealthInfo.value.vaccine);
	};

	const expellingSelect = (e) => {
		petHealthInfo.value.deworm = e.indexs[0];
		showExpelling.value = false;
		console.log('驱虫选择:', petHealthInfo.value.deworm);
	};

	const sterilizationSelect = (e) => {
		petHealthInfo.value.neutered = e.indexs[0];
		showSterilization.value = false;
		console.log('绝育选择:', petHealthInfo.value.neutered);
	};

	const dogSelect = (e) => {
		petHealthInfo.value.petCard = e.indexs[0];
		showDog.value = false;
		console.log('狗证选择:', petHealthInfo.value.petCard);
	};

	const healthsSelect = () => {
		// 初始化临时健康状态和备注
		console.log('=== 打开健康选择弹窗 ===');
		console.log('当前健康数据:', petHealthInfo.value.health, '类型:', typeof petHealthInfo.value.health);
		console.log('当前备注数据:', petHealthInfo.value.remark);
		
		if (typeof petHealthInfo.value.health === 'string' && petHealthInfo.value.health.trim() !== '') {
			// 同时支持中文逗号和英文逗号分隔
			let healthArray = petHealthInfo.value.health.split(/[，,]/).map(item => item.trim()).filter(item => item !== '');
			
			// 处理"其他：xxx"格式的数据
			let processedHealthArray = [];
			let otherRemark = '';
			
			healthArray.forEach(item => {
				if (item.startsWith('其他：')) {
					processedHealthArray.push('其他');
					otherRemark = item.substring(3); // 去掉"其他："前缀
				} else {
					processedHealthArray.push(item);
				}
			});
			
			tempHealthStatus.value = processedHealthArray;
			// 如果从健康数据中解析出了"其他"的备注，优先使用它
			tempRemark.value = otherRemark || petHealthInfo.value.remark || '';
			
			console.log('从字符串解析的健康数组:', processedHealthArray);
			console.log('解析出的其他备注:', otherRemark);
		} else if (Array.isArray(petHealthInfo.value.health)) {
			tempHealthStatus.value = petHealthInfo.value.health || [];
			tempRemark.value = petHealthInfo.value.remark || '';
			console.log('直接使用数组:', petHealthInfo.value.health);
		} else {
			tempHealthStatus.value = [];
			tempRemark.value = petHealthInfo.value.remark || '';
			console.log('设置为空数组');
		}
		
		console.log('最终tempHealthStatus.value:', tempHealthStatus.value);
		console.log('最终tempRemark.value:', tempRemark.value);
		console.log('=== 健康弹窗准备完成 ===');
		
		showHealths.value = true;
		uni.pageScrollTo({
			scrollTop: 2000,
			duration: 300
		});
	};
	
	const healthSelectClose = () => {
		tempHealthStatus.value = [];
		tempRemark.value = '';
		showHealths.value = false;
	};
	
	const healthSelectConfirm = () => {
		// 将数组转换为逗号分隔的字符串保存到后端
		console.log('=== 健康选择确认开始 ===');
		console.log('tempHealthStatus.value:', tempHealthStatus.value);
		console.log('tempHealthStatus类型:', typeof tempHealthStatus.value);
		console.log('tempHealthStatus长度:', tempHealthStatus.value?.length);
		console.log('tempRemark.value:', tempRemark.value);
		console.log('tempRemark是否有值:', tempRemark.value && tempRemark.value.trim() !== '');
		
		// 检查是否至少选择了一个健康状态
		if (!tempHealthStatus.value || tempHealthStatus.value.length === 0) {
			uni.showToast({
				title: '请至少选择一个健康状态!',
				duration: 2000,
				icon: "none"
			});
			return;
		}
		
		let healthArray = [...tempHealthStatus.value];
		console.log('原始healthArray:', healthArray);
		console.log('是否包含其他:', healthArray.includes('其他'));
		
		// 处理"其他"选项 - 如果选择了"其他"且有备注，合并为"其他：备注"
		if (healthArray.includes('其他') && tempRemark.value && tempRemark.value.trim() !== '') {
			const otherIndex = healthArray.indexOf('其他');
			const newOtherValue = `其他：${tempRemark.value.trim()}`;
			healthArray[otherIndex] = newOtherValue;
			console.log('替换其他选项:', newOtherValue);
		}
		
		const healthString = healthArray.join('，');
		console.log('转换后的healthString:', healthString);
		console.log('healthString长度:', healthString.length);
		
		petHealthInfo.value.health = healthString;
		petHealthInfo.value.remark = tempRemark.value; // 保持remark字段同步
		
		console.log('保存后petHealthInfo.value.health:', petHealthInfo.value.health);
		console.log('保存后petHealthInfo.value.remark:', petHealthInfo.value.remark);
		console.log('保存后healthText.value:', healthText.value);
		console.log('=== 健康选择确认完成 ===');
		
		showHealths.value = false;
	};

	const healthCheckboxChange = (n) => {
		console.log('=== 健康checkbox变化 ===');
		console.log('新值:', n);
		console.log('tempHealthStatus.value:', tempHealthStatus.value);
		console.log('是否包含其他:', tempHealthStatus.value.includes('其他'));
		
		// 如果取消选择"其他"，清空备注
		if (!tempHealthStatus.value.includes('其他')) {
			tempRemark.value = '';
			console.log('取消选择其他，清空备注');
		}
		console.log('当前备注:', tempRemark.value);
		console.log('=== 健康checkbox变化完成 ===');
	};

	const save = () => {
		console.log('=== 开始保存宠物信息 ===');
		console.log('petBaseInfo:', petBaseInfo.value);
		console.log('petHealthInfo:', petHealthInfo.value);
		console.log('当前personality值:', petBaseInfo.value.personality, '长度:', petBaseInfo.value.personality?.length);
		console.log('personalityText显示值:', personalityText.value);
		
		if (!(fileList.value.length > 0 && fileList.value[0].url)) {
			uni.showToast({
				title: '请上传宠物照片!',
				duration: 3000,
				icon: "none"
			});
			return;
		}
		headImage.value = fileList.value[0].url;
		
		// 确保性格数据正确处理
		let finalPersonality = '';
		
		// 优先使用tempPersonality中的数据（如果用户有操作过弹窗）
		if (tempPersonality.value && tempPersonality.value.length > 0) {
			finalPersonality = tempPersonality.value.join(',');
			console.log('使用tempPersonality数据:', finalPersonality);
		} else if (petBaseInfo.value.personality && petBaseInfo.value.personality.trim() !== '') {
			// 如果没有temp数据，使用原有数据并转换为英文逗号
			finalPersonality = petBaseInfo.value.personality.replace(/，/g, ',');
			console.log('使用petBaseInfo原有数据:', finalPersonality);
		}
		
		// 确保健康数据正确处理
		let finalHealth = '';
		let finalRemark = tempRemark.value || petHealthInfo.value.remark || '';
		
		console.log('=== 处理健康数据开始 ===');
		console.log('petHealthInfo.value.health:', petHealthInfo.value.health);
		console.log('tempHealthStatus.value:', tempHealthStatus.value);
		console.log('tempRemark.value:', tempRemark.value);
		console.log('petHealthInfo.value.remark:', petHealthInfo.value.remark);
		
		// 优先使用tempHealthStatus中的数据（如果用户有操作过弹窗）
		if (tempHealthStatus.value && tempHealthStatus.value.length > 0) {
			let healthArray = [...tempHealthStatus.value];
			console.log('使用tempHealthStatus数据:', healthArray);
			
			// 处理"其他"选项
			if (healthArray.includes('其他') && tempRemark.value && tempRemark.value.trim() !== '') {
				const otherIndex = healthArray.indexOf('其他');
				const newOtherValue = `其他：${tempRemark.value.trim()}`;
				healthArray[otherIndex] = newOtherValue;
				console.log('合并其他选项和备注:', newOtherValue);
			}
			
			finalHealth = healthArray.join(',');
			console.log('使用tempHealthStatus生成的finalHealth:', finalHealth);
		} else if (petHealthInfo.value.health && petHealthInfo.value.health.trim() !== '') {
			// 如果没有temp数据，使用原有数据并转换为英文逗号
			finalHealth = petHealthInfo.value.health.replace(/，/g, ',');
			console.log('使用petHealthInfo原有数据:', finalHealth);
		}
		
		console.log('最终finalHealth:', finalHealth);
		console.log('最终finalRemark:', finalRemark);
		console.log('=== 处理健康数据完成 ===');
		
		// 处理生日格式转换
		let finalBirthday = '';
		if (petBaseInfo.value.birthday) {
			// 将 "2025-07" 格式转换为 "2025-07-01 00:00:00" 格式
			if (petBaseInfo.value.birthday.length === 7) { // 格式为 "2025-07"
				finalBirthday = `${petBaseInfo.value.birthday}-01 00:00:00`;
			} else {
				finalBirthday = petBaseInfo.value.birthday;
			}
		}
		console.log('原生日格式:', petBaseInfo.value.birthday);
		console.log('转换后生日格式:', finalBirthday);

		let params = {
			...{
				petType: petType.value,
				headImage: headImage.value
			},
			userId:userId.value,
			...petBaseInfo.value,
			...petHealthInfo.value,
			personality: finalPersonality,  // 确保personality字段有正确的数据
			health: finalHealth,  // 确保health字段有正确的数据
			remark: finalRemark,  // 确保remark字段有正确的数据
			birthday: finalBirthday  // 确保birthday字段格式正确
		};
		console.log('合并后的提交参数:', params);
		console.log('其中personality值:', params.personality, '类型:', typeof params.personality, '长度:', params.personality?.length);
		console.log('其中health值:', params.health, '类型:', typeof params.health, '长度:', params.health?.length);
		console.log('其中remark值:', params.remark, '类型:', typeof params.remark, '长度:', params.remark?.length);
		console.log('其中birthday值:', params.birthday, '类型:', typeof params.birthday);
		console.log('finalPersonality:', finalPersonality);
		console.log('finalHealth:', finalHealth);
		console.log('finalRemark:', finalRemark);
		console.log('finalBirthday:', finalBirthday);
		if (!params.nickName) {
			uni.showToast({
				title: '请填写宠物昵称!',
				duration: 3000,
				icon: "none"
			});
			return;
		}
		if (!params.type) {
			uni.showToast({
				title: '请输入宠物品种!',
				duration: 3000,
				icon: "none"
			});
			return;
		}
		if (!params.weight) {
			uni.showToast({
				title: '请选择宠物体重!',
				duration: 3000,
				icon: "none"
			});
			return;
		}
		if (!params.personality || params.personality.trim() === '' || params.personality === undefined || params.personality === null) {
			console.log('=== 性格验证失败详情 ===');
			console.log('params.personality:', params.personality);
			console.log('petBaseInfo.value.personality:', petBaseInfo.value.personality);
			console.log('personalityText.value:', personalityText.value);
			console.log('tempPersonality.value:', tempPersonality.value);
			uni.showToast({
				title: '请选择宠物性格!',
				duration: 3000,
				icon: "none"
			});
			return;
		}
		if (!(params.vaccine >= 0)) {
			uni.showToast({
				title: '请选择宠物疫苗情况!',
				duration: 3000,
				icon: "none"
			});
			return;
		}
		if (!(params.deworm >= 0)) {
			uni.showToast({
				title: '请选择宠物驱虫情况!',
				duration: 3000,
				icon: "none"
			});
			return;
		}
		if (!params.health || params.health.trim() === '' || params.health === undefined || params.health === null) {
			console.log('=== 健康验证失败详情 ===');
			console.log('params.health:', params.health);
			console.log('petHealthInfo.value.health:', petHealthInfo.value.health);
			console.log('healthText.value:', healthText.value);
			console.log('tempHealthStatus.value:', tempHealthStatus.value);
			console.log('tempRemark.value:', tempRemark.value);
			uni.showToast({
				title: '请选择宠物健康情况',
				duration: 3000,
				icon: "none"
			});
			return;
		}
		loading.value = true;
		if (optionType.value === 'edit') {
			params.id = petId.value;
			updatePet(params).then((res) => {
				if (res && res.code === 200) {
					uni.showToast({
						title: '保存成功',
						duration: 3000,
						icon: "none"
					});
					setTimeout(() => {
						loading.value = false;
						if (isNewOrder.value) {
							router.push('/pages/newOrder/petList');
						} else {
							const len = getCurrentPages().length;
							if (len >= 2) {
								uni.navigateBack();
							} else {
								router.push('/pages/personalCenter/pet');
							}
						}
					}, 1000);
				} else {
					loading.value = false;
					uni.showToast({
						title: '更新pet失败',
						duration: 3000,
						icon: "none"
					});
				}
			});
		} else if (optionType.value === 'add') {
			addPet(params).then((res) => {
				if (res.code == 200) {
					uni.showToast({
						title: '保存成功',
						duration: 3000,
						icon: "none"
					});
					setTimeout(() => {
						loading.value = false;
						uni.navigateBack();
					}, 1000);
				} else {
					loading.value = false;
					uni.showToast({
						title: '新增pet失败',
						duration: 3000,
						icon: "none"
					});
				}
			});
		}
	};

	const cancelPet = () => {
		uni.navigateBack(-1);
	};

	const confirmDel = () => {
		delByPetId(petId.value).then((res) => {
			uni.showToast({
				title: '删除成功',
				duration: 3000,
				icon: "none"
			});
			showDel.value = false;
			setTimeout(() => {
				const len = getCurrentPages().length;
				loading.value = false;
				if (len >= 2) {
					uni.navigateBack();
				} else {
					router.push('/pages/personalCenter/pet');
				}
			}, 2000);
		});
	};
</script>

<style lang="scss" scoped>
	.personal-pet-cat {

		.breed-select {
			background-color: #fff;
			box-sizing: border-box;
			width: 100%;
			padding: 20px;
			border-radius: 8px 8px 0 0;
			position: absolute;
			bottom: 0;

			.breed-select-btn {
				display: flex;
				justify-content: space-around;
				align-items: center;
			}
		}

		.personal-pet-info-title {
			font-size: 14px;
			color: #333;
			font-weight: bold;
			padding-bottom: 10px;

		}

		.border-bottom {
			border-bottom: 1px solid #efefef;
		}

		.personal-pet-img {
			height: 118px;
			background-color: #fff;
			padding: 10px 20px;
			
		}

		.personal-pet-basic-info {
			background-color: #fff;
			margin-top: 10px;
			padding: 10px 20px;
		}
		
		.personal-pet-health-info {
			background-color: #fff;
			padding: 10px 20px 0 20px;
			margin-top: 10px;
		}
	}

	.container {
		position: relative;
		height: 100%;
		padding-bottom: 90px;

		.personal-pet-info-btns {
			box-sizing: border-box;
			background-color: #FFFFFF;
			padding: 20rpx 20rpx 40rpx 20rpx;
			width: 100%;
			height: 160rpx;
			position: fixed;
			bottom: 0;
			z-index: 100;
			display: flex;

			.personal-pet-btns {
				display: flex;
				justify-content: space-around;
				align-items: center;
				flex-wrap: nowrap;
				width: 100%;
				height: 90rpx;
				border-radius: 6px;
				font-size: 16px;
				color: #FFFFFF;

				.personal-pet-btn {
					width: 40%;
				}
			}
		}
	}
	
	.personal-pet-disposition-btns {
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
		background-color: #FFFFFF;
		padding: 20rpx 20rpx 40rpx 20rpx;
		left: 0;
		width: 100%;
		height: 160rpx;
		position: fixed;
		bottom: 0;
		z-index: 100;
	}

	.personal-pet-disposition-btn {
		width: 40%;
	}
	
	.health-select {
		background-color: #fffcf2;
		padding: 10px 20px;
	}

	.dog-tips {
		color: #A94F20;
		font-size: 12px;
		display: flex;
		align-items: baseline;
		margin-top: 5px;
	}

	.health-select-btns {
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
		background-color: #FFFFFF;
		padding: 20rpx 20rpx 40rpx 20rpx;
		left: 0;
		width: 100%;
		height: 160rpx;
		position: fixed;
		bottom: 0;
		z-index: 100;
	}

	.health-select-btn {
		width: 40%;
	}
</style>