<template>
	<view class="add-page">
		<scroll-view class="add-scroll" scroll-y :scroll-with-animation="true">
			<view class="add-container">

				<!-- 宠物选择 -->
				<view class="form-section">
					<text class="section-title">选择宠物</text>
					<view class="form-card">
						<view class="form-row" @click="showPetPicker = true">
							<text class="form-label required">宠物</text>
							<text class="form-value" :class="{ 'value-placeholder': !form.petId }">
								{{ selectedPetName || '请选择' }}
							</text>
							<TnIcon name="right" :size="28" color="#CBD5E1" />
						</view>
					</view>
				</view>

				<!-- 记录信息 -->
				<view class="form-section">
					<text class="section-title">记录信息</text>
					<view class="form-card">
						<!-- 记录类型 -->
						<view class="form-row" @click="showTypePicker = true">
							<text class="form-label required">类型</text>
							<text class="form-value" :class="{ 'value-placeholder': !form.type }">
								{{ getTypeLabel(form.type) || '请选择' }}
							</text>
							<TnIcon name="right" :size="28" color="#CBD5E1" />
						</view>
						<view class="form-divider" />

						<!-- 记录标题 -->
						<view class="form-row">
							<text class="form-label">标题</text>
							<TnInput v-model="form.title" placeholder="如：五联疫苗第三针"
								:border="false" text-align="right" :max-length="50" />
						</view>
						<view class="form-divider" />

						<!-- 发生日期 -->
						<view class="form-row" @click="showDatePicker = true">
							<text class="form-label required">日期</text>
							<text class="form-value" :class="{ 'value-placeholder': !form.date }">
								{{ form.date || '请选择' }}
							</text>
							<TnIcon name="calendar" :size="28" color="#CBD5E1" />
						</view>
						<view class="form-divider" />

						<!-- 下次提醒日期 -->
						<view class="form-row" @click="showNextDatePicker = true">
							<text class="form-label">下次提醒</text>
							<text class="form-value" :class="{ 'value-placeholder': !form.nextDate }">
								{{ form.nextDate || '无需提醒' }}
							</text>
							<TnIcon name="calendar" :size="28" color="#CBD5E1" />
						</view>
					</view>
				</view>

				<!-- 类型专属字段 -->
				<view v-if="form.type === 'vaccine'" class="form-section">
					<text class="section-title">疫苗信息</text>
					<view class="form-card">
						<view class="form-row">
							<text class="form-label">疫苗名称</text>
							<TnInput v-model="form.vaccineName" placeholder="如：卫佳伍"
								:border="false" text-align="right" :max-length="50" />
						</view>
						<view class="form-divider" />
						<view class="form-row">
							<text class="form-label">批号</text>
							<TnInput v-model="form.batchNumber" placeholder="疫苗批次号"
								:border="false" text-align="right" :max-length="50" />
						</view>
						<view class="form-divider" />
						<view class="form-row">
							<text class="form-label">品牌</text>
							<TnInput v-model="form.brand" placeholder="如：硕腾"
								:border="false" text-align="right" :max-length="30" />
						</view>
					</view>
				</view>

				<view v-if="form.type === 'deworm'" class="form-section">
					<text class="section-title">驱虫信息</text>
					<view class="form-card">
						<view class="form-row" @click="showDewormPicker = true">
							<text class="form-label">驱虫类型</text>
							<text class="form-value" :class="{ 'value-placeholder': !form.dewormType }">
								{{ getDewormLabel(form.dewormType) || '请选择' }}
							</text>
							<TnIcon name="right" :size="28" color="#CBD5E1" />
						</view>
						<view class="form-divider" />
						<view class="form-row">
							<text class="form-label">品牌</text>
							<TnInput v-model="form.brand" placeholder="如：拜耳"
								:border="false" text-align="right" :max-length="30" />
						</view>
					</view>
				</view>

				<view v-if="form.type === 'medical'" class="form-section">
					<text class="section-title">就诊信息</text>
					<view class="form-card">
						<view class="form-row">
							<text class="form-label">诊断</text>
							<TnInput v-model="form.diagnosis" placeholder="诊断结论"
								:border="false" text-align="right" :max-length="100" />
						</view>
					</view>
				</view>

				<!-- 通用信息 -->
				<view class="form-section">
					<text class="section-title">补充信息</text>
					<view class="form-card">
						<view class="form-row">
							<text class="form-label">医院</text>
							<TnInput v-model="form.hospital" placeholder="就诊医院"
								:border="false" text-align="right" :max-length="50" />
						</view>
						<view class="form-divider" />
						<view class="form-row">
							<text class="form-label">医生</text>
							<TnInput v-model="form.doctor" placeholder="主治医生"
								:border="false" text-align="right" :max-length="30" />
						</view>
						<view class="form-divider" />
						<view class="form-row">
							<text class="form-label">费用</text>
							<view class="cost-row">
								<TnInput v-model="costText" type="digit" placeholder="0.00"
									:border="false" text-align="right" />
								<text class="cost-unit">元</text>
							</view>
						</view>
						<view class="form-divider" />
						<view class="form-row desc-row">
							<text class="form-label">描述</text>
							<TnInput v-model="form.description" type="textarea"
								placeholder="补充说明…" :border="false" :max-length="500" />
						</view>
					</view>
				</view>

			</view>
		</scroll-view>

		<!-- 底部提交按钮 -->
		<view class="bottom-bar" :style="{ paddingBottom: safeBottom + 'px' }">
			<TnButton text-color="#FFFFFF" shape="round" :bold="true"
				:custom-style="primaryButtonStyle"
				:loading="submitting" :disabled="submitting || !canSubmit"
				width="100%" height="96" :font-size="30" @click="handleSubmit">
				{{ submitting ? '保存中...' : '保存记录' }}
			</TnButton>
		</view>

		<!-- 宠物选择弹窗 -->
		<TnPopup v-model="showPetPicker" open-direction="bottom" :radius="32" :safe-area-inset-bottom="true">
			<view class="picker-panel">
				<view class="panel-header">
					<text class="panel-title">选择宠物</text>
					<view class="panel-close" @click="showPetPicker = false">
						<TnIcon name="close" :size="32" color="#64748B" />
					</view>
				</view>
				<scroll-view scroll-y class="picker-scroll">
					<view v-if="petList.length === 0" class="picker-empty">暂无宠物，请先添加</view>
					<view v-for="pet in petList" :key="pet._id" class="pet-option"
						:class="{ 'pet-option-selected': form.petId === pet._id }"
						@click="selectPet(pet._id)">
						<view class="pet-option-avatar">
							<TnAvatar :url="pet._displayAvatar || ''"
								:icon="pet._displayAvatar ? '' : 'floral'"
								:size="72" shape="circle" bg-color="#FFF7ED" />
						</view>
						<view class="pet-option-info">
							<text class="pet-option-name">{{ pet.name }}</text>
							<text class="pet-option-breed">{{ getSpeciesLabel(pet.species) }}{{ pet.breed ? ' · ' + pet.breed : '' }}</text>
						</view>
						<TnIcon v-if="form.petId === pet._id" name="success-circle-fill"
							:size="36" color="#F97316" />
						<TnIcon v-else name="circle" :size="36" color="#E2E8F0" />
					</view>
				</scroll-view>
			</view>
		</TnPopup>

		<!-- 类型选择弹窗 -->
		<TnPopup v-model="showTypePicker" open-direction="bottom" :radius="32" :safe-area-inset-bottom="true">
			<view class="picker-panel">
				<view class="panel-header">
					<text class="panel-title">选择类型</text>
					<view class="panel-close" @click="showTypePicker = false">
						<TnIcon name="close" :size="32" color="#64748B" />
					</view>
				</view>
				<view class="type-grid">
					<view v-for="item in typeOptions" :key="item.value" class="type-item"
						:class="{ 'type-item-selected': form.type === item.value }"
						:style="{ borderColor: form.type === item.value ? item.color : '#E2E8F0' }"
						@click="selectType(item.value)">
						<view class="type-item-icon" :style="{ backgroundColor: item.bg }">
							<TnIcon :name="item.icon" :size="40" :color="item.color" />
						</view>
						<text class="type-item-label" :style="{ color: form.type === item.value ? item.color : '#475569' }">
							{{ item.label }}
						</text>
					</view>
				</view>
			</view>
		</TnPopup>

		<!-- 驱虫类型弹窗 -->
		<TnPopup v-model="showDewormPicker" open-direction="bottom" :radius="32" :safe-area-inset-bottom="true">
			<view class="picker-panel">
				<view class="panel-header">
					<text class="panel-title">选择驱虫类型</text>
					<view class="panel-close" @click="showDewormPicker = false">
						<TnIcon name="close" :size="32" color="#64748B" />
					</view>
				</view>
				<view class="deworm-options">
					<view v-for="item in dewormOptions" :key="item.value" class="deworm-option"
						:class="{ 'deworm-selected': form.dewormType === item.value }"
						@click="selectDeworm(item.value)">
						<TnIcon :name="item.icon" :size="40" :color="form.dewormType === item.value ? item.color : '#94A3B8'" />
						<text class="deworm-label" :class="{ 'deworm-label-active': form.dewormType === item.value }">
							{{ item.label }}
						</text>
						<TnIcon v-if="form.dewormType === item.value" name="success-circle-fill" :size="36" :color="item.color" />
						<TnIcon v-else name="circle" :size="36" color="#E2E8F0" />
					</view>
				</view>
			</view>
		</TnPopup>

		<!-- 日期选择器 -->
		<TnDateTimePicker v-model="form.date" v-model:open="showDatePicker"
			mode="date" :max-time="todayStr"
			@confirm="showDatePicker = false" @cancel="showDatePicker = false" />
		<TnDateTimePicker v-model="form.nextDate" v-model:open="showNextDatePicker"
			mode="date" :min-time="form.date || ''"
			@confirm="showNextDatePicker = false" @cancel="showNextDatePicker = false" />
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import TnInput from '@/uni_modules/tuniaoui-vue3/components/input/src/input.vue'
import TnButton from '@/uni_modules/tuniaoui-vue3/components/button/src/button.vue'
import TnAvatar from '@/uni_modules/tuniaoui-vue3/components/avatar/src/avatar.vue'
import TnIcon from '@/uni_modules/tuniaoui-vue3/components/icon/src/icon.vue'
import TnPopup from '@/uni_modules/tuniaoui-vue3/components/popup/src/popup.vue'
import TnDateTimePicker from '@/uni_modules/tuniaoui-vue3/components/date-time-picker/src/date-time-picker.vue'

