<route lang="json5" type="page">
	{
	layout: 'default',
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '健康随访问卷',
	},
	}
</route>

<template>
	<PageLayout navTitle="健康随访问卷">
		<wd-form ref="form" :model="model">
			<wd-cell-group border>
				<view v-for="(item, index) in list" :key="index" class="question-item">
					<view class="question-text">{{ index + 1 }}. {{ item.tbnr }}</view>
					<wd-radio-group v-model="answers[item.id]" class="radio-group">
						<wd-radio value="是" class="radio-item">是</wd-radio>
						<wd-radio value="否" class="radio-item">否</wd-radio>
					</wd-radio-group>
				</view>
			</wd-cell-group>

			<view class="footer" v-if="list.length">
				<wd-button type="primary" size="large" block round @click="submitForm">提交问卷</wd-button>
			</view>
		</wd-form>
	</PageLayout>
</template>

<script setup>
	import {
		useToast
	} from 'wot-design-uni'
	import {
		querySfwtApi,
		editApi
	} from '@/api/politics/health'
	const toast = useToast()
	const model = ref({})
	const list = ref([])
	const answers = ref({}) // 用于存储所有问题的答案
	const allAnswered = computed(() => {
		return list.value.every(item => answers.value[item.id])
	})

	const getList = () => {
		querySfwtApi().then(res => {
			list.value = res.result
			if (res.result.length > 0) {
				// 检查是否已填写
				if (res.result.every(item => item.sf)) {
					toast.warning('本月问卷已提交!')
					setTimeout(() => {
						uni.navigateBack()
					}, 2000)
				}
				// 初始化答案对象
				answers.value = res.result.reduce((acc, item) => {
					acc[item.id] = ''
					return acc
				}, {})
			} else {
				toast.warning('未查询到本月随访问题!')
				setTimeout(() => {
					uni.navigateBack()
				}, 2000)
			}
		})
	}

	const submitForm = () => {
		if (!allAnswered.value) {
			toast.warning('请回答所有问题!')
			return
		}
		editApi({
			answers: answers.value
		}).then(res => {
			if (res.success) {
				toast.success('提交成功!')
				setTimeout(() => {
					uni.navigateBack()
				}, 2000)
			}
		})
	}

	onLoad(() => {
		/*获取随访问题*/
		getList()
	})
</script>

<style lang="scss" scoped>
	.question-item {
		padding: 20rpx 24rpx;
		border-bottom: 1rpx solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}
	}

	.question-text {
		font-size: 32rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 24rpx;
	}

	.radio-group {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.radio-item {
		flex: 1;

		:deep(.wd-radio__label) {
			font-size: 28rpx;
		}

		:deep(.wd-radio__button) {
			border-radius: 12rpx;
			padding: 16rpx 0;
			text-align: center;
			background: #f7f7f7;
			border: none;
			transition: all 0.3s;

			&.is-checked {
				background: #4b8df8;
				color: #fff;
			}
		}
	}

	.footer {
		padding: 12px;

	}
</style>