interface Pet {
	_id: string
	name: string
	species: string
	breed: string
	avatarUrl: string
	_displayAvatar?: string
}

interface RecordForm {
	petId: string
	type: string
	title: string
	date: string
	nextDate: string
	hospital: string
	doctor: string
	description: string
	vaccineName: string
	batchNumber: string
	dewormType: string
	brand: string
	diagnosis: string
}

const typeOptions = [
	{ value: 'vaccine', label: '疫苗', icon: 'safe-fill', color: '#3B82F6', bg: '#EFF6FF' },
	{ value: 'deworm',  label: '驱虫', icon: 'notice-fill', color: '#8B5CF6', bg: '#F5F3FF' },
	{ value: 'medical', label: '病历', icon: 'write-feather', color: '#F97316', bg: '#FFF7ED' },
	{ value: 'checkup', label: '体检', icon: 'data-fill', color: '#14B8A6', bg: '#F0FDFA' },
	{ value: 'other',   label: '其他', icon: 'inventory-fill', color: '#64748B', bg: '#F8FAFC' },
]

const typeLabelMap: Record<string, string> = {
	vaccine: '疫苗', deworm: '驱虫', medical: '病历', checkup: '体检', other: '其他',
}

const dewormOptions = [
	{ value: 'internal', label: '体内驱虫', icon: 'medicine', color: '#8B5CF6' },
	{ value: 'external', label: '体外驱虫', icon: 'cream-fill', color: '#EC4899' },
	{ value: 'both',     label: '体内外同驱', icon: 'loop', color: '#14B8A6' },
]

const dewormLabelMap: Record<string, string> = {
	internal: '体内驱虫', external: '体外驱虫', both: '体内外同驱',
}

const todayStr = computed(() => {
	const d = new Date()
	return `${d.getFullYear()}/${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')} 23:59:59`
})

const petList = ref<Pet[]>([])
const submitting = ref(false)
const safeBottom = ref(0)
const showPetPicker = ref(false)
const showTypePicker = ref(false)
const showDatePicker = ref(false)
const showNextDatePicker = ref(false)
const showDewormPicker = ref(false)
const costText = ref('')
const primaryButtonStyle = {
	background: 'linear-gradient(135deg, #F97316, #FB923C)',
}

const form = reactive<RecordForm>({
	petId: '',
	type: '',
	title: '',
	date: '',
	nextDate: '',
	hospital: '',
	doctor: '',
	description: '',
	vaccineName: '',
	batchNumber: '',
	dewormType: '',
	brand: '',
	diagnosis: '',
})

const selectedPetName = computed(() => {
	const pet = petList.value.find(p => p._id === form.petId)
	return pet?.name || ''
})

const canSubmit = computed(() => !!(form.petId && form.type && form.date))

onLoad((options: any) => {
	if (options?.type) {
		form.type = options.type
	}
	const sys = uni.getSystemInfoSync()
	safeBottom.value = sys.safeAreaInsets?.bottom || 0
	loadPets()
})

onShow(() => {
	loadPets()
})

async function loadPets() {
	try {
		const uid = uni.getStorageSync('uid')
		if (!uid) return
		const res = await uniCloud.callFunction({
			name: 'petManager',
			data: { action: 'list', uid },
		})
		if (res.result?.code === 0) {
			petList.value = (res.result.data || []) as Pet[]
			for (const pet of petList.value) {
				if (pet.avatarUrl?.startsWith('cloud://')) {
					try {
						const fileRes = await uniCloud.getTempFileURL({ fileList: [pet.avatarUrl] })
						pet._displayAvatar = fileRes.fileList?.[0]?.tempFileURL || ''
					} catch (e) { pet._displayAvatar = '' }
				} else {
					pet._displayAvatar = pet.avatarUrl || ''
				}
			}
			if (!form.petId && petList.value.length === 1) {
				form.petId = petList.value[0]._id
			}
		}
	} catch (e) {
		console.warn('加载宠物失败', e)
	}
}

function getSpeciesLabel(species: string) {
	const map: Record<string, string> = { dog: '狗狗', cat: '猫咪', bird: '鸟类', hamster: '仓鼠', rabbit: '兔子', fish: '鱼类' }
	return map[species] || ''
}

function getTypeLabel(type: string) {
	return typeLabelMap[type] || ''
}

function getDewormLabel(type: string) {
	return dewormLabelMap[type] || ''
}

function selectPet(id: string) {
	form.petId = id
	showPetPicker.value = false
}

function selectType(type: string) {
	form.type = type
	showTypePicker.value = false
	form.vaccineName = ''
	form.batchNumber = ''
	form.dewormType = ''
	form.brand = ''
	form.diagnosis = ''
}

function selectDeworm(type: string) {
	form.dewormType = type
	showDewormPicker.value = false
}

async function handleSubmit() {
	if (!canSubmit.value) return
	if (submitting.value) return
	submitting.value = true
	try {
		const uid = uni.getStorageSync('uid')
		const payload: any = {
			action: 'add',
			uid,
			pet_id: form.petId,
			type: form.type,
			date: form.date,
			title: form.title.trim(),
			nextDate: form.nextDate,
			hospital: form.hospital.trim(),
			doctor: form.doctor.trim(),
			description: form.description.trim(),
			cost: costText.value ? parseFloat(costText.value) : 0,
		}
		if (form.type === 'vaccine') {
			payload.vaccineName = form.vaccineName.trim()
			payload.batchNumber = form.batchNumber.trim()
			payload.brand = form.brand.trim()
		} else if (form.type === 'deworm') {
			payload.dewormType = form.dewormType
			payload.dewormBrand = form.brand.trim()
		} else if (form.type === 'medical') {
			payload.diagnosis = form.diagnosis.trim()
		}

		const res = await uniCloud.callFunction({ name: 'recordManager', data: payload })
		if (res.result?.code === 0) {
			uni.showToast({ title: '添加成功', icon: 'success' })
			setTimeout(() => uni.navigateBack(), 1200)
		} else {
			uni.showToast({ title: res.result?.message || '保存失败', icon: 'none' })
		}
	} catch (e) {
		console.error('保存记录失败', e)
		uni.showToast({ title: '保存失败，请重试', icon: 'none' })
	} finally {
		submitting.value = false
	}
}
</script>

<style lang="scss" scoped>
$primary: #F97316;
$primary-light: #FB923C;
$primary-bg: #FFF7ED;
$text-dark: #1E293B;
$text-body: #475569;
$text-muted: #94A3B8;
$card-bg: #FFFFFF;
$shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
$radius-lg: 24rpx;

.add-page {
	height: 100vh;
	background: #F8FAFC;
	display: flex;
	flex-direction: column;
}

.add-scroll {
	flex: 1;
	overflow: hidden;
}

.add-container {
	padding: 24rpx 28rpx 220rpx;
}

.form-section {
	margin-top: 32rpx;

	&:first-child {
		margin-top: 0;
	}
}

.section-title {
	font-size: 28rpx;
	font-weight: 700;
	color: $text-dark;
	margin-bottom: 16rpx;
	padding-left: 4rpx;
}

.form-card {
	background: $card-bg;
	border-radius: $radius-lg;
	box-shadow: $shadow;
	padding: 0 28rpx;
	overflow: hidden;
}

.form-row {
	display: flex;
	align-items: center;
	padding: 24rpx 0;
	gap: 12rpx;
	min-height: 88rpx;

	&.desc-row {
		align-items: flex-start;
		padding: 24rpx 0 32rpx;
	}
}

.form-divider {
	height: 1rpx;
	background: #F1F5F9;
}

.form-label {
	font-size: 28rpx;
	font-weight: 600;
	color: $text-dark;
	width: 112rpx;
	flex-shrink: 0;
}

.required::before {
	content: '*';
	color: #EF4444;
	margin-right: 4rpx;
}

.form-value {
	flex: 1;
	font-size: 28rpx;
	color: $text-dark;
	text-align: right;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.value-placeholder {
	color: #CBD5E1;
}

.cost-row {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	gap: 8rpx;
}

.cost-unit {
	font-size: 26rpx;
	color: $text-muted;
	flex-shrink: 0;
}

.bottom-bar {
	padding: 16rpx 28rpx;
	background: #FFFFFF;
	box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
}

/* 弹窗通用 */
.picker-panel {
	padding: 32rpx 28rpx 32rpx;
}

.panel-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 28rpx;
}

.panel-title {
	font-size: 32rpx;
	font-weight: 700;
	color: $text-dark;
}

.panel-close {
	width: 56rpx;
	height: 56rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.picker-scroll {
	max-height: 600rpx;
}

.picker-empty {
	padding: 60rpx 0;
	text-align: center;
	font-size: 28rpx;
	color: $text-muted;
}

/* 宠物选项 */
.pet-option {
	display: flex;
	align-items: center;
	padding: 20rpx 8rpx;
	gap: 20rpx;
	border-radius: 16rpx;

	&.pet-option-selected {
		background: #FFF7ED;
	}
}

.pet-option-avatar {
	flex-shrink: 0;
}

.pet-option-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 4rpx;
	min-width: 0;
}

.pet-option-name {
	font-size: 28rpx;
	font-weight: 700;
	color: $text-dark;
}

.pet-option-breed {
	font-size: 24rpx;
	color: $text-muted;
}

/* 类型选项网格 */
.type-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.type-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 12rpx;
	width: calc(33.33% - 14rpx);
	padding: 24rpx 0;
	border-radius: 20rpx;
	background: #F8FAFC;
	border: 2rpx solid #E2E8F0;

	&.type-item-selected {
		background: $primary-bg;
	}
}

.type-item-icon {
	width: 72rpx;
	height: 72rpx;
	border-radius: 18rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.type-item-label {
	font-size: 26rpx;
	font-weight: 600;
}

/* 驱虫选项 */
.deworm-options {
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.deworm-option {
	display: flex;
	align-items: center;
	padding: 24rpx 8rpx;
	gap: 16rpx;
	border-radius: 16rpx;

	&.deworm-selected {
		background: #F5F3FF;
	}
}

.deworm-label {
	flex: 1;
	font-size: 28rpx;
	color: $text-body;

	&.deworm-label-active {
		color: #8B5CF6;
		font-weight: 700;
	}
}
</style>
